1

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)

1
  • To elaborate on why I want to avoid the two mentioned problems: 1) seems wasteful 2) compile time null-safety checks are preferred to runtime checks imo. Commented Jul 3, 2022 at 10:52

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

You could use the constructor of State like this: _MyWidgetState(){ text=widget.text; }. The constructor will certainly be executed before initState and build methods.

2 Comments

Unfortunately this does not work. Initializing the variable in the constructor body is to late (Non-nullable instance field 'text' must be initialized. Try adding an initializer expression.), but doing it in the initializer as _MyWidgetState() : text=widget.text; doesn't work either (The instance member 'widget' can't be accessed in an initializer.)
I found that you can take another approach like _MyWidgetState(this.text);. And at widget State<MyApp> createState() => _MyWidgetState(text); pass the variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.