Skip to content

ebrarbilgili/flutter-search-delegate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Ekran.Kaydi.2021-05-19.15.56.49.mov

HOW TO DO

We will create our atomic ListView:

class ListViewWidget extends StatelessWidget {
  const ListViewWidget({Key? key, required this.list}) : super(key: key);

  final List<UserModel> list;

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (BuildContext context, int index) => buildCard(index),
    );
  }

  Card buildCard(int index) {
    final user = list[index];
    return Card(
      child: ListTile(
        leading: Text(user.id.toString()),
        title: Text(user.name ?? 'user'),
      ),
    );
  }
}

and then we will create our Search Class with Search Delegate:

class UserSearch extends SearchDelegate<UserModel> {
  final List<UserModel> users;
  UserSearch({required this.users});

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

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

  @override
  Widget buildResults(BuildContext context) {
    return ListViewWidget(list: searchList);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return ListViewWidget(list: searchList);
  }

  List<UserModel> get searchList {
    return users
        .where(
          (element) =>
              element.name!.toLowerCase().contains(query.toLowerCase()),
        )
        .toList();
  }
}

builActions and buildLeading are our Buttons because we may need to make delete our searching or navigate to back. buildResults and buildSuggestions are our Searching List when we searched something.

Let's call on appbar:

AppBar(
      title: Text('User Search Demo'),
      actions: [
        IconButton(
          onPressed: () {
            showSearch(
              context: context,
              delegate: UserSearch(users: list),
            );
          },
          icon: Icon(Icons.search),
        ),
      ],
    )

Aaaanndd it is done!