'How to Collapse already opened expansion Tiles after clicking on another expansion Tile in Flutter?
i am using multiple expansion tiles in my app. i need to close already opened tile after clicking on another. i have tried using expansion panel which by default having that functionality. But i need to re Design expansion tile so i am using expansion Tile. how to achieve that functionality in expansion tile
Solution 1:[1]
This answer in GitHub should do the trick.
Here is the sample:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ExpansionTile Collapse',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'ExpansionTile Collapse'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// selected's value = 0. For default first item is open.
int selected = 0; //attention
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('ExpansionTile Collapse',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
),
body: Container(
color: Colors.white,
child: SingleChildScrollView(
child: Column(children: [
ListView.builder(
key: Key('builder ${selected.toString()}'), //attention
padding: EdgeInsets.only(left: 13.0, right: 13.0, bottom: 25.0),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: 5,
itemBuilder: (context, index) {
return Column(children: <Widget>[
Divider(
height: 17.0,
color: Colors.white,
),
ExpansionTile(
key: Key(index.toString()), //attention
initiallyExpanded: index == selected, //attention
leading: Icon(
Icons.person,
size: 50.0,
color: Colors.black,
),
title: Text('ExpansionTile ${index}',
style: TextStyle(
color: Color(0xFF09216B),
fontSize: 17.0,
fontWeight: FontWeight.bold)),
subtitle: Text(
'Software Engineer',
style: TextStyle(
color: Colors.black,
fontSize: 13.0,
fontWeight: FontWeight.bold),
),
children: <Widget>[
Padding(
padding: EdgeInsets.all(25.0),
child: Text(
'DETA?L ${index} \n' + 'Expanded',
),
)
],
onExpansionChanged: ((newState) {
if (newState)
setState(() {
Duration(seconds: 20000);
selected = index;
});
else
setState(() {
selected = -1;
});
}),
),
]);
},
)
]),
),
),
);
}
}
Actual output:
Solution 2:[2]
I would go for an ExpansionPanelList.radio, because in the above method you will loose the animation. Check out this link: ExpansionPanelList.radio usage.You don't have to keep track of the index, and it allows for at most one panel in the list to be open.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MαπμQμαπkγVπ.0 |
| Solution 2 |

