Make a Fully Custom Expandable Widget in Flutter

Kristian Kristola

Kristian Kristola

· 5 min read
flutter

Photo by Charles Deluvio on Unsplash

 

Flutter comes with the ExpansionPanel widget, which is pretty good but it doesn't always work perfectly.

sfdfsd

For example, apparently it's hard to change the appearance of the expansion arrow icon at the top right, among other things.

So here's how you can make your own expandable widget with AnimatedSwitcher and customize it however you want.

In order to use this piece of code, you need to put it inside a stateful widget that has a boolean variable _isExpanded which tells whether the widget is expanded or not.

AnimatedSwitcher(
  duration: Duration(milliseconds: 500),
  switchInCurve: Curves.easeInOutQuart,
  switchOutCurve: Curves.easeInOutQuart,
  transitionBuilder: (Widget child, Animation<double> anim) {
    return SizeTransition(
      sizeFactor: anim,
      child: child,
      axisAlignment: 0,
    );
  },
  child: _isExpanded ? Container(
    key: ValueKey('visible'),
    color: Colors.red,
    height: 100,
    child: Center(
      child: Text('Visible'),
    ),
  ) : Container(
    key: ValueKey('hidden'),
  ),
),

Things to note when using AnimatedSwitcher:

  • You must give both the visible and hidden version of the child widget a key. The key has to be different for the visible and hidden version of the child widget
    • (This is the part that I would always forget or mix up without this blog post. IMO it would be more intuitive if the key had to be the same for both, to tell Flutter that they are the same and Flutter needs to animate between them. But no. It's the other way around.)
  • With the axisAlignment parameter, you can control which direction the expandable area appears and disappears.
    • 0 means it appears from the top and bottom simultaneously
    • 1 means it appears from the top
    • -1 means from the bottom
Kristian Kristola

About Kristian Kristola

I'm a consultant and software developer with a strong foundation in game programming and the ability to adapt to new technologies and languages. Please feel free to contact me at:@
Copyright © 2024 Kiuas Games. All rights reserved.
Made by Osuuskunta Kiuas Games
Powered by Vercel

This website uses Google Analytics to collect anonymous information such as the number of visitors to different pages.