I saw two ways to declare variables with StatefulWidget in many sample codes.
Is there any difference between these? Or which one would be better code in practice?
class Sample extends StatefulWidget {
Sample({Key key}) : super(key: key);
@override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> {
bool firstCase = false;
bool secondCase;
@override
void initState() {
secondCase = false;
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: child,
);
}
}
Steps to Pass Data to Stateful Widget in Flutter To pass data to stateful widget, first of all, create two pages. Now from the first page open the second page and pass the data. Inside the second page, access the variable using the widget. For example widget.
Flutter – initSate() The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is basically the entry point for the Stateful Widgets.
How to Declare Variable in Dart. We need to declare a variable before using it in a program. In Dart, The var keyword is used to declare a variable. The Dart compiler automatically knows the type of data based on the assigned to the variable because Dart is an infer type language.
If you can create initialise your variable directly in the property, do so. It's better for readability (a single place to look for).
The only reason you'll want to use initState
is for when you cannot initialise the variable directly from its declaration.
These situations are for the most part:
widget
or context
this
For example, if you want to create an AnimationController
you'll need to pass it vsync: this
. But the following won't compile:
class MyState extends State with SingleTickerProviderStateMixin {
final myController = AnimationController(
vsync: this, // compile error, cannot use `this` on initialisers
);
}
And you'd have to instead write:
class MyState extends State with SingleTickerProviderStateMixin {
AnimationController myController;
@override
void initState() {
super.initState();
myController = AnimationController(
vsync: this, // OK
);
}
}
Although note that this specific example will soon change as a future version of Dart will introduce the late
keyword, which then allows:
class MyState extends State with SingleTickerProviderStateMixin {
late final myController = AnimationController(
vsync: this, // OK, not a compile error this time
);
}
You may still need initState
for variables that depends on widget
/context
though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With