Flutter Search Bar With ListView

In this article, you will learn how to integrate search bar with listview in flutter applications. In this example, we add our search bar in our app bar to filter listview data.

First of all we need to add search icon in actions property of scaffold app bar. Then we need to display search bar on click of search icon. We display popular soccer player names in listview. User can enter query in search bar using keyboard.

We display back arrow as leading in search bar and close button at the right side. User can clear all entered text using this close button. User can also close this search bar using back arrow and go to back screen.

We need to display suggestions from listview as soon as user enters text in search bar. For this we need to filter listview data according to user input.

 

Flutter Search Bar UI

final soccerPlayers = [ ‘Cristiano Ronaldo’, ‘Lionel Messi’, ‘Neymar Jr.’, ‘Kevin De Brune’, ‘Robert Lewandowski’, ‘Kylian Mbappe’, ‘Virgil van Dijk’, ‘Sadio Mane’, ‘Mohamed Salah’ ];

Scaffold(
    appBar: AppBar(
        actions: [
            IconButton(
                onPressed: () {
                    showSearch( context: context, delegate: PlayerSearch(soccerPlayers));
                },
                icon: Icon(Icons.search),
            )
        ],
        centerTitle: true,
        title: Text(‘Search Bar Sample’),
    ),
    body: ListView.builder(
        itemCount: soccerPlayers.length,
        itemBuilder: (context, position) => ListTile(
            title: Text(soccerPlayers[position]),
        )
    ),
);
 
 

Create Search Delegate Class

We create a class inherited from SearchDelegate class and override four methods buildActions(), buildLeading(), buildResults() and buildSuggestions().

buildActions() method returns UI widgets. So we can add close button in this method. So we can clear text query text.

@override
List<Widget> buildActions(BuildContext context) {
return <Widget>[
    IconButton(
        icon: Icon(Icons.close),
        onPressed: (){
            query = “”;
        }
    )
];
}
 

buildLeading() method displays back button as leading in search bar. We can go back to previous screen using this back button.

@override
Widget buildLeading(BuildContext context) {
return IconButton(
    icon: Icon(Icons.arrow_back),
    onPressed: (){
        Navigator.pop(context);
    });
}
 

buildResults() method displays textfield which is used to filter listview data.

@override Widget buildResults(BuildContext context) {
return Container(
    child: Center(
        child: Text(selectedResult),
    ),
);
}
 

buildSuggestions() method displays listview data after it is filtered according to user entered query in textfield.

@override
Widget buildSuggestions(BuildContext context) {
List<String> suggestedSoccerPlayers = [];
query.isEmpty ? suggestedSoccerPlayers = soccerPlayers
: suggestedSoccerPlayers.addAll(soccerPlayers.where(
    (element) => element.toLowerCase().contains(query.toLowerCase()),
));

return ListView.builder(
    itemCount: suggestedSoccerPlayers.length,
    itemBuilder: (context, position) => ListTile(
        title: Text(suggestedSoccerPlayers[position]),
    )
);
}
 
 

Final Code

 

main.dart

import 'package:flutter/material.dart';
import 'package:fluttersearchbarlsample/my_search_bar_sample.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MySearchBarScreen(),
    );
  }
}
 

my_search_bar_screen.dart

import 'package:flutter/material.dart';
import 'package:fluttersearchbarlsample/player_search.dart';

class MySearchBarScreen extends StatefulWidget {
  @override
  _MySearchBarScreenState createState() => _MySearchBarScreenState();
}

class _MySearchBarScreenState extends State<MySearchBarScreen> {
  final soccerPlayers = [
    'Cristiano Ronaldo',
    'Lionel Messi',
    'Neymar Jr.',
    'Kevin De Brune',
    'Robert Lewandowski',
    'Kylian Mbappe',
    'Virgil van Dijk',
    'Sadio Mane',
    'Mohamed Salah'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: () {
              showSearch(
                  context: context, delegate: PlayerSearch(soccerPlayers));
            },
            icon: Icon(Icons.search),
          )
        ],
        centerTitle: true,
        title: Text('Search Bar Sample'),
      ),
      body: ListView.builder(
          itemCount: soccerPlayers.length,
          itemBuilder: (context, position) => ListTile(
                title: Text(soccerPlayers[position]),
              )),
    );
  }
}
 

player_search.dart

import 'package:flutter/material.dart';

class PlayerSearch extends SearchDelegate{

  List<String> soccerPlayers;
  String selectedResult;

  PlayerSearch(this.soccerPlayers);

  @override
  List<Widget> buildActions(BuildContext context) {
    return <Widget>[
      IconButton(
          icon: Icon(Icons.close),
          onPressed: (){
        query = "";
      })
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
      return IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: (){
            Navigator.pop(context);
          });
  }

  @override
  Widget buildResults(BuildContext context) {
      return Container(
        child: Center(
          child: Text(selectedResult),
        ),
      );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
      List<String> suggestedSoccerPlayers = [];
      query.isEmpty ? suggestedSoccerPlayers = soccerPlayers
          : suggestedSoccerPlayers.addAll(soccerPlayers.where(
            (element) => element.toLowerCase().contains(query.toLowerCase()),
      ));

      return ListView.builder(
          itemCount: suggestedSoccerPlayers.length,
          itemBuilder: (context, position) => ListTile(
            title: Text(suggestedSoccerPlayers[position]),
          ));
  }

}
 
 
 
 
flutter search bar
 

Leave a Reply