Flutter: Customizing ExpansionTile for Auto-Collapsing Magic, Just Like ExpansionPanelList.radio

Ayush Tripathi
3 min readMar 30, 2022

Sometime we need the customisation of ExpansionTile but with the feature of ExpansionPannelList.radio of collapsing all other ExpansionList on opening any one of them.

Introduction
We are making something similar where when you click on any panel — it expanded and rest all automatically collapse. It is called Expansion Panel List of type Radio. But there are some drawbacks that you cannot easily customise it. So we are going to implement this auto collapse feature into Expansion Tile because we can easily customise them according to our need.

Working Expansion Panel List of type Radio.

What we gonna make?

We are going to create a ExpansionTile which automatically collapse themselves on opening one of them and act exactly same as ExpansionPanelList.radio.

Working ExpansionTile with AutoCollapsing.

How this gonna happen?

It is very easy and only going to happen with the help of only one thing that is Keys in Flutter. We are going to implement Keys and see how we happen to implement out desired result.

So what is Keys?

Keys are unique identifier and can be used to uniquely identify specific widgets. They preserve state when widgets move around in your widget tree.
You must have seen Keys used in every Stateful and stateless widget.

They are of two types:
1. Global Key
2. Local Keys :- (Unique Key, ValueKey, ObjectKey)

So lets begin -

First we implement a simple ExpansionTile. As you are implementing the collapsing feature you need more than two ExpansionTile, so we are going to make three of them. So don’t forget to put them inside a Column() or ListView(). We named them Item 1, Item 2, Item 3. And in body of all those we are going to show any simple messages.

So till now its is not that exciting as on opening Item 1, and then opening Item 2, didn’t automatically collapse Item 1. ( Probably thats why you are using ExpansionPanelList.radio till now.)

Working Expansion Tile Without Auto Collapsing.

So now the real thing started.

Now we are going to initialise 3 Unique Keys() named item1Key, item2Key & item3Key.

Initialisation of Unique Keys.

So, now we are going to use two properties of ExpansionTile():- onExpansionChanged & key.

Rest Code of Expansion Tile.

And here it is our desired output.

Working ExpansionTile with AutoCollapsing.

So Now what? What is the use of replicate the same thing and making two different widget work exactly same?

So here, it is the customisation you can easily do on your ExpansionTile which is not easy to achieve in ExpansionPanelList.radio.

More customisation we can easily do on any Expansion Tile.

Complete Code:-
https://github.com/AyushTripathi28/ExpansiontTileRadio

For more about Flutter, follow me so you’ll get notified when we write new posts. Also Have any question then reach out to me at my linkedin: ayushtripathi445
Thanks For Your Time :)

--

--