如何以编程方式滚动SingleChildScrollView?
在长表单上,需要自动滚动到require输入字段。
答案 0 :(得分:2)
使用ScrollController
滚动Column
或ListView
示例:
具有SingleChildScrollView的列
class ScrollContainerPage extends StatelessWidget {
ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ScrollView Example'),
),
body: SingleChildScrollView(
controller: _scrollController,
child: ListView(
children: [
RaisedButton(
onPressed: () {
/// Scroll maximum end, if you want you can give hardcoded values also in place of _scrollController.position.maxScrollExtent
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 500),
curve: Curves.ease);
},
child: Text('Scroll To Bottom'),
),
SizedBox(height: 20,),
Container(height: 200, color: Colors.red,),
SizedBox(height: 20,),
Container(height: 200, color: Colors.blue,),
SizedBox(height: 20,),
Container(height: 200, color: Colors.green,),
SizedBox(height: 20,),
Container(height: 200, color: Colors.yellow,),
SizedBox(height: 20,),
],
),
),
);
}
}
ListView
class ScrollContainerPage extends StatelessWidget {
ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ScrollView Example'),
),
body: ListView(
controller: _scrollController,
children: [
RaisedButton(
onPressed: () {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 500),
curve: Curves.ease);
},
child: Text('Scroll To Bottom'),
),
SizedBox(height: 20,),
Container(height: 200, color: Colors.red,),
SizedBox(height: 20,),
Container(height: 200, color: Colors.blue,),
SizedBox(height: 20,),
Container(height: 200, color: Colors.green,),
SizedBox(height: 20,),
Container(height: 200, color: Colors.yellow,),
SizedBox(height: 20,),
],
),
);
}
}
注意:只需确保将ScrollController
分配给各个小部件
答案 1 :(得分:1)
有多种解决方案:
ScrollController
:将其分配到controller
的{{1}}字段。并使用SingleChilScrollView
或myScrollController.animateTo
myScrollController.jumpTo
的静态方法。可能Scrollable
。但请注意,Scrollable.ensureVisible
参数是需要可见的窗口小部件的上下文。您可以使用context
。