There are two types of widgets provided in Flutter.
- The Stateless Widget
- The Stateful Widget
As the name suggests Stateful Widgets are made up of some 'States'. The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is basically the entry point for the Stateful Widgets. initState() method is called only and only once and is used generally for initializing the previously defined variables of the stateful widget. initState() method is overridden mostly because as mentioned earlier it is called only once in its lifetime. If you want to trigger it again you have to shift the control to an entirely new screen and a new state. Let's understand it more clearly with the example below.
Example Project
Create a class named "stateExample" that extends a Stateful Widget.
class stateExample extends StatefulWidget {
@override
State<stateExample> createState() => _stateExampleState();
}
class _stateExampleState extends State<stateExample> {
@override
Widget build(BuildContext context) {
return Container();
}
}
Under the @override of the Stateful Widget call the initState() method.
@override
initState() {
print("initState Called");
}
Complete the rest of the code according to your requirements.
Implementation:
Dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text(
"GeeksforGeeks",
),
backgroundColor: Colors.green,
),
body: const stateExample(),
),
);
}
}
// ignore: camel_case_types
class stateExample extends StatefulWidget {
const stateExample({Key? key}) : super(key: key);
@override
State<stateExample> createState() => _stateExampleState();
}
// ignore: camel_case_types
class _stateExampleState extends State<stateExample> {
@override
// ignore: must_call_super
initState() {
// ignore: avoid_print
print("initState Called");
}
@override
Widget build(BuildContext context) {
// ignore: avoid_print
print(" Build method called");
return Center(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green)),
onPressed: () {},
child: const Text(
'initState Demonstration',
style: TextStyle(color: Colors.white),
),
),
// RaisedButton widget is deprecated and should not be used anymore.
// Use ElevatedButton instead.
// child: RaisedButton(
// color: Colors.green,
// elevation: 10,
// onPressed: () {},
// child: const Text(
// 'initState Demonstration',
// style: TextStyle(color: Colors.white),
// ),
// ),
);
}
}
Output:
On running the application for the very first time you will find the initState method getting triggered i.e. it is called first and after that, the control enters the Build Context.
But, if you execute it again by invoking the class you will find the initState() method getting overridden and the next print statement will come to form the Build Context.
Code Explanation:
- The code starts by creating a new Flutter application.
- This application will have a MaterialApp widget as its main screen.
- The MaterialApp widget is created using the Scaffold class.
- The home screen of the MaterialApp widget contains an AppBar and a title text field.
- The background color of the AppBar is set to green, and the title text field has a white font color.
- A stateExample widget is then created and initialized with the key value "key".
- The stateExample widget has two child widgets: an ElevatedButton and a Text widget.
- The build method of the MyApp class is called when the app starts up on Android or iOS devices.
- In this method, first, a Center widget is created and placed inside of the MyApp's root container.
- Then, two child widgets are added to it: an ElevatedButton and a Textwidget.
- The ElevatedButton has been given a style that makes it look like a button, while the Textwidget has been given a white font color so that it can be easily seen onscreen.
- Finally, print statements are executed in order to show what happened during construction of the MyApp object.
- The code starts by creating a new Flutter application.
- This application will have a MaterialApp widget as its root widget.
- The MaterialApp widget will contain a home screen with an AppBar and a body .
- The stateExample class will be used to demonstrate how to create and manage states in Flutter.
- The stateExample class has a createState method that takes an instance of State as its parameter.
- This method will be used to create the state for our application.
- The _stateExampleState class will be used to store the current state of our application.
- The _stateExampleState class has a build method that takes an instance of BuildContext as its parameter.
- This method will be used to build the UI for our application
Similar Reads
Flutter Tutorial This Flutter Tutorial is specifically designed for beginners and experienced professionals. It covers both the basics and advanced concepts of the Flutter framework.Flutter is Googleâs mobile SDK that builds native Android and iOS apps from a single codebase. It was developed in December 2017. When
7 min read
Top 50 Flutter Interview Questions and Answers for 2025 Flutter is an open-source, cross-platform application development framework. It was developed by Google in 2017. It is used to build applications for Android, iOS, Linux, Mac, Windows, and the web. Flutter uses the Dart programming language. It provides a simple, powerful, efficient, and easy-to-und
15+ min read
What is Widgets in Flutter? Flutter is Google's UI toolkit for crafting beautiful, natively compiled iOS and Android apps from a single code base. To build any application we start with widgets - The building block of Flutter applications. Widgets describe what their view should look like given their current configuration and
5 min read
Flutter | An introduction to the open source SDK by Google Flutter is Googleâs Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), and Web apps from a single codebase. When building applications with Flutter, everything is Widgets â the blocks with which the flutter apps are built. They are structural elements that ship with a bunch
5 min read
Flutter - Architecture Application Flutter architecture application mainly consists of: WidgetsGesturesConcept of StateLayersWidgetsWidgets are the primary component of any flutter application. It acts as a UI for the user to interact with the application. Any flutter application is itself a widget that is made up of a combination of
3 min read
Flutter - Changing App Icon Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. When we create a Flutter Project, it comes with the default Flutter icon. In order to get the app published in stores like Google Play Store, Apple App Store, etc the default icon can be chan
3 min read
Flutter - AppBar Widget AppBar is usually the topmost component of the app (or sometimes the bottom-most), it contains the toolbar and some other common action buttons. As all the components in a Flutter application are a widget or a combination of widgets. So AppBar is also a built-in class or widget in Flutter which give
7 min read
Scaffold class in Flutter with Examples The Scaffold is a class in flutter that provides many widgets or we can say APIs. The Scaffold will expand or occupy the whole available space in device screen .The class Hierarchy is as follows:Object â³ Diagnosticable â³ Diagnosticable Tree â³ Widget â³ StateFul Widget â³ ScaffoldThe constructor of the
8 min read
Container class in Flutter Container class in flutter is a convenience widget that combines common painting, positioning, and sizing of widgets. A Container class can be used to store one or more widgets and position them on the screen according to our convenience. Basically, a container is like a box to store contents. A bas
8 min read
Flutter - Stateful vs Stateless Widgets The state of an app can very simply be defined as anything that exists in the memory of the app while the app is running. This includes all the widgets that maintain the UI of the app including the buttons, text fonts, icons, animations, etc. So now that we know what are these states let's dive dire
6 min read