Reputation: 111
I want to have a StatefulWidget
where I can pass the initial value for a non-nullable member of the widgets State
from the widgets constructor.
My current solution (see below) seems to be not ideal, I see two problems with it:
late
since it can only be set after initialization.Is there a better way to initialize a StatefulWidget
's state non-nullable member from a value passed to the widget constructor?
My current implementation:
class MyWidget extends StatefulWidget {
final String text;
const MyWidget({Key? key, required this.text}) : super(key: key);
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
late String text;
@override
void initState() {
text = widget.text;
super.initState();
}
@override
Widget build(BuildContext context) {
return Text(text);
}
}
(Not shown here, but later the text
member should be changeable, that's why it is in the State
)
Upvotes: 1
Views: 1316
Reputation: 96
You could use the constructor of State like this: _MyWidgetState(){ text=widget.text; }
. The constructor will certainly be executed before initState and build methods.
Upvotes: 0
Reputation: 202
hey there your code seems good. but the better way is using bloc to pass and receive data. any way . its not necessary to pass and fill data in initstate and _MyWidgetState . you can receive your data directly in build widget As you wrote (widget.text) here is some good things for avoid nullable https://codewithandrea.com/videos/dart-null-safety-ultimate-guide-non-nullable-types/
Upvotes: 1