I am using ExpansionPanel
in flutter(v3.0.4
) like this(this is the minimal reproduce example):
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget buildNewTasks(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 2,
itemBuilder: (BuildContext context, int index) {
return Text(index.toString());
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
ExpansionPanelList(
children: [
ExpansionPanel(
headerBuilder: (context, isExpanded) {
return ListTile(
title: Text("Todo"),
);
},
body: buildNewTasks(context),
isExpanded: true,
canTapOnHeader: true),
],
)
],
));
}
}
when I click the ExpansionPanel
header, the child did not expand or collapse. Am I missing something? what should I do to make the ExpansionPanel expand and collapse when click the header?
CodePudding user response:
Yes, you have missed the expansionCallback which calls when the collapse/expand happens and isExpanded property value should be dynamic. it will need to change while collapsing or expanding.
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget buildNewTasks(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 2,
itemBuilder: (BuildContext context, int index) {
return Text(index.toString());
},
);
}
bool active = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
ExpansionPanelList(
expansionCallback: (panelIndex, expanded) {
active = !active;
setState(() {});
},
children: [
ExpansionPanel(
headerBuilder: (context, isExpanded) {
return ListTile(
title: Text("Todo"),
);
},
body: buildNewTasks(context),
isExpanded: active,
canTapOnHeader: true),
],
)
],
));
}
}