Let’s build a simple Stateful Widget in Flutter

Let’s build a simple Stateful Widget in Flutter

Image courtesy: Flutter.dev

I am a web developer, I have done native android development using Java, I have done cross-platform development using Ionic and React-native but when I learned about flutter, I was little skeptical, ah… another hybrid mobile app technology. I was not ready for it mainly due to setting up the environment and learning a new language Dart.

But in the quarantine period, I decided to get my feet wet with flutter development and in a couple of days, I was able to build some fancy-looking apps with good functionality. I was mesmerized with the simplicity of the Development.

A simple 3 step development setup

  1. Install Flutter
  2. Setup the IDE / Editor plugins
  3. Setup the emulator

and you are done…

In this article, We will build a simple stateful widget in Flutter.

What is a Stateful Widget?

A flutter widget that can have different states which can be changed during the lifetime of the Widget.

Components of a Stateful widget

  • A Widget class which extends StatefulWidget class.
  • A State class that extends generic State class.

Let’s get started:

If flutter is up and running then you just need to start with

flutter create stateful_widget

It will create a simple flutter project with a button and click counter.

Let’s convert it to a simple Application to understand.

which will create an app which looks like this:

Since the App is simple now, let’s create our stateless widget.

  1. Extend the StatefulWidget

class MyApp extends StatefulWidget

2. Every Stateful Widget should have createState() which initializes the State.

class MyApp extends StatefulWidget {

@override

_MyState createState() => _MyState();

}

3. Create the State

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Demo',

theme: ThemeData(

primarySwatch: Colors.blue,

),

home: Scaffold(

appBar: AppBar(title: Text("A Simple App Stateful Widget")),

body: Container(decoration: BoxDecoration(color: _containerColor)),

floatingActionButton: FloatingActionButton(

onPressed: changeIcon,

child: Icon(Icons.add),

tooltip: "Book Here",

),

));

}

}

Here is the complete Code:

I know, it was fast, so let’s understand what is happening here:

The Project has a Stateless Widget named MyApp with State _MyState

In the state we have changeColor function which manages the States for the Widget. State that is the Dynamic Information is defined as Properties for the Stateful widget which can be manipulated and will be loaded dynamically in the widget.

For example, we are changing the Background color of the container from Colors.yellow to Colors.red which is getting called in the onPressed event of FloatingActionButton .

here is the Result:

I hope it helped you to understand stateful widgets in Flutter.