Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 73 ยท Material, styling and assets

ExpansionTile, Stepper, DataTable and Table

Show collapsible lists with ExpansionTile, guided flows with Stepper, and tabular data with DataTable and Table, including sorting, column widths and scrolling.

Not every screen is a list of cards. Settings pages hide detail behind headings, checkout flows walk people through steps, and admin screens show rows and columns. Flutter ships Material widgets for each: ExpansionTile for collapsible sections, Stepper for multi-step flows, and DataTable and Table for grids of data.

Real vs stand-in. The Dart is real and read-only here (the site cannot run Flutter). The live examples are JavaScript stand-ins of the logic you write around the widgets: step validation, and sorting rows by a column.

ExpansionTile

An ExpansionTile is a ListTile that opens to reveal children. It animates the arrow and the height for you.

DART
ExpansionTile(
  leading: const Icon(Icons.local_shipping),
  title: const Text('Shipping'),
  subtitle: const Text('2 to 5 business days'),
  initiallyExpanded: false,
  onExpansionChanged: (open) => debugPrint('shipping open: $open'),
  childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
  expandedCrossAxisAlignment: CrossAxisAlignment.start,
  children: const [
    Text('Standard delivery is free over 50 USD.'),
    SizedBox(height: 8),
    Text('Express delivery is available at checkout.'),
  ],
)

When a list of tiles scrolls, the open/closed state of each tile lives in the tile's own State. A tile scrolled far off screen can be disposed and come back closed. Give each tile a PageStorageKey('shipping') so the framework can restore it, or store the open flags in your own state. To allow only one open section at a time, either track the open index yourself with initiallyExpanded and a key, or use ExpansionPanelList.radio, the older panel API that coordinates panels for you.

Stepper

Stepper shows a numbered sequence with a "Continue" and "Cancel" button under the current step. It does not know what your steps mean: you own currentStep and move it.

DART
class CheckoutStepper extends StatefulWidget {
  const CheckoutStepper({super.key});
  @override
  State<CheckoutStepper> createState() => _CheckoutStepperState();
}

class _CheckoutStepperState extends State<CheckoutStepper> {
  int _step = 0;
  final _address = TextEditingController();

  List<Step> get _steps => [
    Step(
      title: const Text('Address'),
      isActive: _step >= 0,
      state: _step > 0 ? StepState.complete : StepState.indexed,
      content: TextField(controller: _address, decoration: const InputDecoration(labelText: 'Street')),
    ),
    Step(
      title: const Text('Payment'),
      isActive: _step >= 1,
      state: _step > 1 ? StepState.complete : StepState.indexed,
      content: const Text('Choose a card'),
    ),
    Step(
      title: const Text('Review'),
      isActive: _step >= 2,
      content: const Text('Everything looks right?'),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Stepper(
      type: StepperType.vertical,           // or StepperType.horizontal
      currentStep: _step,
      steps: _steps,
      onStepTapped: (i) => setState(() => _step = i),
      onStepCancel: _step == 0 ? null : () => setState(() => _step -= 1),
      onStepContinue: () {
        if (_step == 0 && _address.text.trim().isEmpty) return;   // validate first
        if (_step < _steps.length - 1) setState(() => _step += 1);
        else _placeOrder();
      },
    );
  }

  void _placeOrder() {/* submit */}
}

StepState (indexed, editing, complete, disabled, error) controls the icon in the circle, and isActive colors it. Putting the validation in onStepContinue is the usual pattern: if a step is invalid, simply do not advance, and show an errorText on the field or mark the step StepState.error. The widget is intentionally basic. If you need a polished wizard, build your own with a PageView (PageView in the tabs lesson) and a progress indicator.

JS A stepper's validation state machine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

DataTable

DataTable draws a Material table: header cells, body rows, optional sorting and row selection. You describe columns and rows, and it measures the content.

DART
class ProductTable extends StatefulWidget {
  const ProductTable({super.key, required this.products});
  final List<Product> products;
  @override
  State<ProductTable> createState() => _ProductTableState();
}

class _ProductTableState extends State<ProductTable> {
  int? _sortColumn;
  bool _ascending = true;
  late List<Product> _rows = [...widget.products];

