声明一个滚动控制器并使用它移动到您想要的点。这是滚动到最后一个元素的示例。请注意,滚动控制器是显式声明的,因此您不能发出primary: true
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
ScrollController _scrollController; // NEW
@override // NEW
void initState() { // NEW
super.initState(); // NEW
_scrollController = new ScrollController( // NEW
initialScrollOffset: 0.0, // NEW
keepScrollOffset: true, // NEW
);
}
void _toEnd() { // NEW
_scrollController.animateTo( // NEW
_scrollController.position.maxScrollExtent, // NEW
duration: const Duration(milliseconds: 500), // NEW
curve: Curves.ease, // NEW
); // NEW
} // NEW
@override
Widget build(BuildContext context) {
List items = [];
for (int i = 0; i < _counter; i++) {
items.add(new Text("Item $i"));
}
return new Scaffold(
appBar: new AppBar(
title: new Text("Scroll To End Test"),
actions: <Widget>[ // NEW
new IconButton( // NEW
icon: new Icon(Icons.arrow_downward), onPressed: _toEnd)// NEW
], // NEW
),
body: new GridView.extent(
//primary: true, // REMOVED
maxCrossAxisExtent: 150.0,
children: items,
controller: _scrollController, // NEW
),
floatingActionButton: new FloatingActionButton(
onPressed: () {
setState(() {
_counter++;
});
},
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
关于“奖励点”,我对 ScrollController 不太熟练,但据我所知,.animateTo( )
方法要求作为双精度的第一个输入,在那里设置滚动点:原则上,将i-th您想要滚动到的项目
var cursor = i/(# items) * _scrollController.position.maxScrollExtent
根据网格每行有多少个对象来调整此值。我知道这只是一个草图,但我认为它可以引导您到达那里。