微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在创建一个无限滚动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...';
   }));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