我有一个ListView
,孩子们可以使用三种自定义类型中的任何一种。每个孩子的身高会有所不同,因此我无法根据他们的索引来计算位置。
如何滚动到ListView中的第n个孩子?
答案 0 :(得分:1)
我一直使用quire的scroll_to_index包,并且效果很好
答案 1 :(得分:0)
在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"),
),
],
),
);
}
}
如果有更好的方法,请发布您的代码。