Easy Ways to Create a ListView Search Feature in Flutter

Easy Ways to Create a ListView Search Feature in Flutter
Hello everyone, back at porkaone. We all love programming blogs. This time we will discuss various ways to create a search form and display search results in flutter. Curious?, let's follow in full below.


Stateful widgets are very useful for creating applications that have reactive changes. Well this time I will discuss how to use stateful widgets in the case study "how to create a search form".

So in this tutorial we will display data on the names of people, then in the appbar section there is a search icon, if you click it it will bring up a search form. This search will work reactively, every time a letter is typed, the data list will also change.



How to Create a Search Form and Its Functions in Flutter

1. Create a new project in visual studio code with the name "latihan_pencarian".

2. Create a new file in the lib folder, and name it data.dart. Copy the script below and paste it. So we will use the script below as the data source later.
    

List<String> items = [ "Morgan Schultz", "Kassidy Zamora", "Dakota Lester", "Mauricio Estes", "Anton Fowler", "Angelique Cortez", "Michaela Flowers", "Zaiden Cohen", "Tomas Morrison", "Madeleine Carney", "Kaydence Trujillo", "Zion Dickson", "Laney Scott", "Kyleigh Jordan", "Teagan Roach", "Gilbert Rodgers", "Jaylan Ferrell", "Harley Fry", "Brittany Dickson", "Paulina Stanton", "Tyrell Delgado", "Brayden Conner", "Erin Stewart", "Justus Buck", "Jaycee Hancock", "Landon Hutchinson", "Maxim Schmitt", "Aaron Mccarthy", "Mikaela West", "Alexis Wolf", "Isabel Norman", "Delilah Bishop", "Brock Michael", "Aldo Brady", "Renee Harrell", "Conrad Reed", "Griffin Huerta", "Aditya Morgan", "Raegan Prince", "Rayna Curry", ];

3. Open main.dart and replace its contents with the script below. For the explanation, I have included it in the script and I will breakdown it.

    

    // ignore_for_file: use_key_in_widget_constructors, prefer_final_fields, prefer_const_constructors, avoid_function_literals_in_foreach_calls import 'package:flutter/material.dart'; import 'data.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: LatihanPencarian(), ); } } class LatihanPencarian extends StatefulWidget { @override _LatihanPencarianState createState() => _LatihanPencarianState(); } class _LatihanPencarianState extends State<LatihanPencarian> { //to control the textfield when there is a change TextEditingController _controllerSearch = TextEditingController(); //this widget type data initially we create text //but when there is a change this data will turn into a form and vice versa into text Widget? searchTextField = Text("List Users"); //if flase, then display the search icon //if true, then show arrow icon and close bool search = false; Color _bgColor = Colors.green; List list = []; @override void initState() { super.initState(); //when this file is run for the first time //then the data list will be filled with data from data.dart list.addAll(items); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: _bgColor, //title originally was text title: searchTextField, actions: <Widget>[ //if search is false then display the search icon //if search is true then display icon close (search == false) ? IconButton( icon: Icon(Icons.search), onPressed: () { setState(() { searchTextField = appSearch(context); _bgColor = Colors.white; search = true; }); }) : IconButton( icon: Icon( Icons.close, color: Colors.black, ), onPressed: () { setState(() { list.clear(); list.addAll(items); _controllerSearch.clear(); }); }) ], ), body: ListView.builder( itemCount: list.length, itemBuilder: (context, int index) { return ListTile( title: Text( list[index], style: TextStyle(fontSize: 18), ), ); }, ), ); } //when the search icon is run then this widget will be run //This widget is a form. Widget appSearch(BuildContext context) { return TextField( controller: _controllerSearch, style: TextStyle(color: Colors.black, fontSize: 18), decoration: InputDecoration( icon: IconButton( icon: Icon( Icons.arrow_back, color: Colors.black, ), onPressed: () { setState(() { searchTextField = Text("List Users"); search = false; _bgColor = Colors.green; _controllerSearch.clear(); list.clear(); list.addAll(items); }); }), hintText: "Search", hintStyle: TextStyle(color: Colors.grey)), // every time there is a change, run the function _searchName onChanged: (name) { _searchName(name); }, ); } //this function will be run every time you type //this function will search for the name as typed _searchName(String name) { if (name.isNotEmpty) { setState(() { list.clear(); //do loops items.forEach((item) { //if there is a data list that contains the arrangement of the letters you are looking for //then enter it into the data list if (item.toLowerCase().contains(name.toLowerCase())) { list.add(item); } }); }); } else { setState(() { list.clear(); list.addAll(items); }); } } }

