I have a flutter application that gets a list of users online and it displays the data in a listview. I have tried to implement a search function to search through the data, however every time I try to type anything in the textfield, the whole page refreshes and performs an api call to fetch the data again. This is the code for getting and displaying the data
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Prospect List"),
centerTitle: true,
),
body: prospectData(),
);
}
Widget prospectData() {
return FutureBuilder(
future: _fetchData(),
builder: (BuildContext context, AsyncSnapshot<ProspectList> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.done:
if (snapshot.hasError)
return Text("There was an error: ${snapshot.error}");
prospectList = snapshot.data;
return ListView.builder(
itemCount: prospectList.data.length + 1,
itemBuilder: (context, i) {
if (prospectList.data.length > 0) {
return i == 0 ? _searchBar() : _prospectData(i - 1);
} else {
return Center(child: CircularProgressIndicator());
}
},
);
default:
return null;
}
});
}
_prospectData(i) {
final name =
prospectList.data[i].firstname + " " + prospectList.data[i].lastname;
final phone = prospectList.data[i].phone;
final email = prospectList.data[i].email;
return ListTile(
title: Text(
name,
style: TextStyle(fontSize: 18),
),
subtitle: Text(
phone,
style: TextStyle(fontSize: 16),
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CustomerInfo(
name: name,
phone: phone,
email: email,
))),
);
}
This is the search method I tried to implement but does not work properly
_searchBar() {
return Container(
child: Padding(
padding: EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(hintText: 'Search...'),
onChanged: (text) {
text = text.toLowerCase();
setState(() {
_prospectDisplay = prospectList.data.where((post) {
var postTitle = post.firstname.toLowerCase();
return postTitle.contains(text);
}).toList();
});
})),
);
}
EDIT I found the solution I was looking for Here
