Adarsh Balu
Adarsh Balu

Reputation: 352

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(),  
                         ],
            ), 
    ),

)

Upvotes: 11

Views: 8986

Answers (2)

Khushal
Khushal

Reputation: 779

I have a better and more efficient method :

SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      reverse: true,
      child: Row(
        children: [
          ***
        ],
      ),
    );

as simple as that :)

It will scroll to the end as soon as a new widget is added !

Upvotes: 14

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27137

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(),
            ],
          ),
        ),
      ),
    );
  }

Upvotes: 12

Related Questions