Nereos
Nereos

Reputation: 111

Initialize StatefulWidget state null safe from widget constructor in Flutter

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:

  1. The initial value has to be saved in the widget itself before passing it to the state.
  2. The member in the sate has to be marked as 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

Answers (2)

Felix
Felix

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

Golnar sheikh bahaie
Golnar sheikh bahaie

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

Related Questions