ListView with search in Flutter
Hi Friends, today lets see how to implement a ListView with search bar . So first i am going to create a new dart file named HomePage.dart which extends StatefulWidget
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
StatefulWidget are mutable by nature where we want to change our widgets for multiple times we make use of this StatefulWidget
So first i am creating List of items as below and we have two override method one is initState and another is build. So initState → will be called at the first time when the screen loads and build where we create our UI.
class _HomePageState extends State<HomePage> {
List<String> items = ["First Name",
"Second Name",
"Third Name",
"Fourth Name"];@override
void initState() {
super.initState();
}@override
Widget build(BuildContext context) {
return Scaffold()
}
}
So the next step is am creating an duplicate list so we can perform filter on that instead on orginal list so the duplicate list name is _searchedItems which has the same value of items.
List<String> items = ["First Name",
"Second Name",
"Third Name",
"Fourth Name"];
List<String> _searchedItems = [];
@override
void initState() {
super.initState();
setState(() {
_searchedItems = items;
});
}
So next I have created a filter method to filter list based on input from Textformfield. So if the text is empty we will be taking the actual items else check contains and map it to results list. At last we are setting to _searchedItems = results;
void filter(String searchText) {
List<String> results = [];
if(searchText.isEmpty) {
results = items;
} else {
results = items.where((element) => element.toLowerCase().contains(searchText.toLowerCase())).toList();
}
setState(() {
_searchedItems = results;
});
}
So lets focus on UI Part we are creating an ListView.builder with TextFormField
TextFormField code is pasted below
TextFormField(onChanged: (value) {
filter(value);
},
decoration: InputDecoration(
labelText: "Search",
labelStyle: TextStyle(
color: Colors.black
)
),
)
And For ListView.builder the itemCount take size of list and the itemBuilder holds context with index and return the Text.
Expanded(
child: ListView.builder(
itemCount: _searchedItems.length,
itemBuilder: (context,index) {
final name = _searchedItems[index];
return Text(name);
})
)
I am going to paste the final code of HomePage.dart
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<String> items = ["First Name",
"Second Name",
"Third Name",
"Fourth Name"];
List<String> _searchedItems = [];
@override
void initState() {
super.initState();
setState(() {
_searchedItems = items;
});
}
void filter(String searchText) {
List<String> results = [];
if(searchText.isEmpty) {
results = items;
} else {
results = items.where((element) => element.toLowerCase().contains(searchText.toLowerCase())).toList();
}
setState(() {
_searchedItems = results;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: Column(
children: [
TextFormField(onChanged: (value) {
filter(value);
},
decoration: InputDecoration(
labelText: "Search",
labelStyle: TextStyle(
color: Colors.black
)
),
),
Expanded(
child: ListView.builder(
itemCount: _searchedItems.length,
itemBuilder: (context,index) {
final name = _searchedItems[index];
return Text(name);
})
)
],
),
),
),
);
}
}
And dont forget to call it from main.dart
import 'package:flutter/material.dart';
import 'HomePage.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const HomePage(),
);
}
}
Final Output: