StatelessWidget vs StatefulWidget in Flutter

Share this post

In Flutter everything is a Widget. Whether it’s a Button or a whole page consisting of many elements. Web developers and especially React developers should see Widgets as Components. These Widgets could be something simple like a Button or an Image or something more advanced like a Counter widget.

A simple Button or an Image widget simply show information and don’t need to be re-rendered once shown. That means that the value they hold is not necessarily updated. However, a counter widget needs to update some number.

The following SimpleButton class represents a button with a text and a press callback function:

class SimpleButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
     child: Text("Press me"),
     onPressed() {
      print("Pressed!")
     },
    );
  }
}

Of course, we could customize the button as much as we want, but it will stay a StatelessWidget.

Now let’s try and make some changes to the same widget to make it Stateful:

class SimpleButtonCounter extends StatefulWidget {
  @override
  SimpleButtonCounterState createState() => SimpleButtonCounterState();
}
class SimpleButtonCounterState extends State<SimpleButtonCounter>() {

  int _counter = 0;

  @override
  initState() {
    super.initState();
   // we could also initialise the counter here
   // _counter = 0;
  }

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
     child: Text("Pressed ${_counter} times"),
     onPressed() {
      setState(() {
       _counter++;
      });
     },
    );
  }
}

setState() is the key here. Every time we want to change the value that was used in our build() method, we need to call setState(). Otherwise, the build() method won’t be called and the change won’t be visible. To compare with React and Vue, you could think of StatelessWidget as a Functional Component and StatefulWidget as a “normal” component.

In my future posts, I will post about common things you should know to create your first application with Flutter.