Last active
May 22, 2022 05:50
-
-
Save bharathraj-e/7a71a6d73ed000b137f767760bad8e16 to your computer and use it in GitHub Desktop.
Expansion panel - single expanded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(const MyApp()); | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
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: const MyStatefulWidget(), | |
), | |
); | |
} | |
} | |
// stores ExpansionPanel state information | |
class Item { | |
Item({ | |
required this.expandedValue, | |
required this.headerValue, | |
this.isExpanded = false, | |
}); | |
String expandedValue; | |
String headerValue; | |
bool isExpanded; | |
} | |
List<Item> generateItems(int numberOfItems) { | |
return List<Item>.generate(numberOfItems, (int index) { | |
return Item( | |
headerValue: 'Panel $index', | |
expandedValue: 'This is item number $index', | |
); | |
}); | |
} | |
class MyStatefulWidget extends StatefulWidget { | |
const MyStatefulWidget({Key? key}) : super(key: key); | |
@override | |
State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); | |
} | |
class _MyStatefulWidgetState extends State<MyStatefulWidget> { | |
final List<Item> _data = generateItems(8); | |
@override | |
Widget build(BuildContext context) { | |
return SingleChildScrollView( | |
child: Container( | |
child: _buildPanel(), | |
), | |
); | |
} | |
Widget _buildPanel() { | |
return ExpansionPanelList( | |
expansionCallback: (int index, bool isExpanded) { | |
setState(() { | |
for(int i = 0; i<_data.length; i++){ | |
_data[i].isExpanded = false; | |
} | |
_data[index].isExpanded = !isExpanded; | |
}); | |
}, | |
children: _data.map<ExpansionPanel>((Item item) { | |
return ExpansionPanel( | |
canTapOnHeader: true, | |
headerBuilder: (BuildContext context, bool isExpanded) { | |
return ListTile( | |
title: Text(item.headerValue), | |
); | |
}, | |
body: ListTile( | |
title: Text(item.expandedValue), | |
subtitle: | |
const Text('To delete this panel, tap the trash can icon'), | |
trailing: const Icon(Icons.delete), | |
onTap: () { | |
setState(() { | |
_data.removeWhere((Item currentItem) => item == currentItem); | |
}); | |
}), | |
isExpanded: item.isExpanded, | |
); | |
}).toList(), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment