3

ExpansionTile force closes once it detects a scrolling behavior i.e immediately I scroll the page... I want to keep the ExpansionTile opened until I tapped on its title.

What could be the cause?

expansionTile force loses

Tayo.dev
  • 1,546
  • 3
  • 21
  • 31

2 Answers2

1

The reason your ExpansionTile is closing immediately is because when you scroll through a listview, especially one created with the ListView.builder the list is rebuilt again, so if you want to preserve the status of a certain ExpansionTile you should save its status value out of your build function and use the initiallyExpanded property:

   List<bool> status = <bool>[] ; //store the statuses of your tiles here

   ExpansionTile(
    title: Text('Item'),
    backgroundColor: Colors.transparent,
    initiallyExpanded: status[index],
   ),
Mazin Ibrahim
  • 7,433
  • 2
  • 33
  • 40
1

Add and remove indices from a list with onExpansionChanged callback and set initiallyExpanded if it contains that index.

class _WidgetState extends State<Widget> {
    
      List expandedIndices = [];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
           body: ListView.builder(
                    physics: const BouncingScrollPhysics(
                    parent: AlwaysScrollableScrollPhysics()),
                    itemCount: 10,
                    itemBuilder: (BuildContext context, int index) {
                        return ExpansionTile(
                            title: Text('Item'),
                             onExpansionChanged: (expanded) {
                                 if(expanded) {
                                     expandedIndices.add(index);
                                 }
                                 else{
                                     expandedIndices.remove(index);
                                 }
                             },
                             initiallyExpanded: expandedIndices.contains(index),);
                    } 
                )
            );
       }
  }
Yash
  • 369
  • 5
  • 18