Flutter expansiontile collapse programmatically

Flutter ExpansionTile – Collapse Programmatically

To collapse an ExpansionTile programmatically in Flutter, you need to track the state of expansion and modify it accordingly. Here’s an example:


import 'package:flutter/material.dart';

class MyExpansionTile extends StatefulWidget {
  @override
  _MyExpansionTileState createState() => _MyExpansionTileState();
}

class _MyExpansionTileState extends State<MyExpansionTile> {
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return ExpansionTile(
      title: Text("Expandable Tile"),
      expandedCrossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text("Expanded widget goes here"),
      ],
      onExpansionChanged: (value) {
        setState(() {
          _isExpanded = value;
        });
      },
      initiallyExpanded: _isExpanded,
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text("ExpansionTile Example"),
      ),
      body: MyExpansionTile(),
    ),
  ));
}

In this example, we have created a stateful widget called MyExpansionTile. It has a boolean variable “_isExpanded” to keep track of the expansion state. The ExpansionTile widget is used to create the expandable tile. It takes the “onExpansionChanged” callback to handle the changes in the expansion state.

The onExpansionChanged callback set the “_isExpanded” variable according to the new expansion state. This will rebuild the widget and update the expansion state. Initially, the “initiallyExpanded” property is set to the current expansion state.

You can use this approach to programmatically expand or collapse ExpansionTile widget in Flutter based on your requirements.

Leave a comment