I am taking this as a reference to expanding and collapsing of expansion tile-------Flutter - Collapsing ExpansionTile after choosing an item
What I want is if I one
Instead of having to maintain the active state in expansionCallback
like @Aravindh Kumar did, you can use ExpansionPanelList.radio
which accepts a list of ExpansionPanelRadio
as its children. This widget allows for at most one panel in the list to be open and maintains the active state for you automatically.
Refer to the flutter documentation for example usage.
// Flutter code sample for ExpansionPanelList.radio
// Here is a simple example of how to implement ExpansionPanelList.radio.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: MyStatefulWidget(),
),
);
}
}
// stores ExpansionPanel state information
class Item {
Item({
this.id,
this.expandedValue,
this.headerValue,
});
int id;
String expandedValue;
String headerValue;
}
List- generateItems(int numberOfItems) {
return List.generate(numberOfItems, (int index) {
return Item(
id: index,
headerValue: 'Panel $index',
expandedValue: 'This is item number $index',
);
});
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State
{
List- _data = generateItems(8);
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
child: _buildPanel(),
),
);
}
Widget _buildPanel() {
return ExpansionPanelList.radio(
initialOpenPanelValue: 2,
children: _data.map
((Item item) {
return ExpansionPanelRadio(
value: item.id,
headerBuilder: (BuildContext context, bool isExpanded) {
return ListTile(
title: Text(item.headerValue),
);
},
body: ListTile(
title: Text(item.expandedValue),
subtitle: Text('To delete this panel, tap the trash can icon'),
trailing: Icon(Icons.delete),
onTap: () {
setState(() {
_data.removeWhere((currentItem) => item == currentItem);
});
}));
}).toList(),
);
}
}