How to create a Filter/Search ListView in Flutter (2022)Last updated on January 4, 2022 A Goodman Loading... Loading... 13 comments Working with ElevatedButton in Flutter (2022) January 4, 2022 Flutter: ListTile examples July 29, 2021 Flutter: GridView.builder() Example October 14, 2021 Flutter: Add a Search Field to an App Bar (2 Approaches) August 10, 2021 Most Popular Packages for State Management in Flutter (2022) January 1, 2022 How to read data from local JSON files in Flutter October 27, 2021 Flutter: ListView Pagination (Load More) example August 2, 2021 Flutter ListView.builder() example October 14, 2021 More This article is about making a filter/search ListView in Flutter. We will take a quick look at the approach to get the job done then go through a concrete and complete example of applying that approach. No third-party packages are required. Table of Contents
OverviewWe will create a function to filter the results and this function will be called when the text field changes (onChanged). The search algorithm can be different on a case-by-case basis, but the simplest and most popular is to use the following Dart methods:Advertisements
These words can be confusing. See the example for more clarity. ExampleLets say we have a list of users with some information including id, name, and age. In the beginning, all of these users are shown in a ListView. If you type something into the search field, only users whose names match the keyword will be displayed. If you clear the search field, the full list of users will appear again. PreviewThe CodeThe full source code in lib/main.dart with explanations in the comments (this code was updated to work properly with the latest version of Flutter): // main.dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( // Remove the debug banner debugShowCheckedModeBanner: false, title: 'Kindacode.com', home: HomePage(), ); } } class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { // This holds a list of fiction users // You can use data fetched from a database or a server as well final List<Map<String, dynamic>> _allUsers = [ {"id": 1, "name": "Andy", "age": 29}, {"id": 2, "name": "Aragon", "age": 40}, {"id": 3, "name": "Bob", "age": 5}, {"id": 4, "name": "Barbara", "age": 35}, {"id": 5, "name": "Candy", "age": 21}, {"id": 6, "name": "Colin", "age": 55}, {"id": 7, "name": "Audra", "age": 30}, {"id": 8, "name": "Banana", "age": 14}, {"id": 9, "name": "Caversky", "age": 100}, {"id": 10, "name": "Becky", "age": 32}, ]; // This list holds the data for the list view List<Map<String, dynamic>> _foundUsers = []; @override initState() { // at the beginning, all users are shown _foundUsers = _allUsers; super.initState(); } // This function is called whenever the text field changes void _runFilter(String enteredKeyword) { List<Map<String, dynamic>> results = []; if (enteredKeyword.isEmpty) { // if the search field is empty or only contains white-space, we'll display all users results = _allUsers; } else { results = _allUsers .where((user) => user["name"].toLowerCase().contains(enteredKeyword.toLowerCase())) .toList(); // we use the toLowerCase() method to make it case-insensitive } // Refresh the UI setState(() { _foundUsers = results; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Kindacode.com'), ), body: Padding( padding: const EdgeInsets.all(10), child: Column( children: [ const SizedBox( height: 20, ), TextField( onChanged: (value) => _runFilter(value), decoration: const InputDecoration( labelText: 'Search', suffixIcon: Icon(Icons.search)), ), const SizedBox( height: 20, ), Expanded( child: _foundUsers.isNotEmpty ? ListView.builder( itemCount: _foundUsers.length, itemBuilder: (context, index) => Card( key: ValueKey(_foundUsers[index]["id"]), color: Colors.amberAccent, elevation: 4, margin: const EdgeInsets.symmetric(vertical: 10), child: ListTile( leading: Text( _foundUsers[index]["id"].toString(), style: const TextStyle(fontSize: 24), ), title: Text(_foundUsers[index]['name']), subtitle: Text( '${_foundUsers[index]["age"].toString()} years old'), ), ), ) : const Text( 'No results found', style: TextStyle(fontSize: 24), ), ), ], ), ), ); } }AdvertisementsActually, we dont need a TextEditingController in this case. ConclusionYouve learned how to create a filter/search ListView in Flutter. At this point, you should get a better understanding and become more comfortable when dealing with this task or something similar to it. Continue exploring list view and other interesting stuff by taking a look at the following articles:
You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.Advertisements Advertisements Share Tweet Telegram Subscribe Notify of I allow to use my email address and send notification about new comments and replies (you can unsubscribe at any time). Label {} [+] Name* Email* Label {} [+] Name* Email* 13 Comments Inline Feedbacks View all comments rew 1 month ago How do we apply to Api 0 Reply Author A Goodman 1 month ago Reply to rew There are 2 common approaches: 0 Reply Bagas Galang Bijaky 1 month ago gracias 0 Reply Author A Goodman 1 month ago Reply to Bagas Galang Bijaky eres bienvenido 0 Reply nova 1 month ago Sir, can I ask you this one question? Ummm is there any way that I can add the filter to this searching system? 0 Reply Author A Goodman 1 month ago Reply to nova Do you mean a detailed search system? Yes, you can, but it may need some extra work. 0 Reply Nursultan 2 months ago Спасибо! 0 Reply Author A Goodman 2 months ago Reply to Nursultan Youre welcome 0 Reply mahdi 4 months ago tank you bro 0 Reply Ricardo 6 months ago Genial..!!! 0 Reply Ghina Sharaf 6 months ago Thank you 0 Reply Klaus 7 months ago Thank you! I am a beginner and have looked for this example. 0 Reply HHH 9 months ago As always, thank you. 0 Reply Related ArticlesBest Libraries for Making HTTP Requests in Flutter (2022) January 7, 2022 Dart: Convert Class Instances (Objects) to Maps and Vice Versa January 7, 2022 Creating Masonry Layout in Flutter with Staggered Grid View January 7, 2022 Flutter: Creating Custom Back Buttons December 28, 2021 Flutter: Creating an Auto-Resize TextField December 28, 2021 Flutter: Columns with Percentage Widths December 28, 2021 Flutter & Hive Database: CRUD Example (2022) January 7, 2022 Flutter: Text with Read More / Read Less Buttons December 24, 2021 Flutter: Making a Dropdown Multiselect with Checkboxes December 24, 2021 Using Stepper widget in Flutter: Tutorial & Example December 23, 2021 Using Provider for State Management in Flutter (2022) December 25, 2021 Using BlockSemantics in Flutter: Tutorial & Example December 21, 2021 |