我有一个可滚动的ListView,其中项目的数量可以动态变化。每当一个新项目被添加到列表的末尾时,我希望以编程的方式将ListView滚动到末尾。(例如,类似聊天消息列表的东西,可以在最后添加新消息)

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

有没有简单的方法来实现这个目标?

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


如果你使用一个带有reverse: true的收缩包装的ListView,那么将它滚动到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),
          );
        }
      ),
    );
  }
}

截图:

Scrolling with animation: final ScrollController _controller = ScrollController(); // This is what you're looking for! void _scrollDown() { _controller.animateTo( _controller.position.maxScrollExtent, duration: Duration(seconds: 2), curve: Curves.fastOutSlowIn, ); } @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton.small( onPressed: _scrollDown, child: Icon(Icons.arrow_downward), ), body: ListView.builder( controller: _controller, itemCount: 21, itemBuilder: (_, i) => ListTile(title: Text('Item $i')), ), ); } Scrolling without animation: Replace above _scrollDown method with this: void _scrollDown() { _controller.jumpTo(_controller.position.maxScrollExtent); }


我在尝试使用滚动控制器到列表底部时遇到了很多问题,所以我使用了另一种方法。

我没有创建一个事件将列表发送到底部,而是将逻辑更改为使用反向列表。

所以,每次我有一个新项目,我简单地,在列表的顶部插入。

// add new message at the begin of the list 
list.insert(0, message);
// ...

// pull items from the database
list = await bean.getAllReversed(); // basically a method that applies a descendent order

// I remove the scroll controller
new Flexible(
  child: new ListView.builder(
    reverse: true, 
    key: new Key(model.count().toString()),
    itemCount: model.count(),
    itemBuilder: (context, i) => ChatItem.displayMessage(model.getItem(i))
  ),
),

listViewScrollController.animateTo(listViewScrollController.position.maxScrollExtent)是最简单的方法。


你可以使用0.09*height作为列表中一行的高度,_controller的定义如下:_controller = ScrollController();

(BuildContext context, int pos) {
    if(pos != 0) {
        _controller.animateTo(0.09 * height * (pos - 1), 
                              curve: Curves.easeInOut,
                              duration: Duration(milliseconds: 1400));
    }
}

为了得到完美的结果,我将Colin Jackson和CopsOnRoad的答案结合如下:

_scrollController.animateTo(
    _scrollController.position.maxScrollExtent,
    curve: Curves.easeOut,
    duration: const Duration(milliseconds: 500),
 );

不要将widgetBinding放在初始化状态,相反,您需要将它放在从数据库获取数据的方法中。比如,像这样。如果将scrollcontroller置于initstate,它将不会附加到任何listview。

    Future<List<Message>> fetchMessage() async {

    var res = await Api().getData("message");
    var body = json.decode(res.body);
    if (res.statusCode == 200) {
      List<Message> 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');
    }
   }

我在使用StreamBuilder小部件从数据库中获取数据时遇到了这个问题。我把WidgetsBinding.instance.addPostFrameCallback放在小部件的构建方法的顶部,它不会一直滚动到最后。我是这样解决的:

...
StreamBuilder(
  stream: ...,
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    // Like this:
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_controller.hasClients) {
        _controller.jumpTo(_controller.position.maxScrollExtent);
      } else {
        setState(() => null);
      }
     });

     return PutYourListViewHere
}),
...

我尝试了_controller。animateTo太,但它似乎没有工作。


虽然所有的答案都产生了预期的效果,但我们应该在这里做一些改进。

First of all in most cases (speaking about auto scrolling) is useless using postFrameCallbacks because some stuff could be rendered after the ScrollController attachment (produced by the attach method), the controller will scroll until the last position that he knows and that position could not be the latest in your view. Using reverse:true should be a good trick to 'tail' the content but the physic will be reversed so when you try to manually move the scrollbar you must move it to the opposite side -> BAD UX. Using timers is a very bad practice when designing graphic interfaces -> timer are a kind of virus when used to update/spawn graphics artifacts.

不管怎样,说到这个问题,完成任务的正确方法是使用jumpTo方法和hasClients方法作为保护。

是否有任何ScrollPosition对象使用attach方法将自己附加到ScrollController。 如果该值为false,则不能调用与ScrollPosition交互的成员,例如position、offset、animateTo和jumpTo

在代码中简单地做这样的事情:

if (_scrollController.hasClients) {
    _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

无论如何,这段代码仍然不够,即使可滚动条不在屏幕末端,该方法也会被触发,因此如果你手动移动工具条,该方法将被触发,并执行自动滚动。

我们可以做得更好,在一个监听器和一对bool的帮助下就可以了。 我使用这种技术在SelectableText中可视化大小为100000的CircularBuffer的值,内容保持正确更新,自动滚动非常流畅,即使对于非常非常长的内容也没有性能问题。也许就像有人在其他回答中说的那样,animateTo方法可以更流畅,更可定制,所以可以尝试一下。

首先声明这些变量:

ScrollController _scrollController = new ScrollController();
bool _firstAutoscrollExecuted = false;
bool _shouldAutoscroll = false;

然后让我们创建一个自动滚动的方法:

void _scrollToBottom() {
    _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

然后我们需要听众:

void _scrollListener() {
    _firstAutoscrollExecuted = true;

    if (_scrollController.hasClients && _scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _shouldAutoscroll = true;
    } else {
        _shouldAutoscroll = false;
    }
}

在initState中注册它:

@override
void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);
}

