Programmatically scrolling to the end of a ListView

前端 未结 7 2049
既然无缘
既然无缘 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:34

    Use ScrollController.jumpTo() or ScrollController.animateTo() method to achieve this.

    Example:

    final _controller = ScrollController();
    
    @override
    Widget build(BuildContext context) {
      
      // After 1 second, it takes you to the bottom of the ListView
      Timer(
        Duration(seconds: 1),
        () => _controller.jumpTo(_controller.position.maxScrollExtent),
      );
    
      return ListView.builder(
        controller: _controller,
        itemCount: 50,
        itemBuilder: (_, __) => ListTile(title: Text('ListTile')),
      );
    }
    

    If you want smooth scrolling, then instead of using jumpTo above use

    _controller.animateTo(
      _controller.position.maxScrollExtent,
      duration: Duration(seconds: 1),
      curve: Curves.fastOutSlowIn,
    );
    

提交回复
热议问题