【问题标题】:How to scroll item in ListView so it is visible?如何滚动 ListView 中的项目使其可见?
【发布时间】:2023-03-31 18:31:01
【问题描述】:

向 ListView 添加新项目(例如 ListTile)时,是否可以将新添加的项目滚动到视图中?新项目可能不在列表底部(例如,它按字母顺序排序)。

【问题讨论】:

标签: flutter


【解决方案1】:

您可以使用ScrollController 滚动浏览ListView

final scrollController = ScrollController();

// ...
ListView(controller: scrollController // ...
);
// ...
scrollController.animateTo(height, duration: Duration(milliseconds: 678), 
  curve: Curves.ease);

您必须自己确定高度。这可以使用您的项目的索引和一般项目高度来完成。

有一个full example available here

【讨论】:

  • 这个解决方案对我不起作用,因为我的应用程序具有不同类型的内容(文本、照片、视频、联系人、位置),并且它们在 ListView 中的高度确实不同(不一样)。感谢您的建议。
【解决方案2】:

您可以使用 quire-io 团队的以下库将 ListView 滚动到该位置:

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

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(),
)

【讨论】:

    【解决方案3】:

    扩展@creativecreatorormaybenot,如果你想在你添加了一个项目之后这样做,当然你需要提示它使用setstate进行绘制,但是还有一些其他的关键部分。例如,此代码将自动滚动,以便在构建列表后立即看到列表的末尾:

    class MyList extends StatefulWidget {
      @override
      _MyState createState() => _MyState();
    }
    
    class _MyState extends State<MyList> {
      ScrollController _scrollController;
    
      @override
      void initState() {
        super.initState();
        _scrollController = ScrollController();
      }
    
      void _onAfterBuild(BuildContext context) {
        _scrollController.animateTo(double.maxFinite, /* <- the offset in units to scroll to */
            duration: Duration(milliseconds: 1), curve: Curves.ease);
      }
    
      @override
      Widget build(BuildContext context) {
        WidgetsBinding.instance.addPostFrameCallback((_) => _onAfterBuild(context));
    
        return ListView.builder(
            controller: _scrollController,
            //initialScrollIndex: appState.doseEvents?.length ?? 0,
            itemCount: 20,
            itemBuilder: (BuildContext ctxt, int index) {
              return Row(
                children: <Widget>[
                  Text("A"),
                  Text("B"),
                  Text("C"),
                ],
              );
            });
      }
    }
    

    如果你想去一个特定的项目,你将不得不在 _onAfterBuild 中计算该项目的偏移量。例如:

      void _onAfterBuild(BuildContext context) {
        double scrollPos = _mostRecentlyAddedIndex * _itemHeight;
        _scrollController.animateTo(scrollPos, 
            duration: Duration(milliseconds: 1), curve: Curves.ease);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      相关资源
      最近更新 更多