The reason state for the ExpansionTile
state loss is the fact that it no longer has the same key after data is re-generated. Here is the experiment I ran on top of the documentation code you linked in your question. I am focusing only on the key part, which is where you assign keys to your ExpansionTile
:
Widget _buildTiles(Entry root) {
if (root.children.isEmpty) return new ListTile(title: new Text(root.title));
return new ExpansionTile(
key: new PageStorageKey<Entry>(root),
title: new Text(root.title),
children: root.children.map(_buildTiles).toList(),
);
}
Because you are most likely working with immutable data, when you get new data from Firebase, you generate new objects from it. Even though the root
has the same data and is the same to you, it is not the same object for Flutter. You now have 2 ways of dealing with this. One is to override ==
which in my opinion is a bad idea and will explain why with a comment. The second would be to generate your keys from data attributes you know will be the same (like unique database keys). I chose the title
attribute for my example.
Widget _buildTiles(Entry root) {
if (root.children.isEmpty) return new ListTile(title: new Text(root.title));
return new ExpansionTile(
key: new PageStorageKey<String>(root.title), // root.title == newerRoot.title is true
title: new Text(root.title),
children: root.children.map(_buildTiles).toList(),
);
}
You can try it out yourself using the updated code in this gist. I also had to make some modifications to the original code from the documentation so I could refresh the data and simulate your situation.