I’m having a problem with the search bar. I typed the text I wanted to search into the search box but found nothing appeared even though the text was displayed in the normal ListView builder. Before I tried refactoring the code because I was stuck with the search bar. It doesn’t work (not showing search results), but my ListView builder works fine.
enter image description here
class _view_problemState extends State<view_problem> {
TextEditingController _searchController = TextEditingController();
List<problemModel> problemlist = [];
List<problemModel> originalList = [];
StreamController _streamController = StreamController();
Future getAllProblem() async {
problemlist = await problemcontrollers().getProblem();
originalList = problemlist;
_streamController.sink.add(problemlist);
}
@override
void initState() {
getAllProblem();
super.initState();
}
void _filterSearch(String query) {
List<problemModel> filteredList = [];
for (var item in originalList) {
if (item.toString().contains(query.toString())) {
filteredList.add(item);
}
}
setState(() {
problemlist = filteredList;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 14, 12, 134),
title: const Text('search'),
),
body: Container(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (value) {
_filterSearch(value);
},
controller: _searchController,
decoration: InputDecoration(
labelText: "search",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
Expanded(
child: StreamBuilder(
stream: _streamController.stream,
builder: (context, snapshots) {
if (snapshots.hasData) {
return ListView.builder(
itemCount: problemlist.length,
itemBuilder: ((context, index) {
problemModel problem = problemlist[index];
return Card(
margin: EdgeInsets.all(10),
child: ListTile(
title: Text(
problem.name_surname,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 19),
),
subtitle: Text(
problem.area,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 17),
),
),
);
}));
}
return Center(
child: CircularProgressIndicator(),
);
},
),
)
],
),
),
);
}
}
>Solution :
void _filterSearch(String query) {
List<problemModel> filteredList = [];
for (var item in originalList) {
if (item.name_surname.toLowerCase().contains(query.toString())) {
filteredList.add(item);
}
}
setState(() {
problemlist = filteredList;
});
}