concept StatefulWidget in category flutter

appears as: A StatefulWidget, StatefulWidget, StatefulWidget
Flutter in Action

This is an excerpt from Manning's book Flutter in Action.

A StatefulWidget in the shopping cart application, on the other hand, is the QuantityCounter widget, because it’s managing a piece of stateful data that tracks the number of items you wish to add to your cart. A StatefulWidget object has an associated State object. The State object has special methods such as setState that tell Flutter when it needs to think about repainting.

Figure 3.6. StatefulWidget lifecycle
Listing 3.11. The FancyButton custom widget
class FancyButton extends StatefulWidget {
  final VoidCallback onPressed;
  final Widget child;

  const FancyButton({Key key, this.onPressed, this.child}) : super(key: key);

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

class _FancyButtonState extends State<FancyButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: RaisedButton(
        color: _getColors(),                                             #1
        child: widget.child,
        onPressed: widget.onPressed,
      ),
    );
  }

  Color _getColors() {
    return _buttonColors.putIfAbsent(this, () => colors[next(0, 5)]);    #2
  }
}

Map<_FancyButtonState, Color> _buttonColors = {};                        #3
final _random =  Random();                                               #3
int next(int min, int max) => min + _random.nextInt(max - min);          #3
 List<Color> colors = [                                                  #3
  Colors.blue,                                                           #3
  Colors.green,                                                          #3
  Colors.orange,                                                         #3
  Colors.purple,                                                         #3
  Colors.amber,                                                          #3
  Colors.lightBlue,                                                      #3
];                                                                       #3
  • Deep dive into the StatefulWidget. This is information you need regardless of your state management approach.
  • sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest