小编典典

Flutter:滚动到ListView中的小部件

flutter

如何滚动到中的特殊小部件ListView?例如ContainerListView如果我按下特定的按钮,我想自动滚动到其中的某个。

ListView(children: <Widget>[
  Container(...),
  Container(...), #scroll for example to this container 
  Container(...)
]);

阅读 1140

收藏
2020-08-13

共1个答案

小编典典

到目前为止,最简单的解决方案是使用Scrollable.ensureVisible(context)。因为它可以为您完成所有工作,并且可以使用任何大小的小部件。使用获取上下文GlobalKey

问题是ListView不会渲染不可见的项目。这意味着你的目标很可能不会建 在所有 。这意味着你的目标将没有context;
阻止您在无需进行其他工作的情况下使用该方法。

最后,最简单的解决方案是将您ListView的替换为,SingleChilScrollView然后将您的孩子打包成Column。范例:

class ScrollView extends StatelessWidget {
  final dataKey = new GlobalKey();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      primary: true,
      appBar: new AppBar(
        title: const Text('Home'),
      ),
      body: new SingleChildScrollView(
        child: new Column(
          children: <Widget>[
            new SizedBox(height: 160.0, width: double.infinity, child: new Card()),
            new SizedBox(height: 160.0, width: double.infinity, child: new Card()),
            new SizedBox(height: 160.0, width: double.infinity, child: new Card()),
            // destination
            new Card(
              key: dataKey,
              child: new Text("data\n\n\n\n\n\ndata"),
            )
          ],
        ),
      ),
      bottomNavigationBar: new RaisedButton(
        onPressed: () => Scrollable.ensureVisible(dataKey.currentContext),
        child: new Text("Scroll to data"),
      ),
    );
  }
}

注意 :虽然这使您可以轻松滚动到所需项目,但仅对小型预定义列表考虑此方法。至于更大的列表,您会遇到性能问题。

但是有可能Scrollable.ensureVisible与之合作ListView;尽管这需要更多工作。

2020-08-13