小编典典

以编程方式滚动到ListView的末尾

flutter

我有一个可滚动ListView的项目的数量可以动态更改。每当将新项目添加到列表的末尾时,我都希望以编程方式将其滚动ListView到末尾。(例如,像聊天消息列表之类的,可以在末尾添加新消息)

我的猜测是,我需要ScrollController在我的State对象中创建一个并将其手动传递给ListView构造函数,以便以后可以在控制器上调用animateTo()/
jumpTo()方法。但是,由于我无法轻松确定最大滚动偏移量,因此似乎不可能简单地执行某种scrollToEnd()类型的操作(而我可以轻松地通过0.0使其滚动到初始位置)。

有没有简单的方法可以做到这一点?

使用reverse: true对我来说不是一个完美的解决方案,因为当ListView视口内只有少量项目时,我希望这些项目在顶部对齐。


阅读 337

收藏
2020-08-13

共1个答案

小编典典

如果将收缩包装ListView与一起使用reverse: true,将其滚动到0.0即可完成所需的操作。

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<MyHomePage> {
  List<Widget> _messages = <Widget>[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),
          );
        }
      ),
    );
  }
}
2020-08-13