如何获得 ScrollController 的完整尺寸 [英] How to get full size of a ScrollController

查看:27
本文介绍了如何获得 ScrollController 的完整尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 ScrollController 附加到 [SliverAppBar, SliverList] 的 CustomScrollView

I've attached a ScrollController to a CustomScrollView of [SliverAppBar, SliverList]

在默认情况下,我会使用 reverse:true 和 animateTo (0.0) 将滚动移动到添加的最后一个元素,但在这种情况下,使用 reverse 也会反转 SliverAppBar/SliverList 的顺序!

In a default case I would use reverse:true and animateTo (0.0) to move the scroll to the last element added but in this case using reverse would also reverse the SliverAppBar/SliverList order !

所以我想使用 animateTo ( sizeOfScrollableAfterElementAdded ) 但我找不到这个值.

So I'd like to use animateTo ( sizeOfScrollableAfterElementAdded ) but I can't find this value.

谢谢!

推荐答案

您可以使用 _scrollController.position.maxScrollExtent 滚动到最后.确保在帧后回调中执行此操作,以便它包含您刚刚添加的新项目.

You can use _scrollController.position.maxScrollExtent to scroll to the end. Make sure to do this in a post-frame callback so that it will include the new item you just added.

这是一个随着添加更多项目而滚动到末尾的条形列表示例.

Here is an example of a sliver list that scrolls to the end as more items are added.

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

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  State createState() => new MyHomePageState();
}


class MyHomePageState extends State<MyHomePage> {
  ScrollController _scrollController = new ScrollController();

  List<Widget> _items = new List.generate(40, (index) {
    return new Text("item $index");
  });

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.arrow_downward),
        onPressed: () {
          setState(() {
            _items.add(new Text("item ${_items.length}"));
          });
          SchedulerBinding.instance.addPostFrameCallback((_) {
            _scrollController.animateTo(
              _scrollController.position.maxScrollExtent,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOut,
            );
          });
        },
      ),
      body: new CustomScrollView(
        controller: _scrollController,
        slivers: [
          new SliverAppBar(
            title: new Text('Sliver App Bar'),
          ),
          new SliverList(
            delegate: new SliverChildBuilderDelegate(
              (context, index) => _items[index],
              childCount: _items.length,
            ),
          ),
        ],
      ),
    );
  }
}

这篇关于如何获得 ScrollController 的完整尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