I have a list of ExpansionTile with a list of ListTile in a Drawer. What I want to achieve is, when I press an ExpansionTile, the another ExpansionTile must be collapsed. I had been stuck with this problem for two days and could not find an answer. Can anybody know how to collapse the ExpansionTile programmatically?
Note:
I don't want to mess up the animation of the widget.
Here is my code,
ListView.builder(
itemCount: userList.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, findex) {
return ExpansionTile(
key: Key(findex.toString()),
title: Text(userList[findex].parentdata[0].title,
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold,color: Colors.black),
),
onExpansionChanged: (value) {
},
children: [
ListView.builder(
itemCount: userList[findex].document.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, sindex) {
return ListTile(
title: Text(
userList[findex].document[sindex].title,
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold,color: Colors.black),
),
onTap: () {
print(
userList[findex].document[sindex].title);
},
);
},
),
],
);
},
),
CodePudding user response:
Try this:
Create a variable: int selected = -1;
And listview
:
ListView.builder(
itemCount: 10,
shrinkWrap: true,
itemBuilder: (BuildContext context, findex) {
return ExpansionTile(
initiallyExpanded: findex == selected,
key: Key(selected.toString()),
title: Text(userList[findex].parentdata[0].title,
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold,color: Colors.black),
),
onExpansionChanged: (newState) {
setState(() {
selected = findex;
});
},
children: [
ListView.builder(
itemCount: 10,
shrinkWrap: true,
itemBuilder: (BuildContext context, sindex) {
return ListTile(
title: Text(
userList[findex].document[sindex].title,
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold,color: Colors.black),
),
onTap: () {
print(userList[findex].document[sindex].title);
},
);
},
),
],
);
},
),
CodePudding user response:
Try below code
declare one int variable
int selectedTile = -1;
Your widget
ListView.builder(
key: Key(selectedTile.toString()),
itemCount: 5,
itemBuilder: (context, index) {
return ExpansionTile(
key: Key(index.toString()),
initiallyExpanded: index == selectedTile,
title: Text('ExpansionTile $index'),
subtitle: Text('Trailing expansion arrow icon'),
children: [
ListTile(
title: Text('This is tile number $index'),
),
],
onExpansionChanged: ((newState) {
if (newState)
setState(() {
selectedTile = index;
});
else
setState(() {
selectedTile = -1;
});
}),
);
},
);
CodePudding user response:
Use ExpansionPanel
widget.
You need to create a variable and maintain the expansion state of expansion panel index.
expansionCallback: (int index, bool isExpanded) {
setState(() {
// when any of expansionPanel is Tapped
// set all expansion to false
for(int i = 0; i<_data.length; i ){
_data[i].isExpanded = false;
}
// then set the tapped index to its state
_data[index].isExpanded = !isExpanded;
});
},