Display Expansion Panel in Flutter

Display Expansion Panel in Flutter

An expansion panel is expandable container that has a header and a body. A panel has two states - collapsed or expanded. The body of the panel is only visible when it is expanded.

We define a MyPanelItem class to hold information about panel item. We use ExpansionPanelList to lay out expansion items defined as ExpansionPanel.

import 'package:flutter/material.dart'; void main() => runApp(const MaterialApp(home: MyApp())); class MyPanelItem { bool isExpanded; final String header; final String body; MyPanelItem({this.header = '', this.body = '', this.isExpanded = false}); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final List<MyPanelItem> _items = <MyPanelItem>[ MyPanelItem(header: "Header 1", body: "Body 1"), MyPanelItem(header: "Header 2", body: "Body 2"), MyPanelItem(header: "Header 3", body: "Body 3"), ]; Widget _buildPanel() { return ExpansionPanelList( expansionCallback: (int index, bool isExpanded) { setState(() { _items[index].isExpanded = !isExpanded; }); }, children: _items.map((MyPanelItem item) { return ExpansionPanel( isExpanded: item.isExpanded, headerBuilder: (BuildContext context, bool isExpanded) { return ListTile(title: Text(item.header)); }, body: ListTile(title: Text(item.body)), ); }).toList(), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Expansion panel')), body: ListView( children: <Widget>[ _buildPanel(), ], ), ); } }

Leave a Comment

Cancel reply

Your email address will not be published.