【发布时间】:2018-07-09 16:12:29
【问题描述】:
我正在创建一个无限滚动 listView,我想在 _loadNames 函数中使用 setState 将 _loadingState 字符串从“正在加载...”更改为“已加载”,但是当从 itemBuilder 调用 _loadNames 时,我得到“在构建错误期间调用 setState”。使用 RefreshIndicator 可以正常工作并更新项目,但滚动到底部会导致错误。我如何能够从 ListViews 构建器调用 _loadNames 而不会出现错误或我可以使用什么其他方法。
注意:不想使用 redux 或 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;
});
}
}
【问题讨论】: