Building a Searchable List in Flutter using ListView Widget
2 May, 2023
14
14
3
Contributors
Introduction
Hey everyone, I am Hasnain Makada and I am currently working as a Rotational Super Writer at Showwcase where I produce high-quality content on tech and make it understandable in a simple for my community. Today in this blog, I will show you how you can implement search functionality inside the ListView widget where you can filter out a specific ListTile based on your specific search query.
Flutter search in ListView is a powerful and essential functionality to have in any app that deals with large amounts of data. In this blog post, we will guide you through the process of implementing search functionality in a Flutter app using ListView. We will cover each step in detail, including creating a list of items, adding a search bar, and filtering the list based on user input. By the end of this tutorial, you will have a better understanding of how to implement a search feature in your Flutter app and improve the user experience of your app.
So without wasting any furthermore time, Let's get started 🔥
Setting up the Flutter App
Before starting out with Flutter, make sure you have Flutter installed on your machine.
Create a new flutter project inside your machine by running the below command 👇
flutter create <project_name>
After setting up the project successfully, add the Faker dependency inside your app to generate random data for testing purposes.
Now open your Flutter project inside any of your code editors and go to the main.dart
file.
The Searching Code
Now Remove the boilerplate code generated by Flutter and paste the code below 👇
import 'package:faker/faker.dart';
import 'package:flutter/material.dart';
void main() {
var faker = Faker();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const SearchScreen(),
);
}
}
class SearchScreen extends StatefulWidget {
const SearchScreen({super.key});
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
List<String> items = List.generate(50, (index) => faker.food.dish());
List<String> filteredItems = [];
String _query = '';
void search(String query) {
setState(
() {
_query = query;
filteredItems = items
.where(
(item) => item.toLowerCase().contains(
query.toLowerCase(),
),
)
.toList();
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
style: const TextStyle(color: Colors.white),
onChanged: (value) {
search(value);
},
decoration: const InputDecoration(
hintText: 'Search...',
hintStyle: TextStyle(color: Colors.white),
fillColor: Colors.white,
prefixIcon: Icon(
Icons.search,
color: Colors.white,
),
),
),
),
body: filteredItems.isNotEmpty || _query.isNotEmpty
? filteredItems.isEmpty
? const Center(
child: Text(
'No Results Found',
style: TextStyle(fontSize: 18),
),
)
: ListView.builder(
itemCount: filteredItems.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(filteredItems[index]),
);
},
)
: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
);
}
}
Let's break down the above code step by step,
- Importing required packages
The first thing this code does is importing the required packages, which are faker
for generating random data, and flutter/material.dart
for building UIs in Flutter.
- Generating random data
The main()
function initializes a faker
instance, which is used to generate random data. Specifically, it generates a list of 50 food dishes, which are stored in the items
list using the List.generate()
method.
- Building the UI
The MyApp
class is a stateless widget that builds the UI for the app. It returns a MaterialApp
widget, which is the root widget of the app. It sets the app's title and theme and sets the SearchScreen
widget as the home screen of the app.
- Building the search screen
The SearchScreen
class is a stateful widget that builds the search screen. It has two properties, items
and filteredItems
, which are both lists of strings. The items
list contains all the food dishes, and the filteredItems
list is used to store the filtered list of dishes based on the user's search query. It also has a _query
property, which stores the user's search query.
- Implementing search functionality
The search()
method takes a query
parameter, updates the _query
property with the search query, and filters the items
list based on the search query. The filtered items are stored in the filteredItems
list.
- Building the app bar
The build()
method of the SearchScreen
widget builds the UI for the search screen. It returns a Scaffold
widget, which has an AppBar
with a TextField
widget as the title. The TextField
widget has a prefix icon of a search icon and a hint text of "Search...". It also calls the search()
method whenever the user types in the search bar.
- Building the body
The body
of the Scaffold
widget is a ListView.builder()
widget, which builds a list of ListTile
widgets based on the items
or filteredItems
list. If the user has not typed anything in the search bar, the entire list of food dishes is displayed. If the user types a search query, the filteredItems
list is displayed. If the filteredItems
list is empty, a Center
widget with a text of "No Results Found" is displayed instead.
So that's all that the code does, now let's see the output.
The Final Output
Here is the output of the above code which we discussed 👇
As you can clearly see from the output, we're getting a random list of data from the faker package and when we try to provide any invalid query, we're getting no results found. Similarly, you can apply this search functionality anywhere when you're getting a bunch of data from API(s). But do keep in mind when building complex apps, use state-management solutions such as Riverpod and Provider so you can keep the state similar all over your app.
This was just a demo where I used the setState
method to implement the search functionality.
FAQ's
- What is search functionality in a Flutter app?
Search functionality allows users to quickly find specific data or information from a large set of data by typing a keyword or phrase in the search bar.
- How to implement search functionality in a Flutter app?
To implement search functionality in a Flutter app, we can use a combination of widgets such as TextField
, ListView
, and StatefulWidget
to create a search bar and display filtered results based on user input.
- How to filter data in a Flutter app?
We can filter data in a Flutter app using the where()
method on a list. This method takes a callback function as an argument and returns a new list with only the elements that match the condition specified in the callback function.
- How to update the search results dynamically in a Flutter app?
We can update the search results dynamically in a Flutter app by using the setState()
method to update the state of the widget tree whenever the user enters a new search query.
- Are there any third-party libraries available for implementing search functionality in a Flutter app?
Yes, there are several third-party libraries available for implementing search functionality in a Flutter app, such as flutter_search_bar
, search_widget
, searchable_dropdown
, and flappy_search_bar
. These libraries provide pre-built widgets and UI components that can be easily integrated into your Flutter app.
Conclusion
In this blog post, we discussed the basic steps for implementing search functionality in a Flutter app, including creating a list of items, adding a text input field, and filtering the list based on the user's input.
If you have any further doubts regarding this tutorial, feel free to reach out on Twitter and Showwcase.
Till then, Happy Coding 😃
flutter
listview
setstate
fluttersearchinlistview