0

TL;DR: when do I pass a variable to a state contra access it from the widget.

I often come to a point when I must choose to either pass a property from my stateful widget to my state constructor, or use the widget.propertysyntax to access it directly from the Widget.

class MyWidget extends StatefulWidget {
  final myProperty;

  ParallaxView({this.myProperty});

  @override
  _MyWidgetState createState() => _MyWidgetState(myProperty);
}

class MyWidgetState extends State<MyWidget> {
  final myProperty;

  MyWidgetState({this.myProperty});

@override
  Widget build(BuildContext context) {
    return Container(child: myProperty); //<-using passed property
    return Container(child: widget.myProperty); //<-or, using widgets property?
  }

Is there a right way to go about this or is it only preference?

Joel Broström
  • 3,530
  • 1
  • 34
  • 61
  • see how for example [_ImageState](https://www.crossdart.info/p/flutter/0.0.38-dev/src/widgets/image.dart.html#line-443) makes it (check `build()` method) - other widgets do the same – pskink Apr 08 '19 at 08:29
  • Hi @Rémi Rousselet! You don't happen to have de duplicated questions link? I can't get find clear answer on when to use one over the other and without finding the duplicated question I cannot edit this one to explain how it's different. Cheers! – Joel Broström Apr 08 '19 at 08:41
  • Would you mind explaining why you think this is not a duplicate? I can reopen the question if needed, but I need to understand the reasoning first :) – Rémi Rousselet Apr 08 '19 at 08:46
  • My bad, I never saw the link at the top of the page. When I clicked the inbox link it took me to the bottom of the page where it says you marked it as duplicated. The other answer were great, recommend it to all who came here. – Joel Broström Apr 08 '19 at 12:40

0 Answers0