Reputation: 13151
How to scroll SingleChildScrollView programmatically?
On long Form, it is desirable to automatically scroll to a require input field.
Upvotes: 18
Views: 24544
Reputation: 34270
Use ScrollController
to scroll inside Column
or ListView
Examples:
Colum With 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,),
],
),
);
}
}
Note: Only thing need to make sure that ScrollController
assigned to respective widget
Upvotes: 27
Reputation: 277627
There are multiple solutions :
ScrollController
: Assign it to controller
field of your SingleChildScrollView
. And use myScrollController.animateTo
or myScrollController.jumpTo
Scrollable
. Possibly Scrollable.ensureVisible
. But be aware that the context
parameter is the context of the widget that needs to be visible. You can get that context by using GlobalKey
.Upvotes: 20