'Flutter : How to Automaticallly scroll to end of SingleChildScrollView
I have a SingleChildScrollView, its scrollDirection is set to Horizontal with 5 child widgets placed inside a Row Widget. I want to programmatically scroll to the last widget in the Row and when the last widget is reached(waits 2 seconds) I want to scroll backward.
SingleChildScrollView(
scrollDirection:Axis.horizontal,
child:Row(
children:<Widget>[
Widget(),
Widget(),
Widget(),
Widget(),
Widget(),
],
),
),
)
Solution 1:[1]
You can do it using scroll controller in following way.
ScrollController _controller;
@override
void initState() {
super.initState();
_controller = ScrollController();
WidgetsBinding.instance.addPostFrameCallback((_) {
_controller
.animateTo(_controller.position.maxScrollExtent,
duration: Duration(seconds: 1), curve: Curves.ease)
.then((value) async {
await Future.delayed(Duration(seconds: 2));
_controller.animateTo(_controller.position.minScrollExtent,
duration: Duration(seconds: 1), curve: Curves.ease);
});
});
}
callMeWidget() {
return Container(
height: 100,
width: 100,
color: Colors.red,
margin: EdgeInsets.all(10),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: SingleChildScrollView(
controller: _controller,
scrollDirection: Axis.horizontal,
child: Row(
children: <Widget>[
callMeWidget(),
callMeWidget(),
callMeWidget(),
callMeWidget(),
callMeWidget(),
],
),
),
),
);
}
Solution 2:[2]
I have a better and more efficient method :
SingleChildScrollView(
scrollDirection:Axis.horizontal,
reverse = true;
child:Row(
children:<Widget>[
Widget(),
Widget(),
Widget(),
Widget(),
Widget(),
],
),
),
as simple as that :)
It will scroll to the end as soon as a new widget is added !
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Khushal Jangid |