The Wayback Machine - https://web.archive.org/web/20240921220622/https://www.geeksforgeeks.org/flutter-stateful-widget/
Open In App

Flutter – Stateful Widget

Last Updated : 01 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Stateful Widget has states in it. To understand a Stateful Widget you need to have a clear understanding of widgets and state management.  A state can be defined as “an imperative changing of the user interface” and, a widget is “an immutable description of the part of user interface”. To learn more about them refer to the articles below. 

Based on states, widgets are divided into 2 categories:

  1. Stateless Widget
  2. Stateful Widget

In this article, we will walk you through the Stateful Widgets. 

What are Stateful Widgets?

A Stateful Widget has its own mutable state that it needs to track. It is modified according to the user’s input. A Stateful Widget looks after two things primarily, the changed state based on its previous state and an updated view of the user interface. A track of the previous state value has to be looked at because there is a need to self-rebuild the widget to show the new changes made to your application. A Stateful Widget triggers a build method for creating its children widgets and the subclass of the state holds the related data. It is often used in cases where redrawing of a widget is needed. A Stateful Widget can change when:

  1. There is a User Input included
  2. There are some User Interaction
  3. There are some Dynamic Changes

Given below is the basic structure of a Stateful Widget-

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

The MyApp is a class that extends Stateful Widget. A generic method createState() creates a mutable state for the widget at a particular location and returns another class that is extended by the previous state. The _MyAppState class extends another state. 

Special Methods Associated with Stateful Widget

There are various methods provided by the Stateful class to work with:

1. BuildContext: It provides information regarding which widget is to be built/re-build and where it will be located after re-building. Thus, BuildContext is the widget associated with the state. 

Widget build(BuildContext context) {
    return Container();
  }

2. SetState(): A State object is used to modify the user interface. It executes the code for a particular callback and repaints the widgets that rely on that state for configuration. 

setState(setState(() {
  
});

3. initState(): This method is the entry point of a widget. The initState() method initializes all the methods that the build method will depend upon. This is called only once in a widget’s lifetime and mostly overridden the rest of the time. 

initState() {
    //...
    super.init();
}

4. didChangeDependencies(): It is used for loading the dependencies required for execution of a state. The didChangeDependencies() is called immediately after the initState() is called for the first time and before the triggering of the build method.

void didChangeDependencies() {

 }

5. dispose(): This method is used for removing an object permanently from the widget tree. It is used when we need to clear up the memory by invoking super.dispose().

void dispose(){
    //...
    super.dispose();
}

Given below is an example of the Stateful Widget.

Example

Dart




import 'package:flutter/material.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);
 
  @override
  State<MyApp> createState() => _MyAppState();
}
 
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.green,
              title: const Text('GeeksforGeeks'),
            ),
            body: const FirstScreen()));
  }
}
 
class FirstScreen extends StatelessWidget {
  const FirstScreen({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
          child: RaisedButton(
        color: Colors.green,
        onPressed: () => Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => const NewScreen())),
        child: const Text(
          'Move to next screen',
          style: TextStyle(color: Colors.white),
        ),
      )),
    );
  }
}
 
class NewScreen extends StatefulWidget {
  const NewScreen({Key? key}) : super(key: key);
 
  @override
  State<NewScreen> createState() => _NewScreenState();
}
 
class _NewScreenState extends State<NewScreen> {
  TextEditingController textEditingController = TextEditingController();
 
  @override
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GeeksforGeeks '),
        backgroundColor: Colors.green,
      ),
      body: Container(
          child: Center(
        child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            child: Container(
              child: Text(
                'User Interface Changed!!',
              ),
            )),
      )),
    );
  }
}


Output:

In the given example, the user interface changes, and the control shift to the next screen as soon as  the central button is clicked i.e. State of the object is changed. This is exactly what a Stateful Widget is used for. 



Similar Reads