在dispose中删除监听器:

@override
void dispose() {
    _scrollController.removeListener(_scrollListener);
    super.dispose();
}

然后触发_scrollToBottom,根据你的逻辑和需要,在你的setState:

setState(() {
    if (_scrollController.hasClients && _shouldAutoscroll) {
        _scrollToBottom();
    }

    if (!_firstAutoscrollExecuted && _scrollController.hasClients) {
         _scrollToBottom();
    }
});

解释

We made a simple method: _scrollToBottom() in order to avoid code repetitions; We made a _scrollListener() and we attached it to the _scrollController in the initState -> will be triggered after the first time that the scrollbar will move. In this listener we update the value of the bool value _shouldAutoscroll in order to understand if the scrollbar is at the bottom of the screen. We removed the listener in the dispose just to be sure to not do useless stuff after the widget dispose. In our setState when we are sure that the _scrollController is attached and that's at the bottom (checking for the value of shouldAutoscroll) we can call _scrollToBottom(). At the same time, only for the 1st execution we force the _scrollToBottom() short-circuiting on the value of _firstAutoscrollExecuted.


_controller.jumpTo(_controller.position.maxScrollExtent);
_controller.animateTo(_controller.position.maxScrollExtent);

这些调用不能很好地用于动态大小的项列表。在调用jumpTo()时,我们不知道列表有多长,因为所有的项都是变量,并且是在向下滚动列表时惰性构建的。

这可能不是聪明的方法,但作为最后的手段,你可以这样做:

Future scrollToBottom(ScrollController scrollController) async {
  while (scrollController.position.pixels != scrollController.position.maxScrollExtent) {
    scrollController.jumpTo(scrollController.position.maxScrollExtent);
    await SchedulerBinding.instance!.endOfFrame;
  }
}

根据这个答案,我已经创建了这个类,只是发送你的scroll_controller,如果你想要相反的方向使用反向参数

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

class ScrollService {
  static scrollToEnd(
      {required ScrollController scrollController, reversed = false}) {
    SchedulerBinding.instance!.addPostFrameCallback((_) {
      scrollController.animateTo(
        reverced
            ? scrollController.position.minScrollExtent
            : scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }
}

我的解决方案:

1 . 像这样定义全局键:

final lastKey = GlobalKey();

2 . 附加到最后一条消息

SingleChildScrollView(
    controller: scrollController,
    padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
    physics: const AlwaysScrollableScrollPhysics(),
    child: Column(
        children: List.generate(
            data.length,
            (index) {
            return BuildMessage(
                key:
                    data.length == index + 1 ? lastKey : null,
                message: data[index],
                focusNode: focusNode,
            );
            },
        ),
    ),
)

3 . 创建滚动的函数调用

void scrollToBottom() {
    Scrollable.ensureVisible(lastKey.currentContext!,alignment: 1, duration: const Duration(milliseconds: 500));
}

当你想滚动到底部时调用,延迟100毫秒

Timer(const Duration(milliseconds: 100),() => scrollToBottom());

_scrollController.animateTo ( _scrollController.position.maxScrollExtent, duration: const持续时间(毫秒:400), 曲线:Curves.fastOutSlowIn); });


我使用的是一个动态列表视图,但scrollController.animateTo()不会工作在这里提到的动态列表https://stackoverflow.com/a/67561421/13814518,我甚至没有在以前的答复中找到任何好的解决方案。下面是我解决这个问题的方法。

void scrollToMaxExtent() {
  WidgetsBinding.instance.addPostFrameCallback((_) {
    scrollController.animateTo(
      scrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 100),
      curve: Curves.easeIn,
    );
  });
}

如果你想看到最后一项从底部填充可见,然后添加额外的距离像这样

 _controller.jumpTo(_controller.position.maxScrollExtent + 200);

这里200是额外的距离


对我来说,问题是scrollController.position.maxScrollExtent总是返回0.0。原因是我的ListView在ScrollView里面。

删除ScrollView修复了这个问题。


优点:

这是一个100%有效的解决方案。它总是滚动到最后,在线上一些其他的解决方案。而且,它不需要倒车。

缺点:

锁定曲线。线性动画曲线。

    Future.doWhile(() {
      if (scrollController.position.extentAfter == 0)
        return Future.value(false);
      return scrollController
          .animateTo(scrollController.position.maxScrollExtent,
              duration: Duration(milliseconds: 100), curve: Curves.linear)
          .then((value) => true);
    });