滚动到AnimatedList的末尾

时间:2019-04-12 07:58:31

标签: dart flutter

我有一个可滚动的AnimatedList,我希望每当有一个新项目添加到列表的末尾时,它将滚动到末尾。

我尝试应用此代码格式ListView,但是它不起作用。

import 'package:flutter/material.dart';

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  List<String> list = ["a", "a", "a", "a", "a", "a", "a"];
  final ScrollController _listScrollController = new ScrollController();
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: AnimatedList(
          key: _listKey,
          controller: _listScrollController,
          initialItemCount: list.length,
          itemBuilder: (BuildContext context, int index, Animation animation) {
            return FadeTransition(
              opacity: animation,
              child: Container(
                width: itemSize,
                height: itemSize,
                child: Text(list[index]),
              ),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(onPressed: _addNewItem),
    );
  }

  _addNewItem() {
    list.add(list.length.toString());
    _listKey.currentState.insertItem(
      list.length - 1,
      duration: Duration(seconds: 1),
    );

    _listScrollController.animateTo(
      _listScrollController.position.maxScrollExtent, // wrong value (this value is before add new item)
      duration: const Duration(milliseconds: 250),
      curve: Curves.ease,
    );
  }
}

所以我需要稍微更改滚动代码。

const double itemSize = 40.0;

_listScrollController.animateTo(
   _listScrollController.position.maxScrollExtent + itemSize,
   duration: const Duration(milliseconds: 250),
   curve: Curves.ease,
);

但是它需要itemSize来进行硬编码(itemSize)或使用BuildLayout,RenderBox来确定新的项目大小。你们有更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

问题是您在添加内容之前先对其进行了动画处理。您花费了1秒的时间来添加项目,请使用此计时器,该计时器将在1秒后运行。

Timer(
  Duration(milliseconds: 1100),
  () {
    _listScrollController.animateTo(
      _listScrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 250),
      curve: Curves.ease,
    );
  },
);

用我的替换您的。

_addNewItem() {
  list.add(list.length.toString());
  _listKey.currentState.insertItem(
    list.length - 1,
    duration: Duration(milliseconds: 200),
  );

  Timer(
    Duration(milliseconds: 220),
    () {
      _listScrollController.animateTo(
        _listScrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 500),
        curve: Curves.ease,
      );
    },
  );
}

输出:

enter image description here