Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Flutter app from scrolling to top after calling setState?

Tags:

flutter

dart

I have an ExpansionPanelList inside a SingleChildScrollView. Whenever I (un)fold a panel and therefore call setState, the SingleChildScrollView scrolls back to the top. How can I prevent this?

@override
Widget build(BuildContext context) {
  final _scaffoldKey = new GlobalKey<ScaffoldState>();
  return new Scaffold(
    key: _scaffoldKey,
    appBar: new AppBar(
      title: new Text(widget.title),
    ),
    body: new SingleChildScrollView(
      child: new ExpansionPanelList(
        children: <ExpansionPanel>[
          // panels
        ],
        expansionCallback: (int index, bool isExpanded) {
          setState(() {
            // toggle expanded
          });
        },
      ), // ExpansionPanelList
    ), // SingleChildScrollView
  ); // Scaffold
}

This answer suggests using a custom ScrollController with keepScrollOffset set to true, however this is the default value and setting it explicitly to true therefore does not change anything.

like image 674
Scriptim Avatar asked Jan 01 '19 21:01

Scriptim


1 Answers

That's because you are using a new Key every time you rebuild the widget (setState).

To fix your issue just move the code below outside the build method

 final _scaffoldKey = new GlobalKey<ScaffoldState>(); 

Like this :

 final _scaffoldKey = new GlobalKey<ScaffoldState>();

    @override
    Widget build(BuildContext context) {
      return new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
like image 52
diegoveloper Avatar answered Sep 23 '22 00:09

diegoveloper