Programmatically scrolling to the end of a ListView

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

    If you use a shrink-wrapped ListView with reverse: true, scrolling it to 0.0 will do what you want.

    import 'dart:collection';
    
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(new MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Example',
          home: new MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }
    
    class _MyHomePageState extends State {
      List _messages = [new Text('hello'), new Text('world')];
      ScrollController _scrollController = new ScrollController();
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          body: new Center(
            child: new Container(
              decoration: new BoxDecoration(backgroundColor: Colors.blueGrey.shade100),
              width: 100.0,
              height: 100.0,
              child: new Column(
                children: [
                  new Flexible(
                    child: new ListView(
                      controller: _scrollController,
                      reverse: true,
                      shrinkWrap: true,
                      children: new UnmodifiableListView(_messages),
                    ),
                  ),
                ],
              ),
            ),
          ),
          floatingActionButton: new FloatingActionButton(
            child: new Icon(Icons.add),
            onPressed: () {
              setState(() {
                _messages.insert(0, new Text("message ${_messages.length}"));
              });
              _scrollController.animateTo(
                0.0,
                curve: Curves.easeOut,
                duration: const Duration(milliseconds: 300),
              );
            }
          ),
        );
      }
    }
    

提交回复
热议问题