Reputation: 9581
I'm Creating an infinite scroll listView and i want to change the _loadingState
String from 'loading...' to 'loaded' using setState in the _loadNames
function, but when _loadNames is called from itemBuilder
, I get the 'setState called during build error'.Using the RefreshIndicator works fine and updates the items, but scrolling to the bottom causes the error. How can i be able to call _loadNames from the ListViews builder without getting an error or what other approach can i use.
NB: Dont want to use redux or bloc.
class _HomePageState extends State<HomePage> {
List<String> names = [];
List<String> _shownNames = [];
int currentPage = 0;
int limit = 20;
String _loadingState = 'loading';
bool loading = true;
@override
void initState() {
super.initState();
for (int i = 0; i < 200; i++) {
names.add("hello $i");
}
_loadNames();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: new AppBar(title: new Text('User')),
body: Column(children: <Widget>[
Text(_loadingState),
Expanded(child:_getListViewWidget()),
],)
);
}
Widget _getListViewWidget(){
ListView lv = new ListView.builder(
itemCount: _shownNames.length,
itemBuilder: (context, index){
if(index >= _shownNames.length - 5 && !loading){
_loadNames(); // Getting error when this is called
}
return ListTile(
title: Text(_shownNames[index]),
);
});
RefreshIndicator refreshIndicator = new RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: (){
_loadNames();
return null;
},
child: lv
);
return refreshIndicator;
}
_loadNames(){
loading = true;
setState(() {
_loadingState = 'loading...';
});
new Timer(const Duration(seconds: 5), () {
setState(() {
_shownNames.addAll(names.getRange(currentPage, currentPage + limit));
currentPage += limit;
_loadingState = 'loaded';
});
loading = false;
});
}
}
Upvotes: 3
Views: 2475
Reputation: 657108
Change _loadNames() {
to
_loadNames(){
loading = true;
// setState(() {
_loadingState = 'loading...';
// });
and
onRefresh: (){
_loadNames();
return null;
},
to
onRefresh: (){
setState(() => _loadNames());
},
update
_loadNames(){
loading = true;
new Future.delayed(Duration.zero, () => setState(() {
_loadingState = 'loading...';
}));
Upvotes: 5