DEV Community

Cover image for expandable_panel: collapsible panels for Flutter with accordions, a11y and RTL
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

expandable_panel: collapsible panels for Flutter with accordions, a11y and RTL

An expandable panel looks like one of the simplest widgets in an app: a header, a body, and a tap that shows or hides the body. Then the details arrive. The panel sits in a list and has to scroll into view when it opens. A FAQ page wants only one answer open at a time. A screen reader has to announce whether the section is open. The icon has to move to the other side in Arabic. And the app has to remember what was open after Android kills and restores it.

The expandable package is a well-known answer to this. expandable_panel is a package with the same widgets and nearly the same API, written from scratch, that adds accordion groups, accessibility, keyboard support, RTL layouts, reduced motion and state restoration, and fixes a list of known issues. The README says most apps can migrate by changing one import.

What it does

A familiar API. The widgets are the ones you know from expandable: ExpandablePanel, Expandable, ExpandableNotifier, ExpandableController, ExpandableButton, ExpandableIcon, ScrollOnExpand, ExpandableTheme and ExpandableThemeData, with the same theme fields.

Accordion. ExpandableGroup keeps at most one panel open, or at most maxExpanded panels, or leaves the count unlimited. Its state object has collapseAll().

Accessibility. The header is one button in the semantics tree. It reports an expanded or collapsed state and gives the localized hint "Expand" or "Collapse". Hidden content is left out of the semantics tree and of focus traversal, so a screen reader does not read text that is not on screen.

Keyboard. The header can take focus and shows a focus highlight. Enter, numpad Enter and Space toggle it.

RTL. The icon is placed at start or end by default, so it mirrors in right-to-left locales. If you want a fixed physical side, use left or right.

Reduced motion. When MediaQuery.disableAnimations is set, panels, icons and scrolls snap without animating.

Initial state and restoration. Use initialExpanded, or set a restorationId to save and restore the state with RestorationMixin.

Lazy content. The expanded child is not built until the panel first expands, and expandedBuilder defers even the construction of the widget. With maintainState: true, the expanded content keeps its state while collapsed: it stays offstage, its tickers are muted, and it cannot receive focus.

Material 3 defaults. The icon color comes from ColorScheme.onSurfaceVariant, so it follows dark mode, and the motion uses Durations.medium2 and Easing.standard.

The fixes

The README lists the fixed issues in a table, each linked to the upstream issue and covered by a widget test. Some of them were also reproduced by running the same test against expandable 5.0.1, where it fails. The others are fixes for causes visible in the 5.0.1 source. A few examples:

  • ScrollOnExpand scrolled to the wrong place when animationDuration differed from scrollAnimationDuration. Now the scroll waits until every Expandable below it has finished animating, instead of starting on a timer.
  • scrollOnExpand: false still scrolled. The flag is now honoured.
  • Inside a scrollable nested in another scrollable, the expanded panel ended up clipped. The scroll now runs on the final layout and reveals the panel in every enclosing viewport.
  • The icon stopped rotating, or the panel stopped following the controller, after a parent rebuilt with a new controller. Every widget now rebinds when the controller in scope is replaced.
  • Content that changed height while expanded animated again. Once settled, the body now takes its content's size directly.
  • Nested panels opened and closed their parents. A panel nested in another panel's body now has its own state.
  • The icon stayed dark in a dark theme. It now follows the color scheme.

How to use it

Add it from GitHub:

dependencies:
  expandable_panel:
    git: https://github.com/AbdeldjalilChougui/expandable_panel
Enter fullscreen mode Exit fullscreen mode
import 'package:expandable_panel/expandable_panel.dart';
Enter fullscreen mode Exit fullscreen mode

A basic panel takes a header, a collapsed preview and the expanded content:

class ArticleTile extends StatelessWidget {
  const ArticleTile({super.key, required this.title, required this.body});

  final String title;
  final String body;

  @override
  Widget build(BuildContext context) {
    return ExpandablePanel(
      header: Text(title),
      collapsed: Text(body, maxLines: 2, overflow: TextOverflow.ellipsis),
      expanded: Text(body),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

An accordion is a group around the panels:

Widget faq(Map<String, String> answers) {
  return ExpandableGroup(
    maxExpanded: 1, // at most one open; use 2, 3 ... or null for no limit
    child: Column(
      children: [
        for (final entry in answers.entries)
          ExpandablePanel(
            header: ListTile(title: Text(entry.key)),
            expanded: Text(entry.value),
          ),
      ],
    ),
  );
}
Enter fullscreen mode Exit fullscreen mode

And when the content is heavy, or holds state you do not want to lose:

Widget comments() {
  return ExpandablePanel(
    header: const Text('Comments'),
    // Built only when the panel opens.
    expandedBuilder: (context) => ListView(
      shrinkWrap: true,
      children: const [TextField()],
    ),
    // Keep the text field's content while collapsed.
    maintainState: true,
  );
}
Enter fullscreen mode Exit fullscreen mode

For control from code, pass an ExpandableController. It has toggle(), expand(), collapse() and an expanded setter, and you can listen to it. The README also shows cards in a ListView that scroll into view with ScrollOnExpand, and custom layouts with Expandable and ExpandableButton. The example app shows all of them.

Migrating from expandable

Replace the dependency and the import. Class names, constructor parameters and theme fields are unchanged. Then check the behaviour changes, which the README lists in full. The ones you are most likely to notice:

  • The icon color is ColorScheme.onSurfaceVariant instead of Colors.black54. Set iconColor to keep the old color.
  • The header alignment is center instead of top.
  • The icon placement is end instead of right. That is still the right side in LTR.
  • The expanded child is built on first expansion and removed after collapsing. Use maintainState: true if it must keep state or a GlobalKey.
  • A nested ExpandablePanel without a controller gets its own state. Pass the same controller if you want them linked.
  • A missing controller throws a FlutterError naming ExpandableNotifier.

The new options are all opt-in.

Things to know

  • Vertical only. Panels expand vertically. Horizontal expansion is not supported.
  • One cross-fade point. crossFadePoint applies symmetrically: when collapsing, the timeline runs backwards. Separate expand and collapse points are not supported.
  • No onExpansionChanged callback. Listen to the ExpandableController, which is a ValueListenable<bool>.
  • ScrollOnExpand waits only for Expandable widgets below it. Any other animation you run inside is not waited for. It also keeps its list item alive until the scroll has run, which needs the list's default addAutomaticKeepAlives: true.
  • Groups count direct members. An ExpandableGroup counts only the panels and notifiers directly inside it. Panels nested inside a member are independent.
  • Accessibility was verified in tests, not on a device. Semantics, focus and keyboard behaviour are checked with widget tests in the semantics tree. The README states they have not been tried with TalkBack or VoiceOver on a device.
  • ExpandableButton needs a Material ancestor with the default useInkWell: true, as InkWell does.

Why I built it

The expandable API is good, and existing code is written against it. But its issue tracker has reports about scrolling to the wrong place, controllers that stop working after a rebuild, nested panels that toggle their parents and an icon that is unreadable in dark mode. It also has no accordion, no semantics for screen readers, no keyboard support and no RTL-aware placement.

I wanted those fixed without asking anyone to rewrite their screens. So the package keeps the names and parameters, and puts the effort into behaviour: each fix has a widget test, and the changes that could surprise you are written down in a migration table. It is a clean-room implementation, written against the public API and the issue tracker of expandable (MIT, Alexander Ryzhov), and it does not copy that package's code.

Get the code

The source, the README with the full table of fixes and the migration guide, the example app and the tests are on GitHub: https://github.com/AbdeldjalilChougui/expandable_panel. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)