4. Open your emulator, then run the application. You can see the result as shown in the image below.

Membuat Form Pencarian di Flutter
Hasil Akhir



BerakDown Explanation of the Script Above

1. We initially use the script below to initialize the initial state. Where the initial state of the application that we built has a green appbar with the words List Users, then there is a search icon in the right corner of the appbar. All this data will change later according to their respective circumstances.
    

//to control the textfield when there is a change TextEditingController _controllerSearch = TextEditingController(); //This widget type data initially we create text. //but when there is a change this data will turn into a form and vice versa into text Widget? searchTextField = Text("List Users"); //if false then display the search icon //if true then show arrow icon and close bool search = false; Color _bgColor = Colors.green; List list = []; @override void initState() { super.initState(); //when this file is run for the first time //then the data list will be filled with data from data.dart list.addAll(items); }



2. We use this script to create the appbar. If the search value is false then display the search icon, and if true then display the close icon. We also set the setState when the search icon and close icon are pressed. When the search icon is pressed, the searchTextField will change to an appsearch widget, and if the close icon is pressed, the searchTextField will change to List Users again.
    

appBar: AppBar(     backgroundColor: _bgColor, //title originally was text title: searchTextField, actions: <Widget>[     //if search is false then display the search icon //if search is true then display icon close (search == false) ? IconButton(     icon: Icon(Icons.search), onPressed: () {     setState(() {     searchTextField = appSearch(context); _bgColor = Colors.white; search = true; }); }) : IconButton(     icon: Icon(     Icons.close,     color: Colors.black, ), onPressed: () {     setState(() {     list.clear(); list.addAll(items); _controllerSearch.clear(); }); }) ], ),



3. We use this widget to create a search form in the appbar. We make it separately because it looks a little complicated. Broadly speaking we create a fairly simple textfield. This widget will run if the search data is false.
    

//when the search icon is run then this widget will be run //This widget is a form. Widget appSearch(BuildContext context) { return TextField( controller: _controllerSearch, style: TextStyle(color: Colors.black, fontSize: 18), decoration: InputDecoration( icon: IconButton( icon: Icon( Icons.arrow_back, color: Colors.black, ), onPressed: () { setState(() { searchTextField = Text("List Users"); search = false; _bgColor = Colors.green; _controllerSearch.clear(); list.clear(); list.addAll(items); }); }), hintText: "Search", hintStyle: TextStyle(color: Colors.grey)), // every time there is a change, run the function _searchName onChanged: (name) { _searchName(name); }, ); }



4. This function will be executed when there is a change in the textfield. When you do typing, the data list will adjust. With what you're looking for.

//this function will be run every time you type //this function will search for the name as typed _searchName(String name) { if (name.isNotEmpty) { setState(() { list.clear(); //do loops items.forEach((item) { //if there is a data list that contains the arrangement of the letters you are looking for //then enter it into the data list if (item.toLowerCase().contains(name.toLowerCase())) { list.add(item); } }); }); } else { setState(() { list.clear(); list.addAll(items); }); } }



Cool!, now you can create a reactive search form using dummy data. Then you can improvise using dynamic api data.

That's it for this tutorial on how to create a search form and its functions in Flutter. May be useful. If there are difficulties, please ask in the comments column. That's all and see you in another cool tutorial.



Post a Comment

0 Comments