I am trying to use provider with an ExpansionPanelList.
The issue is that I would need a new instance of provider for each ExpansionPanel but the ExpansionPanelList needs the expansionCallBack function which controls the state of the expansion (bool isExpanded).
This is the sample code using setState and StatefulWidget, and I am trying to port this to provider.
class ExpansionPanelProvider {
ExpansionPanelProvider({
this.expandedValue,
this.headerValue,
this.isExpanded = false,
});
String expandedValue;
String headerValue;
bool isExpanded;
/*void updateExpansionState() {
isExpanded = !isExpanded;
notifyListeners();
}*/
}
List<ExpansionPanelProvider> generateItems(int numberOfItems) {
return List.generate(numberOfItems, (int index) {
return ExpansionPanelProvider(
headerValue: 'Panel ${index + 1}',
expandedValue: 'This is item number ${index + 1}',
);
});
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
List<ExpansionPanelProvider> _data = generateItems(80);
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
child: _buildPanel(),
),
);
}
Widget _buildPanel() {
return ExpansionPanelList(
animationDuration: Duration(milliseconds: 800),
expansionCallback: (int index, bool isExpanded) {
setState(() {
_data[index].isExpanded = !isExpanded;
});
},
children: _data.map<ExpansionPanel>((ExpansionPanelProvider item) {
return ExpansionPanel(
canTapOnHeader: true,
isExpanded: item.isExpanded,
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(),
);
}
}
This code uses set strings and data which is to be displayed. My data comes from another provider.
[EDIT]
I tried wrapping ExpansionPanel in a ChangeNotifierProvider, but that didn't work because ExpansionPanel can be a child of only ExpansionPanelList Widget.