Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpansionTile doesn't keep state

Tags:

flutter

dart

following problem: I have a list of ExpansionTiles which works very well. The only problem I'm facing is that a expanded ExpansionTile which is scrolled out of view will, after scrolling it into view again, no longer be expanded. This leads to undesired user experience and also a kind of "jumpy" scrolling.

The documentation states the following:

When used with scrolling widgets like ListView, a unique key must be specified to enable the ExpansionTile to save and restore its expanded state when it is scrolled in and out of view.

This doesn't work though. So far I have found no way to make this work.
Here is the code so far:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'ExpansionTile Test',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> _getChildren() {
    List<Widget> elements = [];
    for (int i = 0; i < 20; i++) {
      elements.add(new ListChild());
    }
    return elements;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('ExpansionTile Test'),
      ),
      body: new ListView(
        children: _getChildren(),
      ),
    );
  }
}

class ListChild extends StatefulWidget {
  @override
  State createState() => new ListChildState();
}

class ListChildState extends State<ListChild> {
  GlobalKey<ListChildState> _key = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    return new ExpansionTile(
      key: _key,
      title: const Text('Test Tile'),
      children: <Widget>[
        const Text('body'),
      ],
    );
  }
}
like image 628
Rainer Wittmann Avatar asked Sep 18 '25 23:09

Rainer Wittmann


1 Answers

Use a PageStorageKey instead of a GlobalKey.

like image 91
Collin Jackson Avatar answered Sep 21 '25 19:09

Collin Jackson