Home > other >  How to scroll a SingleChildScrollView to a certain position?
How to scroll a SingleChildScrollView to a certain position?

Time:10-03

I have an app where when I press a TypeAheadFormField, I want the page to scroll down a little bit, for the user to see the suggestions as long as the keyboard. I watched stuff on internet and I can not figure it out. I get the error "ScrollController not attached to any scroll views".

Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        bottomNavigationBar: BottomAppBar(
        color: Colors.teal[200],
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Spacer(),
              IconButton(
                tooltip: 'Home',
                splashColor: Colors.lightBlueAccent,
                icon: const Icon(Icons.home),
                iconSize: 25,
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              const Spacer(),
            ],
          ),
        ),
        body: buildScroll(),
        backgroundColor: Colors.white,
      ),
    );

  }

Here above I am using the buildScroll widget.

Widget buildGame() {

    var myController = TextEditingController();

    @override
    void dispose() {
      myController.dispose();
      super.dispose();
    }

    int nextNumber({required int min, required int max}) =>
        min   Random().nextInt(max - min   1);

    int rowNumber = Random().nextInt(5);
    int columnNumber = nextNumber(min: 1, max: 10);
    int columnNumberHints = nextNumber(min: 1, max: 10);
    final String language = languageMatrix[rowNumber][0];
    final sentence = languageMatrix[rowNumber][columnNumber];
    final String languageLowerCases = language.toLowerCase();

    scrollController.animateTo(
        scrollController.position.pixels,
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeInOut
    );

    return Column(
         ---stuff here
    )
Widget buildScroll () {
    return SingleChildScrollView(
      controller: scrollController,
      child: buildGame(),
    );
  }

And here I am putting all together. But as I said, I am getting that error. What should I change?

CodePudding user response:

Try the following code:

if (scrollController.hasClients) {
  scrollController.animateTo(
    scrollController.position.pixels,
    duration: const Duration(milliseconds: 200),
    curve: Curves.easeInOut
  );
}
  • Related