user14037074
user14037074

Reputation:

Using widget property VS taking arguments on state class

Given a stateful widget which takes arguments when it's called, there are two options (that I know of). I can either use widget.arg to access the data in the state object, or I can create new variables and a new constructor in the state object.

Now I've mostly used the second one and there are some use cases in which the first one causes some problems. However, it looks more concise and readable (I guess).

My question is which one is a better practice?

Example code:

First option:

class Home extends StatefulWidget {
  final String email;

  const Home({Key key, this.email}) : super(key: key);
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String example() {
    return widget.email;
  }

Second option:

class Home extends StatefulWidget {
final String email;
  const Home({Key key, this.email}) : super(key: key);
  @override
  _HomeState createState() => _HomeState(email);
}

class _HomeState extends State<Home> {
  final String email;
  _HomeState(this.email);



  String example() {
        return email;
      }

Upvotes: 0

Views: 629

Answers (2)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277587

Don't use the second option, aka having a constructor on State. This is a bad practice.
Use the .widget.property syntax instead.

If you purposefully want to ignore the updates of a property, instead use initState:

class Example {
  Example(this.initialText);

  final String initialText;

  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  String text;

  @override
  void initState() {
    text = widget.initialText;
  }
}

Upvotes: 0

RegularGuy
RegularGuy

Reputation: 3686

I use both approaches, however, i don't use a constructor for the second approach because idk i don't like it. I store a reference in initState. Something like email = widget.email;.

It really depends. It's mostly preference. But i use the widget. approach often, it avoids boilerplate code, and it's a way of identifying which arguments come from the widget vs whcih arguments come from the state.

The flutter team also uses this approach. A LOT. Check the Material AppBar source code. It would be a mess to declare the arguments twice and pass them to _AppBarState. It's cleaner and it works for them. And for me ;)

Upvotes: 0

Related Questions