Flutter Stateful and Stateless Widgets

Baran Aslankan
BAU Yazılım ve Bilişim Kulübü
3 min readDec 27, 2021

When it comes to Flutter, the main starts are the widgets, in Flutter there are mainly two types of widgets; stateful and stateless widgets. Today i am going to explain those terms.

What is state ?

A state is the property of the widget that can change after the built as long as the widget is there. For example, a checkbox has a state and when we check it or uncheck it, the state also changes.

Stateless Widgets

So we have covered what a state is but there are also stateless widgets in flutter. After the app is built the states of those widgets can’t be changed. For example icon or text widgets.

Example of Stateless Widgets

import 'package:flutter/material.dart';class Stateless_ex extends StatelessWidget {
const Stateless_ex({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Stateless Widget"),
),
body: Center(
child: Icon(
Icons.add_circle_outline_sharp,
),
),
),
);
}
}

Example of Stateless Widgets

import 'package:flutter/material.dart';class Stateless_ex extends StatelessWidget {
const Stateless_ex({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Stateless Widget"),
),
body: Center(
child: Icon(
Icons.add_circle_outline_sharp,
),
),
),
);
}
}

I have created an app bar and it has a text widget, there is also an icon widget, and i didn’t add any state changer so they will remain the same after the built.

Stateful Widgets

The widgets that their state can change after the built and can also change multiple times as long as the widget is there.

Example of Stateful Widgets

Before we see an example of stateful widgets let’s see what set State is;

setState Method

When we change a state of a widget, we call setState method to see the changes on use.

Now let’s see an example;

import 'package:flutter/material.dart';

class Stfull_ex extends StatefulWidget {
const Stfull_ex({Key key}) : super(key: key);

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

class _Stfull_exState extends State<Stfull_ex> {

bool _isPressed=false;

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FlatButton(
color: _isPressed ? Colors.amber:Colors.black,
onPressed: (){
setState(() {
_isPressed=!_isPressed;
});
},
),
),
); }
}

In this code i declared a boolean variable to control the color of the button in state changes, i created a button in the center of the app and when pressed the state of the variable changes thus the color of the button changes, i also used setState method to see the state change immediately.

Here is the output;

That was all from me today, thanks for reading hope you enjoyed it ;)

--

--