Difference Between Stateless and Stateful Widget in Flutter
As we all know the flutter app consists of widgets only, these are broadly classified into two types: Stateless WidgetStateful WidgetState: Before knowing the difference between the stateless and stateful widget we should take a look at the definition of State of a widget. The State is information that can read synchronously when the widget is buil
3 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 directly into our main topic i.e. what are these state
5 min read
Expandable Widget in Flutter
The expandable widgets do not have a fixed size, they expand on the screen according to the available areas on the screen. Due to size constraints, certain widgets can throw rendering errors, so widgets are made expandable. The one use of expandable widgets is cards that include images, texts, and to further read the text we can click "Read More" o
3 min read
Flutter - ColoredBox Class Widget
A Colored Box is a container that fills it with color according to its child or A widget that paints its area with a specified Color and then draws its child on top of that color. A sample image is given below to get an idea about what we are going to do in this article. How to use it? You can simple use this widget anywhere in your project as you
3 min read
How to Get the Height of a Widget in Flutter?
To get the height of a widget in Flutter, you can use the LayoutBuilder widget to obtain the constraints of the parent container and then get the height from those constraints. How to use it? You can simply use this widget anywhere in your project as you needed that. LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { doubl
3 min read
Flutter - Wrap Widget
Wrap widget aligns the widgets in a horizontal and vertical manner. Generally, we use Rows and Columns to do that but if we have some widgets which are not able to fit in the Row/Column then it will give us Overflow Message ( for ex: Right Overflowed by 570 pixels). Constructor of Wrap class:Wrap({Key key, Axis direction, WrapAlignment alignment, d
3 min read
Raised Button widget in Flutter
RaisedButton is the material design button based on a Material widget that elevates when pressed upon in flutter. It is one of the most widely used buttons in the flutter library. Let's understand this button with the help of an example. Disclaimer: As of May 2021 the RaisedButton class in flutter is deprecated. ElevatedButton class should be used
5 min read
OffStage Widget in Flutter
Flutter provides an inbuilt widget called “Offstage”, which is been used to hide or show any widget programmatically depending on user action/event. Offstage Widget is a widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit-testing, and without taking any room in the paren
4 min read
NotificationListener Widget in Flutter
In Flutter, every Scrollable sends Notifications that contain information about the current scroll state. So to catch these notifications we use NotificationListener Widget. NotificationListener Widget will listen for Notifications bubbling up the tree. In this, article we will learn about NotificationListener Widget Default Constructor:Notificatio
4 min read
endDrawer Widget in Flutter
The endDrawer is the panel displayed to the side of the body (Scaffold Widget). It is generally hidden in mobile devices. We can open it by swiping in from right to left, or we can customise it to open on-press of an icon or a button. This widget is similar to the already present Drawer widget in flutter except for the fact the Drawer by default op
2 min read
Table Widget in Flutter
Table widget is used to display items in a table layout. There is no need to use Rows and Columns to create a table. If we have multiple rows with the same width of columns then Table widget is the right approach. SliverList or Column will be most suitable if we only want to have a single column. The height of rows in the Table widget is dependent
3 min read
PageView Widget in Flutter
The PageView widget allows the user to transition between different screens in their flutter application. All you need to set it up are a PageViewController and a PageView. Constructor of PageView class:Syntax: PageView({Key key, Axis scrollDirection, bool reverse, PageController controller, ScrollPhysics physics, bool pageSnapping, void Function(i
3 min read
ListWheelScrollView Widget in Flutter
ListWheelScrollView is a flutter widget that is used to build ListView with a 3D effect. We can also use ListView to create a list of items but we can't add a 3D effect to it plus it also comes with a constraint that all the children inside this widget must be of the same size along the strolling axis. Flutter's ListWheelScrollView adds its childre
7 min read
FlatButton Widget in Flutter
FlatButton is the material design widget in a flutter. It is a text label material widget that performs an action when the button is tapped. Let's understand with the help of examples. Disclaimer: As of May 2021 the FlatButton class in flutter is deprecated. TextButton class should be used instead. The later class will eventually be removed from fl
3 min read
ClipOval widget in Flutter
ClipOval widget clips the child widget in oval or circle shape. We can reshape the child widget by changing width and height. If width and height are equal the shape will be circular. If the width and height are given differently then the shape will be oval. Let's understand this with the help of an example. Constructor of ClipOval class:Syntax: Cl
2 min read
Center widget in Flutter
Center widget comes built-in with flutter, it aligns its child widget to the center of the available space on the screen. The size of this widget will be as big as possible if the widthFactor and heightFactor properties are set to null and the dimensions are constrained. And in case the dimensions are not constrained and the widthFactor and HeightF
2 min read
BottomNavigationBar Widget in Flutter
The BottonNavigationBar widget is used to show the bottom of an app. It can consist of multiple items such as icons, text, or both that leads to a different route depending upon the design of the application. It is meant to help the user navigate to different sections of the application in general. Constructors:Syntax: BottomNavigationBar( {Key key
4 min read
ClipRRect Widget in Flutter
The ClipRRect widget in flutter is used to clips its child using a rounded rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRect and is used to Clip a Rectangle portion of the child widget but with rounded corners Constructor:Syntax: C
2 min read
Drawer Widget in Flutter
Drawer widget is used to provide access to different destinations and functionalities provided in your application. It is represented by three horizontal parallel lines on the upper end of the scaffold. It has a horizontal movement from the edge of the Scaffold that navigates the link to different routes in the flutter app. In order to use the app
5 min read
ClipRect Widget in Flutter
The ClipRect widget is used to clips its child using a rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRRect and is used to Clip a Rectangle portion of the child widget but without the rounded corners Constructors:Syntax: ClipRect( {K
2 min read
Opacity Widget in Flutter
The Opacity widget that makes its child partially transparent. This class colors its child into an intermediate buffer and then merges the child back into the scene partially transparent. For values of opacity other than 0.0 and 1.0, this class is relatively expensive as it needs coloring the child into an intermediate buffer. For the value 0.0, th
2 min read
RotatedBox Widget in Flutter
The RotatedBox widget is used to rotate its child by an integral number of quarter turns. It is used to orient its child widgets into either horizontal or vertical orientation. Furthermore, it is very lightweight and can be used for designing various UI as it gives flexibility to the user over the Design of the app. Constructors:Syntax: RotatedBox(
2 min read
Flutter - RichText Widget
The RichText widget is used to display text that uses various different styles. The displayed text is described using a tree of TextSpan objects, each of which has its own associated style that is used for that subtree. Depending on the layout constraints the text might break across multiple lines or might all be displayed on the same line. Constru
3 min read
TextSpan Widget in Flutter
TextSpan is an immutable span of text. It has style property to give style to the text. It is also having children property to add more text to this widget and give style to the children. Let's understand this with the help of an example. Constructors:Syntax: TextSpan({String text, List&lt;InlineSpan&gt; children, TextStyle style, GestureRecognizer
3 min read
Flutter - Banner Widget
Banner widget comes built-in with flutter API. It is somewhat similar to the debug banner that we are used to seeing on the top-right corner on a flutter app in debug mode. It enables us to show a message or text on top of any other widget. Below we will see its implementation with the help of an example and all its properties. Constructor of Banne
3 min read
Align Widget in Flutter
Align Widget is the widget that is used to align its child within itself and optionally sizes itself based on the child's size. Align Widget is quite flexible and can change its size according to the size of its child. Constructor of Align class: Syntax: Align({Key key, AlignmentGeometry alignment: Alignment.center, double widthFactor, double heigh
2 min read
Flutter - Fading a Widget
Every application needs to navigate through multiple pages and components in an application. In flutter one way to do so is to make the use of routes (ie, pages). But when there is a need to just remove a part (element) from a page, using routes becomes redundant. This is where Fading comes in. In this, the component is simply faded away from the p
3 min read
Flutter - AnimatedContainer Widget
In Flutter a container is a simple widget with well-defined properties like height, width, and color, etc. The AnimatedContainer widget is a simple container widget with animations. These types of widgets can be animated by altering the values of their properties which are the same as the Container widget. These types of animation in Flutter is kno
3 min read
Flutter - AbsorbPointer Widget
AbsorbPointer is a built-in widget in flutter which absorbs pointer, in other words, it prevents its subtree from being clicked, tapped, scrolled, dragged, and responding to hover. In flutter, most widgets already come with an option to disable them for example in a RaisedButton we can set the onClicked function to null to disable, or we can use Ne
4 min read
Flutter - OctoImage Widget
The OctoImage widget in Flutter requires an ImageProvider to display images in an application. The images in the OctoImage widget can be supplied with a Progress indicator or a Place holder for loading the Image in it. An OctoImage widget makes use of the Octosets which are nothing but the combination of predefined placeholders, imagebuilder, and e
4 min read
Article Tags :