Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Types
  • Functions
  • Oops
  • Collections
  • Sets
  • Dart Interview Questions
  • Fluter
  • Android
  • Kotlin
  • Kotlin Android
  • Android with Java
  • Android Studio
Open In App
Next Article:
Flutter - ListTile Widget
Next article icon

Flutter - Stateful Widget

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 the user interface". To learn more about them, refer to the articles below. 

  • What are widgets in Flutter?
  • Flutter – State Management

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 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 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:

  • There is a User Input included
  • There are some User Interaction
  • There are some Dynamic Changes

Given below is the basic structure of a Stateful Widget:

Dart
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(), rebuilds 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/rebuilt and where it will be located after rebuilding. 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 the 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.black,           foregroundColor: Colors.white,           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: ElevatedButton(           style: ElevatedButton.styleFrom(             backgroundColor: Colors.black,             foregroundColor: Colors.white,           ),           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.black,         foregroundColor: Colors.white,       ),       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 shifts 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. 


Next Article
Flutter - ListTile Widget

R

rharshitaaa21
Improve
Article Tags :
  • Dart
  • Flutter
  • Flutter-Widgets
  • Flutter-Basics

Similar Reads

  • Flutter - Stateless Widget
    Stateless Widget is something that does not have a state. To understand a Stateless Widget, you need to clearly understand widgets and states. A state can be defined as "an imperative changing of the user interface," and a widget is "an immutable description of the part of the user interface". To le
    4 min read
  • Flutter - Stack Widget
    The Stack widget in Flutter is a powerful tool that allows for the layering of multiple widgets on top of each other. While layouts like Row and Column arrange widgets horizontally and vertically, respectively, Stack provides a solution when you need to overlay widgets. For instance, if you want to
    6 min read
  • Flutter - ListTile Widget
    The ListTile widget is used to populate a ListView in Flutter. It contains a title as well as leading or trailing icons. Let's understand this with the help of an example. The Constructor of the ListTile classListTile({ Key key, Widget leading, Widget title, Widget subtitle, Widget trailing, bool is
    4 min read
  • Flutter - Stepper Widget
    In this article, we will learn about the Stepper widget in Flutter. A stepper widget displays progress through a sequence of steps. Stepper is generally used in filling forms online. For example, remember filling an online form for applying to any university or passport or driving license. We filled
    8 min read
  • Flutter - TabView Widget
    There are lots of apps where you often have come across tabs. Tabs are a common pattern in the apps. They are situated at top of the app below the App bar. So today we are going to create our own app with tabs. Table of Contents:Project SetupCodeConclusionProject Setup: You can either create a new p
    4 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
    4 min read
  • Flutter - StreamBuilder Widget
    A StreamBuilder in Flutter is used to listen to a stream of data and rebuild its widget subtree whenever new data is emitted by the stream. It's commonly used for real-time updates, such as when working with streams of data from network requests, databases, or other asynchronous sources. In this art
    5 min read
  • Flutter - FlutterLogo Widget
    FlutterLogo widget is as simple as it sounds, it is just the flutter logo in the form of an icon. This widget also comes built-in with Flutter SDK. This widget can found its use as a placeholder for an image or icon. Below we will see its implementation with all its properties and constructor. Const
    3 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. Th
    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 dire
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences