Passing parameters to a State
While creating a stateful widget, I ran into a small linting error. The problem was, I was passing parameters to the constructor of the state during its initialization like,
class MyStateful extends StatefulWidget {
@override
MyState createState() => MyState(42);
}
This is apparently not a good pattern according to Flutter Devs because the StatefulWidget
’s fields are available to the State
via the widget
parameter anyway, so there’s no need to pass down parameters manually. But when I went to implement it using the widget
parameter, I faced several more problems.
For instance, I tried the following
class SomeState extends State<SomeStateful> {
List<String> strings = widget.strings;
// ...
}
But I immediately got an error saying
The instance member ‘widget’ can’t be accessed in an initializer. Try replacing the reference to the instance member with a different expression
From the error message, I concluded it was too soon to assign the value to the strings
variable during the initialization.
Then I decided to use late
and tried something like this,
class SomeState extends State<SomeStateful> {
late List<String> strings;
SomeState() {
strings = widget.strings;
}
// ...
}
Now, although there was no compilation error, the page failed to load and also did not give me any error. I’m not sure what to make of this, but since the act of passing parameters is trivial I thought there might be a more correct way of doing this and didn’t linger on the present problem.
Instead I tried,
class SomeState extends State<SomeStateful> {
late List<String> strings = widget.strings;
// ...
}
And to my surprise, I didn’t get any compilation errors! Also, it did the trick and displayed the content correctly.