我正在创建一个无限滚动listView,并且我想使用_loadNames函数中的setState将_loadingState字符串从’loading …’更改为’loaded’,但是当从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;
});
}
}
解决方法:
更改_loadNames(){
至
_loadNames(){
loading = true;
// setState(() {
_loadingState = 'loading...';
// });
和
onRefresh: (){
_loadNames();
return null;
},
至
onRefresh: (){
setState(() => _loadNames());
},
更新
_loadNames(){
loading = true;
new Future.delayed(Duration.zero, () => setState(() {
_loadingState = 'loading...';
}));