How to Expand only one ExpansionTile at a time in Flutter

Issue

I have built a Listview with ExpansionTile. But Now I want that if I tap on an ExpansionTile then only that ExpansionTile should open and other Expanded ExpansionTile should close.

Please help me how can I achieve this?

Here is my Code for ExpansionTile

   @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text("Short Product"),
            ),
            body: ListView.builder(
              itemCount: Category_List.length,
              itemBuilder: (context, i) {
                return ExpansionTile(
                  title: Text(Category_List[i].cat_name),
                  children:_Product_ExpandAble_List_Builder(Category_List[i].cat_id)
                );
              },
            )
         );
      }

      _Product_ExpandAble_List_Builder(int cat_id) {
        List<Widget> columnContent = [];
        Product_List.forEach((product) => {
                columnContent.add(
                  ListTile(
                    title: ExpansionTile(
                        title: Text(product.prod_name),
                        ),
                    trailing: Text("${product.total_Qty} (Kg)"),
                  ),
                ),
            });
        return columnContent;
      }
}

Thanks in advance.

Solution

you can programmatically change expansion tile should open or close.

I made similar to your code.

int selected; //attention

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Short Product"),
      ),
      body: ListView.builder(
        key: Key('builder ${selected.toString()}'), //attention
        itemCount: 10,
        itemBuilder: (context, i) {
          return ExpansionTile(
              key: Key(i.toString()), //attention
              initiallyExpanded: i == selected, //attention
              title: Text(i.toString()),
              children: _Product_ExpandAble_List_Builder(i),
              onExpansionChanged: ((newState) {
                if (newState)
                  setState(() {
                    selected = i;
                  });
                else
                  setState(() {
                    selected = -1;
                  });
              }));
        },
      ),
    );
  }

  _Product_ExpandAble_List_Builder(int cat_id) {
    List<Widget> columnContent = [];
    [1, 2, 4, 5].forEach((product) => {
          columnContent.add(
            ListTile(
              title: ExpansionTile(
                title: Text(product.toString()),
              ),
              trailing: Text("$product (Kg)"),
            ),
          ),
        });
    return columnContent;
  }

Answered By – Viren V Varasadiya

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.