Reading Time: < 1 minute
To create a search bar and filter a list, follow these simple steps:
The list of elements we will display and filter is as follows:
List<dynamic> tutorsData = [ { "name": "Maria", "email": "example1_devcodelight@email.com", "phone": "1234567890" }, { "name": "Laura", "email": "example2_devcodelight@email.com", "phone": "1234567890" }, { "name": "Isma", "email": "example3_devcodelight@email.com", "phone": "1234567890" }, ]; List<dynamic> filteredList = []; TextEditingController _controller = TextEditingController();
Next, you need to create the design for the search bar:
TextField( controller: _controller, cursorColor: Colors.black, decoration: InputDecoration( prefixIcon: Icon( CupertinoIcons.search, color: Colors.black, ), border: InputBorder.none, hintText: Traducir.of(context)!.translate('buscar'), ), onChanged: (text) { filterList(text); // Call the filtering function when the text changes }, )
Finally, add the method that performs the filtering, in this case, it is called filterList:
void filterList(String text) { setState(() { tutorsData = filteredList .where((tutor) => tutor['name'] .toString() .toLowerCase() .contains(text.toLowerCase())) .toList(); }); }
I hope this helps. Have a great day.