How to Use Expansion Tile in Flutter?

What is an Expansion Tile?

Expansion Tile is a single-line ListTile with an expansion arrow icon that expands or collapses the tile to reveal or hide the children. It is typically used with ListView to create an “expand/collapse” list entry. That is when you want to add some extra details to your ListTile but are not required at the first view. This can be viewed by the user by expanding the tile if they want to see the detail.

Parameters of Expansion Tile Widget

Lets take a look at constructor of Expansion Tile to get an idea of the parameters

ExpansionTile(
{
Key? key, Widget? leading, 
required Widget title, 
Widget? subtitle, 
ValueChanged<bool>? onExpansionChanged, 
List<Widget> children = const <Widget>[], 
Widget? trailing, 
bool initiallyExpanded = false, 
bool maintainState = false, 
EdgeInsetsGeometry? tilePadding, 
CrossAxisAlignment? expandedCrossAxisAlignment, 
Alignment? expandedAlignment, 
EdgeInsetsGeometry? childrenPadding, 
Color? backgroundColor, 
Color? collapsedBackgroundColor, 
Color? textColor, 
Color? collapsedTextColor, 
Color? iconColor, 
Color? collapsedIconColor, 
ShapeBorder? shape, 
ShapeBorder? collapsedShape,
Clip? clipBehavior,
ListTileControlAffinity? controlAffinity,
ExpansionTileController? controller,
bool? dense,
VisualDensity? visualDensity,
double? minTileHeight,
bool? enableFeedback = true,
bool enabled = true,
AnimationStyle? expansionAnimationStyle
})

backgroundColor:The color to display behind the sublist when expanded.

children:The widgets that are displayed when the tile expands.

childrenPadding:Specifies padding for children.

clipBehavior:The content will be clipped (or not) according to this option.

collapsedBackgroundColor:When not null, defines the background color of tile when the sublist is collapsed.

collapsedIconColor:The icon color of tile’s expansion arrow icon when the sublist is collapsed.

collapsedShape:The tile’s border shape when the sublist is collapsed.

collapsedTextColor:The color of the tile’s titles when the sublist is collapsed.

controlAffinity:Typically used to force the expansion arrow icon to the tile’s leading or trailing edge.

controller:If provided, the controller can be used to expand and collapse tiles.

dense:Whether this list tile is part of a vertically dense list.

enabled:Whether this expansion tile is interactive.

enableFeedback:Whether detected gestures should provide acoustic and/or haptic feedback.

expandedAlignment:Specifies the alignment of children, which are arranged in a column when the tile is expanded.

expandedCrossAxisAlignment:Specifies the alignment of each child within children when the tile is expanded.

expansionAnimationStyle:Used to override the expansion animation curve and duration.

hashCode:The hash code for this object.

iconColor:The icon color of tile’s expansion arrow icon when the sublist is expanded.

initiallyExpanded:Specifies if the list tile is initially expanded (true) or collapsed (false, the default).

key:Controls how one widget replaces another widget in the tree.

leading:A widget to display before the title.

maintainState:Specifies whether the state of the children is maintained when the tile expands and collapses.

minTileHeight:The minimum height allocated for the ListTile widget.

onExpansionChanged:Called when the tile expands or collapses.

runtimeType:A representation of the runtime type of the object.

shape:The tile’s border shape when the sublist is expanded.

subtitle:Additional content displayed below the title.

textColor:The color of the tile’s titles when the sublist is expanded.

tilePadding:Specifies padding for the ListTile.

title:The primary content of the list item.

trailing:A widget to display after the title.

visualDensity:Defines how compact the expansion tile’s layout will be.

Methods Provided

createElement():Creates a StatefulElement to manage this widget’s location in the tree.

createState():Creates the mutable state for this widget at a given location in the tree.

debugDescribeChildren():Returns a list of DiagnosticsNode objects describing this node’s children.

debugFillProperties():Add additional properties associated with the node.

noSuchMethod():Invoked when a nonexistent method or property is accessed.

toDiagnosticsNode():Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep.

toString():A string representation of this object.

toStringDeep():Returns a string representation of this node and its descendants.

toStringShallow():Returns a one-line detailed description of the object.

toStringShort():A short, textual description of this widget.

Implementation of Expanded Tile Widget

import 'package:flutter/material.dart';

/// Flutter code sample for [ExpansionTile] and [ExpansionTileController].

void main() {
  runApp(const ExpansionTileControllerApp());
}

class ExpansionTileControllerApp extends StatefulWidget {
  const ExpansionTileControllerApp({super.key});

  @override
  State<ExpansionTileControllerApp> createState() =>
      _ExpansionTileControllerAppState();
}

class _ExpansionTileControllerAppState
    extends State<ExpansionTileControllerApp> {
  final ExpansionTileController controller = ExpansionTileController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(useMaterial3: true),
      home: Scaffold(
        appBar: AppBar(title: const Text('ExpansionTileController Sample')),
        body: Column(
          children: <Widget>[
            // A controller has been provided to the ExpansionTile because it's
            // going to be accessed from a component that is not within the
            // tile's BuildContext.
            ExpansionTile(
              controller: controller,
              title: const Text('ExpansionTile with explicit controller.'),
              children: <Widget>[
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.all(24),
                  child: const Text('ExpansionTile Contents'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              child: const Text('Expand/Collapse the Tile Above'),
              onPressed: () {
                if (controller.isExpanded) {
                  controller.collapse();
                } else {
                  controller.expand();
                }
              },
            ),
            const SizedBox(height: 48),
            // A controller has not been provided to the ExpansionTile because
            // the automatically created one can be retrieved via the tile's BuildContext.
            ExpansionTile(
              title: const Text('ExpansionTile with implicit controller.'),
              children: <Widget>[
                Builder(
                  builder: (BuildContext context) {
                    return Container(
                      padding: const EdgeInsets.all(24),
                      alignment: Alignment.center,
                      child: ElevatedButton(
                        child: const Text('Collapse This Tile'),
                        onPressed: () {
                          return ExpansionTileController.of(context).collapse();
                        },
                      ),
                    );
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Conclusion

So, in this article, we learned how to use the Expanded Tile widget. You can change and update this Flutter code according to your requirements.

Wanna Level up Your Flutter game? Then check out our ebook The Complete Guide to Flutter Developement where we teach you how to build production grade cross platform apps from scratch.Do check it out to completely Master Flutter framework from basic to advanced level.

Also Read

How to use Filled Button in flutter

Leave a comment