In my flutter project, I am getting some value by API call. I call the function inside my initState function and then save the result in a list.
Then, I have added the one TextField to make the search in my list. The search is working properly but the problem is - initially no items are shown in the list. If I type something or after typing I delete those text it's working.
Here's my code-
Inside the class I have added the following variables-
List<ModelAllNotes> _allNotes = List<ModelAllNotes>();
TextEditingController editingController = TextEditingController();
var items = List<ModelAllNotes>();
Inside the initState function I have called a function-
@override
void initState() {
setState(() {
_getAllNotes();
items.addAll(_allNotes);
});
}
Inside the _getAllNotes() function I have done the API calling part-
void _getAllNotes() {
Webservice().load(ModelAllNotes.allNotes).then( (allNotes) => {
setState(()=>{
_allNotes = allNotes
})
});
}
For filtering, the list while searching I have created a function for that-
void filterSearchResults(String query) {
List<ModelAllNotes> dummySearchList = List<ModelAllNotes>();
dummySearchList.addAll(_allNotes);
if(query.isNotEmpty) {
List<ModelAllNotes> dummyListData = List<ModelAllNotes>();
dummySearchList.forEach((item) {
if(item.title.contains(query)) {
dummyListData.add(item);
}
});
setState(() {
items.clear();
items.addAll(dummyListData);
});
return;
} else {
setState(() {
items.clear();
items.addAll(_allNotes);
});
}
}
Then inside the build function I have done the list showing part like below way-
@override
Widget build(BuildContext context) {
return new Scaffold(
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (value) {
filterSearchResults(value);
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
Expanded (
child: Container(
child: new ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
child: Container(
child: showCard(index),
),
onTap: (){
print('Card pressed');
Navigator.pushNamed(ctxt, '/DetailsNotes', arguments: items[index]).then((val)=>{_getAllNotes()});
},
),
)
);
}
),
),
)
],
)
);
After doing all these stuff it is showing the blank screen initially. When I type something in the search TextField it showing the list. So, I need a solution to show the list when the screen appears.