Flutter Puzzle (I)

Flutter is an aspiring cross platform development framework. It has its quirks and features.

Flutter Puzzle (I)
Photo by Shirley Cairns / Unsplash

Let's have a look at a variant of the sample counter app. Its source code is available on Dartpad. The application also can be run there.

The buttons do as they are named, they increment and decrement the counter. On the bottom right is a floating button. It resets the counter, and swaps the buttons.

On reset, the texts and the callbacks on the buttons change, but the color stays in its original position.

This is not a bug, but the way Flutter updates components.

On setState() the widgets will be recreated, and the corresponding entries in the element tree will be updated. In this very example there's no direct mapping from widget to element. So the button elements still refer to the widgets at the previous position. Since state is part of an element, the buttons don't changes colors.

If keys are added to the widget, their color will also be swapped:

final incrementButton = FancyButton(
    key: const Key("inc"),
    onPressed: () => _incrementCounter(), child: const Text("Increment"));

final decrementButton = FancyButton(
  key: const Key("dec"),
    onPressed: _decrementCounter, child: const Text("Decrement"));

To see the build up of this example and way more detailed explanations, have a look into Flutter in Action by Eric Windmill.