4

I have a StatefulWidget named BounceContainer. This class contains a parameter child like a typical Flutter widget. Basically, it bounces the child whenever the user taps on it. The way I pass the child parameter as of now is as follow:

class BounceContainer extends StatefulWidget {
    final Widget child;                 // Declaring "child"
    BounceContainer({this.child});      // Initializing "child"

    // Passing "child" to State

    @override
    _BounceContainerState createState() => _BounceContainerState(this.child);
}

class _BounceContainerState extends State<BounceContainer> {
    Widget child;
    _BounceContainerState(this.child);  // Receiving "child"

    @override 
    Widget build(BuildContext context) {
        ...
    }
}

The problem, in this case, is that even if the child parameter changes, the child itself does not update.

For example, if I have a button whose color changes from grey to any random color based on AnimationController and I pass this button as child parameter to BounceContainer class, the button still remains grey and calling setState() (either from the main program or BounceContainer class) also does not force update the child widget.

What's the proper way (and also efficient way) to work around this problem?

Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33
  • 4
    You don't need to pass all your parameters to State class. You can access with `widget.child`. – siega May 21 '19 at 20:18
  • @siega Thanks that worked for me! ✌ – Melvin Abraham May 21 '19 at 20:47
  • @siega is it good practice? im using it so often but don't know side effects of that – dubace May 22 '19 at 07:54
  • I think the greatest advantage here is to reduce code. Otherwise, if you have 10 parameters, you need to create 10 properties in the State and pass all this values down via constructor. @dubace – siega May 22 '19 at 11:20

1 Answers1

4

You don't need to pass all your parameters to State class. You can access them with widget.child

siega
  • 2,508
  • 1
  • 19
  • 22