小编典典

无限滚动listview-在构建过程中调用setState()或markNeedsBuild

flutter

我正在创建一个无限滚动listView,我想_loadingState使用该_loadNames函数中的setState
将String从’loading …’更改为’loaded’
,但是当从调用_loadNames时itemBuilder,我得到了“在构建错误期间调用了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;
       });
     }
  }

阅读 274

收藏
2020-08-13

共1个答案

小编典典

更改 _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...';
   }));
2020-08-13