Programmatically scrolling to the end of a ListView

前端 未结 7 2048
既然无缘
既然无缘 2020-11-27 13:03

I have a scrollable ListView where the number of items can change dynamically. Whenever a new item is added to the end of the list, I would like to programmatic

7条回答
  •  迷失自我
    2020-11-27 13:48

    Do not put the widgetBinding in the initstate, instead, you need to put it in the method that fetches your data from database. for example, like this. If put in initstate, the scrollcontroller will not attach to any listview.

        Future> fetchMessage() async {
    
        var res = await Api().getData("message");
        var body = json.decode(res.body);
        if (res.statusCode == 200) {
          List messages = [];
          var count=0;
          for (var u in body) {
            count++;
            Message message = Message.fromJson(u);
            messages.add(message);
          }
          WidgetsBinding.instance
              .addPostFrameCallback((_){
            if (_scrollController.hasClients) {
              _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
            }
          });
          return messages;
        } else {
          throw Exception('Failed to load album');
        }
       }
    

提交回复
热议问题