0

When creating a stateful widget in flutter, you may want some fields of the widget to not be mutated. In that case, I'm having trouble trying to figure out if it is better to always reference those fields from the state's widget reference, or if it's better to declare those fields in the state still, and get any initial values from the widget. For example:

class MyStatefulWidget extends StatefulWidget {
    final bool? mutateMe; // allows the user to provide an initial value of a mutable field
    final bool? doNotMutateMe; // allows the user to provide the value of a field that is not intended to be mutated

    MyStatefulWidget({ super.key, this.mutateMe, this.doNotMutuateMe });

    @override State<MyStatefulWidget> createState() => MyStatefulWidgetState();
}

class MyStatefulWidgetState extends State<MyStatefulWidget> {
    late bool mutateMe;
    late bool doNotMutateMe; // <-- HERE: is it better to include this field here?

    @override void initState() {
        mutateMe = widget.mutateMe ?? true; 
        doNotMutateMe = widget.doNotMutateMe ?? false;
    }

    // ...
}

For a field like doNotMutateMe, that is not intended to be modified, does it make sense to re-create the field in the state object, or not, and always just refer to widget.doNotMutateMe instead? I've read that the state object outlives the widget, so I'm curious what implications that might have here?

1 Answer 1

1

As you've included , I will prefer using widget.variableName on state class

class MyStatefulWidget extends StatefulWidget {
  final bool? mutateMe;
  final bool? doNotMutateMe;

  const MyStatefulWidget({
    super.key,
    this.mutateMe = true,
    this.doNotMutateMe = false,
  });

  @override
  State<MyStatefulWidget> createState() => MyStatefulWidgetState();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a reason that is better?
I cant think of>> we are setting default value while creating the widget

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.