Open In App

Flutter – initState()

Last Updated : 25 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

There are two types of widgets provided in Flutter.

  1. The Stateless Widget
  2. 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:

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:

  1.  The code starts by creating a new Flutter application.
  2. This application will have a MaterialApp widget as its main screen.
  3. The MaterialApp widget is created using the Scaffold class.
  4. The home screen of the MaterialApp widget contains an AppBar and a title text field.
  5. The background color of the AppBar is set to green, and the title text field has a white font color.
  6. A stateExample widget is then created and initialized with the key value “key”.
  7. The stateExample widget has two child widgets: an ElevatedButton and a Text widget.
  8. The build method of the MyApp class is called when the app starts up on Android or iOS devices.
  9. In this method, first, a Center widget is created and placed inside of the MyApp’s root container.
  10. Then, two child widgets are added to it: an ElevatedButton and a Textwidget.
  11. 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.
  12. Finally, print statements are executed in order to show what happened during construction of the MyApp object.
  13. The code starts by creating a new Flutter application.
  14. This application will have a MaterialApp widget as its root widget.
  15. The MaterialApp widget will contain a home screen with an AppBar and a body .
  16. The stateExample class will be used to demonstrate how to create and manage states in Flutter.
  17. The stateExample class has a createState method that takes an instance of State as its parameter.
  18. This method will be used to create the state for our application.
  19. The _stateExampleState class will be used to store the current state of our application.
  20. The _stateExampleState class has a build method that takes an instance of BuildContext as its parameter.
  21. This method will be used to build the UI for our application


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads