scroll-to-index

此包提供了固定/可变行高的滚动到索引机制,用于 Flutter 可滚动小部件。

入门

在您的 flutter 项目的 pubspec.yaml 文件中,添加以下依赖项

dependencies:
  ...
  scroll_to_index: any

在您的库中添加以下导入

import 'package:scroll_to_index/scroll_to_index.dart';

要开始使用 Flutter,请查看在线 文档

用法

这是一个小部件级别的库,意味着您可以在任何 Flutter 可滚动的小部件中使用此机制。

Flutter ListView 示例

ListView(
  scrollDirection: scrollDirection,
  controller: controller,
  children: randomList.map<Widget>((data) {
  	final index = data[0];
  	final height = data[1];
    return AutoScrollTag(
      key: ValueKey(index),
      controller: controller,
      index: index,
      child: Text('index: $index, height: $height'),
      highlightColor: Colors.black.withOpacity(0.1),
    );
  }).toList(),
)

您可以包装任何具有动态行高的行小部件

AutoScrollTag(
  key: ValueKey(index),
  controller: controller,
  index: index,
  child: child
)

使用 AutoScrollController 控制器。

当您需要滚动到指定索引时,您可以调用

controller.scrollToIndex(index, preferPosition: AutoScrollPosition.begin)

更进一步,对于固定行高,您可以提供一个建议高度以实现更高效的滚动。还有更多配置。

final controller = AutoScrollController(
  //add this for advanced viewport boundary. e.g. SafeArea
  viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),

  //choose vertical/horizontal
  axis: scrollDirection,

  //this given value will bring the scroll offset to the nearest position in fixed row height case.
  //for variable row height case, you can still set the average height, it will try to get to the relatively closer offset 
  //and then start searching.
  suggestedRowHeight: 200
);

如需完整示例,请参阅此 演示

GitHub

https://github.com/quire-io/scroll-to-index