【问题标题】:Scroll to n-th child in a ListView where children have variable height滚动到 ListView 中的第 n 个孩子,其中孩子的高度可变
【发布时间】:2019-12-13 23:04:24
【问题描述】:

我有一个ListView,孩子们可以在其中拥有三种自定义类型中的任何一种。每个孩子的身高都不一样,所以我无法根据他们的索引来计算位置。

如何滚动到 ListView 中的第 n 个子项?

【问题讨论】:

  • 如果项目的顺序是已知的,那么你可以用数学公式var peakOfItem = (item1.height * count) + (item2.height * count) + (item3.height * count)来做,然后滚动到这个高度
  • 每个孩子都是三种类型之一,但每个孩子的身高会根据其内容而有所不同。
  • 在 ListView 中已知 issue。希望您可以使用indexed_list_view package,如果这对您的问题有帮助,请告诉我将其作为答案。

标签: flutter dart flutter-layout


【解决方案1】:

我一直在使用 quire 的 scroll_to_index 包,它的工作非常好

【讨论】:

    【解决方案2】:

    Listview Scrolling to widget 的帮助下,当前示例需要GlobalKey 将显示移动到Widget,即n-th child 列表中,每个孩子都有可变高度。

      import 'dart:math';
      class ScrollView extends StatelessWidget {
      final firstKey = GlobalKey(debugLabel: "top");
      final lastKey = GlobalKey(debugLabel: "bottom");
      final r = Random();
      var count = 25;
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          primary: true,
          appBar: new AppBar(
            title: const Text('Home'),
          ),
          body: SingleChildScrollView(
            child: new Column(
              children: List.generate(
                count,
                (index) {
                  if (index == 0) {
                    return Text("First entry", key: firstKey);
                  }
                  if (index == count - 1) {
                    return Text("Last entry", key: lastKey);
                  }
                  return Container(
                    margin: const EdgeInsets.all(8.0),
                    height: 20 + (r.nextDouble() * 80),
                    color: Colors.red,
                    child: Center(child: Text("Random Height Widget")),
                  );
                },
              ),
            ),
          ),
          bottomNavigationBar: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              new RaisedButton(
                onPressed: () => Scrollable.ensureVisible(firstKey.currentContext,
                    curve: Curves.linear, duration: Duration(milliseconds: 500)),
                child: new Text("Scroll to first"),
              ),
              new RaisedButton(
                onPressed: () => Scrollable.ensureVisible(lastKey.currentContext,
                    curve: Curves.linear, duration: Duration(milliseconds: 500)),
                child: new Text("Scroll to last"),
              ),
            ],
          ),
        );
      }
    }
    

    如果有更好的方法,请发布您的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 2021-04-15
      • 2018-03-05
      • 1970-01-01
      • 2016-07-08
      相关资源
      最近更新 更多