Changing title of ExpansionTile, when expanded in flutter

177 views Asked by At

I want to change ExpansionTile title in flutter, so when tile is expanded, title is "less" and when tile isn't expanded, title is "more"...

I already tried using ExpansionTileController.isExpanded? "less": "more", but I get error: Failed assertion: line 49 pos 12: '_state != null': is not true.

1

There are 1 answers

0
ph.zeng On BEST ANSWER

You can add parameter isExpanded into is and set setState in onExpansionChanged.

The sample code follows below:

class CustomExpansionTile extends StatefulWidget {
  const CustomExpansionTile({
    super.key,
    required this.level,
    required this.person,
  });

  final int level;
  final Person person;

  @override
  State<CustomExpansionTile> createState() => _CustomExpansionTileState();
}

class _CustomExpansionTileState extends State<CustomExpansionTile> {
  bool isExpanded = false; // Add this

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(
        dividerColor: Colors.transparent,
      ),
      child: ExpansionTile(
        onExpansionChanged: (bool expanded) {
          // Add this
          setState(() {
            isExpanded = expanded;
          });
        },
        title: Text(widget.person.name),
        leading: Icon(
          isExpanded ? Icons.expand_more : Icons.chevron_right, // Using
        ),
        trailing: const Text(''),
        children: widget.person.subPersons
            .map((sp) => Padding(
                  padding: const EdgeInsets.only(left: 24.0),
                  child: CustomExpansionTile(
                    person: sp,
                    level: widget.level + 1,
                  ),
                ))
            .toList(),
      ),
    );
  }
}

Result:

enter image description here