Which one is better approach for initialize flutter widget properties?
can someone explain which approach is better and why.
First one
having const constructor
and initialize properties in build
method.
class CustomStatusBar extends StatelessWidget {
const CustomStatusBar({
Key? key,
required this.report,
}) : super(key: key);
final Report report;
@override
Widget build(BuildContext context) {
final int open = report.open;
final int finished = report.finished;
final int terminated = report.terminated;
final int total = open finished terminated;
return MyWidget();
}
}
Second one
having Non-cost constructor
and initialize properties in constructor
.
class CustomStatusBar extends StatelessWidget {
CustomStatusBar({
Key? key,
required this.report,
}) :
open = report.open,
finished = report.finished,
terminated = report.terminated,
total = report.open report.finished report.terminated,
super(key: key);
final Report report;
final int open;
final int finished;
final int terminated;
final int total;
@override
Widget build(BuildContext context) {
return MyWidget();
}
}
CodePudding user response:
Second 100%, do not declare nothing in build method. The reason is that build method can be called multiple times during build of widget
CodePudding user response:
A constructor is a special function of the class that is responsible for initializing the variables of the class.
As per your example you are trying to initialise final variable of the class which you need to initialise when class is created. (variables with final keyword can't be reassigned and modified)
Also when you initialise variable in constructor it will be assigned once. But if you define it in build method it will assign each time when the widget rebuild. (Not in case of variables with final keyword)
So second approach is the best way to define a widget.