如何获得ScrollController的完整大小

时间:2017-05-23 17:14:38

标签: flutter

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

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

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

谢谢!

2 个答案:

答案 0 :(得分:31)

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

以下是添加更多项目时滚动到最后的条子列表的示例。

before after

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,
            ),
          ),
        ],
      ),
    );
  }
}

答案 1 :(得分:2)

此外,如果您想在开始时立即滚动到列表的底部(在initState()中),则可以在第一次调用setState()之前,将来自Collin解决方案的以下代码块放置进去。 >

class ExampleState extends State<Example>{
    void initState(){
    super.initState();

    _scrollController = new ScrollController();

    void _getListItems() async{

        //get list items

        SchedulerBinding.instance.addPostFrameCallback((_) {
          _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 100),
        curve: Curves.ease,
         );
        });

      setState((){
      });
   }
 }
}