Flutter Stateful Widget example

In this tutorial, we’re gonna look at the difference between stateless and stateful widgets, then we will build a Flutter App that uses stateful widget to update state.

Stateful and stateless widgets

Stateless widget

A stateless widget is a subclass of StatelessWidget, it has no internal state to manage, there is no need to redraw them when something happens.

For example, Icon, IconButton, and Text are stateless widgets.

Stateful widget

A stateful widget is a subclass of StatefulWidget.
We can interact with it (type into a Form, move a Slider). Its state can change over time with a data feed that causes the UI to update (like a Slider’s current value).

For example, Checkbox, Slider, InkWell, Form, TextField are stateful widgets.

A widget’s state is stored in a State object. When the state changes, the State object calls setState() to tell the framework to redraw the widget.

Create stateful widget

Example Overview

We will build a Flutter App that has stateful widget named Counter.
When clicking on Increase/Decrease button, the state value will change and update on UI immediately:

flutter-stateful-widget-example-overview

Step by step

We need to creat two classes:
– A subclass of StatefulWidget that defines the widget.
– A subclass of State that contains the state for the widget, it will implement build() method.

Subclass StatefulWidget

Our Counter class will manage its own state, so it overrides createState() for State object. Flutter framework calls createState() to create an instance of _CounterState when building the widget.

Subclass State

_CounterState class stores mutable value in _counter variable that can change over the lifetime of the widget.

This State object also implement build() method that creates a Text for showing counter value and two FlatButtons for changing the counter value with onPressed property that defines the callback method.

_increaseCounter() and _decreaseCounter() method, which is called when the FlatButton is tapped, calls setState(). This tells the framework that the widget’s state has changed and the widget should redraw.

Practice

Create a Custom StatefulWidget

Create new counter.dart file at lib/ui/ for Counter class:

Inflate and attach stateful widget to screen

main.dart

Source Code

stateful_widget_example

By grokonez | July 4, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*