  void _sort<T extends Comparable<T>>(int column, T Function(Product) key, bool asc) {
    _rows.sort((a, b) => asc ? key(a).compareTo(key(b)) : key(b).compareTo(key(a)));
    setState(() { _sortColumn = column; _ascending = asc; });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
        sortColumnIndex: _sortColumn,
        sortAscending: _ascending,
        columns: [
          DataColumn(label: const Text('Name'), onSort: (i, asc) => _sort(i, (p) => p.name, asc)),
          DataColumn(label: const Text('Price'), numeric: true, onSort: (i, asc) => _sort(i, (p) => p.price, asc)),
          const DataColumn(label: Text('Stock'), numeric: true),
        ],
        rows: [
          for (final p in _rows)
            DataRow(cells: [
              DataCell(Text(p.name)),
              DataCell(Text(p.price.toStringAsFixed(2))),
              DataCell(Text('${p.stock}')),
            ]),
        ],
      ),
    );
  }
}

The widget only shows the sort arrow. Sorting your list is your job, in the onSort callback. Mark numeric columns numeric: true so they right-align. A DataTable builds all its rows at once, so it suits tens of rows. For hundreds, use PaginatedDataTable (pages of rows from a DataTableSource) or a lazy ListView of Rows. Because the table has a natural width, wrapping it in a horizontal SingleChildScrollView prevents overflow on a phone, and a vertical one handles the height.

JS Sorting rows by a column, ascending and descending

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Table

Table is the lightweight sibling: no header semantics, no sorting, just a grid of widgets whose columns line up. It is good for a spec sheet, a price list or a small form layout.

DART
Table(
  border: TableBorder.all(color: Colors.black12),
  columnWidths: const {
    0: FlexColumnWidth(2),       // twice the share
    1: FixedColumnWidth(80),     // exactly 80 logical pixels
    2: IntrinsicColumnWidth(),   // as wide as the widest cell (slow on big tables)
  },
  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
  children: const [
    TableRow(children: [Text('Item'), Text('Qty'), Text('Note')]),
    TableRow(children: [Text('Pencil'), Text('12'), Text('HB')]),
  ],
)

Every TableRow must have the same number of children. Prefer FlexColumnWidth and FixedColumnWidth; IntrinsicColumnWidth measures every cell and costs layout time. The default width is an equal flex share. For tables that must scroll in both directions, or have frozen headers, look at packages such as data_table_2.

Choosing between them

You need Use
Show or hide detail under a heading ExpansionTile
A guided, ordered flow Stepper (or your own PageView)
Sortable Material table, dozens of rows DataTable
Hundreds of rows with pages PaginatedDataTable
A simple aligned grid of widgets Table

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who sorts the data when a DataTable column header is tapped?

    sortColumnIndex and sortAscending only control the arrow. You reorder the rows yourself.
  2. 2. Where does a Stepper keep the current step?

    Stepper is controlled: it shows the step you give it and reports taps through onStepTapped, onStepContinue and onStepCancel.
  3. 3. A DataTable overflows horizontally on a phone. What is the usual fix?

    The table has a natural width wider than the screen, so give it a scrollable parent.
  4. 4. Which column width setting for Table is slowest on big tables?

    IntrinsicColumnWidth measures every cell in the column to find the widest one.

Summary

  • ExpansionTile collapses detail; keep state with a PageStorageKey or your own flags.
  • Stepper is controlled: you own currentStep, validate in onStepContinue, and set StepState.
  • DataTable displays sorting but you sort; make it scrollable and use PaginatedDataTable for big data.
  • Table aligns widgets in columns with FlexColumnWidth and FixedColumnWidth.

Next: RichText, Text.rich and FittedBox