Hello so basically I want to know why setState() works on widgets extracted as methods but does not work on widgets extracted as widgets....
and also when to use extracted widgets/ extracted widgets as methods or are they both the same? but I guess they cant be the same since one works and other doesnt?
If you want the code i tried before changing it to extracted methods:
from main class:
void refresh() => setState(() {});
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.blue,
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: const [
SizedBox(height: 50),
PageHeader(),
PageBody(),
],
),
floatingActionButton: AddTaskButton(
transitionAnimationController: transitionAnimationController,
refresh: refresh,
),
),
);
}
Extracted widgets:
class PageHeader extends StatelessWidget {
const PageHeader({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const CircleAvatar(
radius: 30,
backgroundColor: Colors.white,
child: Icon(
Icons.list,
color: Colors.blue,
size: 30,
),
),
const SizedBox(
height: 15,
),
const Text(
'Todoey',
style: TextStyle(color: Colors.white, fontSize: 35),
),
Text(
' ${TaskData.tasks.length} Tasks',
style: const TextStyle(color: Colors.white, fontSize: 15),
),
],
),
),
);
}
}
class PageBody extends StatelessWidget {
const PageBody({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Expanded(
flex: 3,
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: TaskList(taskData: TaskData.tasks),
),
),
);
}
}
Extracted Methods:
Expanded pageHeader() {
return Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const CircleAvatar(
radius: 30,
backgroundColor: Colors.white,
child: Icon(
Icons.list,
color: Colors.blue,
size: 30,
),
),
const SizedBox(
height: 15,
),
const Text(
'Todoey',
style: TextStyle(color: Colors.white, fontSize: 35),
),
Text(
' ${TaskData.tasks.length} Tasks',
style: const TextStyle(color: Colors.white, fontSize: 15),
),
],
),
),
);
}
}
Expanded pageBody() {
return Expanded(
flex: 3,
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: TaskList(taskData: TaskData.tasks),
),
),
);
}