Flutter   发布时间:2022-05-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了flutter – 以编程方式滚动到ListView的末尾大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有@L_197_1@可滚动的ListView,其中项目的数量可以动态更改.每当将新项添加到列表的末尾时,我想以编程方式将ListView滚动到最后. (例如,聊天消息列表,其中可以在最后添加新消息)

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

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

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

解决方法

如果你使用@L_197_1@收缩包装的ListView with 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 @R_696_8620@n(
            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),);
        }
      ),);
  }
}

大佬总结

以上是大佬教程为你收集整理的flutter – 以编程方式滚动到ListView的末尾全部内容,希望文章能够帮你解决flutter – 以编程方式滚动到ListView的末尾所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。