Skip to content
Related Articles

Related Articles

Improve Article

Flutter – State Management

  • Last Updated : 17 Feb, 2021
Geek Week

In a reactive framework like Flutter, you can think of your UI as the function’s return value.  The function here is considered as your state. So in simple words, what a user sees in the application is one state, and he clicks on the button, he sees another UI screen. So now that screen is a state. So an application is made up of many states, i.e. UI. And their states are managed by Navigation and route.

A lot of your data can be Self-contained within a Single widget known as a Local State.  And a state that needs to be shared throughout the widget tree is called Global State.

The state of an application is everything that exists in the memory when the application is running. All the assets, animation state, information about UI and textures, All these data are included in these. The framework manages most of the states for the user. The state that we manage ourselves can be separated into Ephemeral state and App state.

Ephemeral State:

The ephemeral state is the state where you can neatly contain it in a single widget. There is no need to serialize it, and it doesn’t change in complex ways. In simpler words, there is no need to use State Management in this. Just use StatefulWidget here. 

Dart






class MainPage extends StatefulWidget {
  @override
  _MainPage createState() => _MainPage();
}
  
class _MainPage extends State<MainPage> {
  int _index = 0;
  
  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      currentIndex: _index,
      onTap: (newIndex) {
        setState(() {
          _index = newIndex;
        });
      },
      // ... items ...
    );
  }
}

In the above code _index is an ephemeral state. It is being held in the _index field of the _Mainpage class. The variable only changes inside the _MainPage widget, and even if the user restarts the application, you don’t mind that _index resets to zero.

Once created, this widget can’t be accessed by the other UI’s of the application. We generally use this state when the application is small or for the current page or current progress pages in the application.

App State:

States which the user wants to share across many parts of the application are called the App state or the Shared state. We use this state in complex or large applications. 

For Example:-

  • User Preferences
  • Login info
  • The cart in an e-commerce app
  • Notifications of the apps

There is no compulsion in using these states. Both the states are valid and depends on which the user wants to use. If the widget the application is going to be used within a single UI, the user can go with the Ephemeral state, and the user can use the App state.  

There are many ways to approach state management:-

  • Provider
  • setState
  • InheritedWidget and InheritedModel
  • Redux and Fish-Redux
  • BLoc/Rx
  • GetIt
  • MobX
  • Binder
  • GetX
  • Riverpod

Let us consider a simple example of an application:-

  1. As the application opens, the user sees 3 buttons.
  2. Each button takes the user to a different screen.
  3. And after going to the other screen, the user can also come back to the previous screen.

Navigation and Routing:

In any application, navigation from one screen to another screen is essential. The way that navigation is handled is called Routing. Flutter provides an elementary routing class –  MaterialPageRoute and two methods – Navigator.push and Navigator.pop.



MaterialPageRoute

MaterialPageRoute is a widget used to render its UI by replacing the entire screen with a platform-specific animation. The following is the syntax of this widget:-

MaterialPageRoute(builder: (context)=>Widget())

Let us create a new application for better understanding of this concept.

Create a new Flutter application in Android Studio, test_app, or you can name the app according to your choice.

The 1st screen that is visible to you is of main.dart

Dart




import 'package:flutter/material.dart';
import 'mainscreen.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
    
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MainScreen(),
    );
  }
}

Here we have created a StatlessWidget because we didn’t want to make a dynamic application. If you want to make a dynamic application, then use StatefullWidget. We have added the theme, which makes the primary color of the application blue. The blue color is the default color of flutter, but we will give a green color here.. You can give whatever color you want to give. And we have set the home as MainScreen(). This means that the 1st screen that will be visible to the user will open the UI of the MAIN SCREEN.

This is the code of mainscreen.dart

Dart




import 'package:flutter/material.dart';
import 'secondscreen.dart';
  
class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Geeksforgeeks SCREEN 1"),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('SCREEN 2'),
          onPressed: (){
            Navigator.push(context,
            MaterialPageRoute(builder: (context)=>SecondScreen()));
          },
        ),
      ),
    );
  }
}

This code created the 1st screen of our application whose title we have given as Geeksforgeeks SCREEN 1. And in the middle, we had added a RaisedButton which when clicked will take us to SCREEN 2. The line ” MaterialPageRoute(builder: (context)=>SecondScreen())” is mainline that is telling our app to move to screen 2 when the button is pressed. Now create a new dart file named secondscreen.dart . Creating this file will help us to import this in the mainscreen.dart.

This is the code of secondscreen.dart

Dart




import 'package:flutter/material.dart';
  
class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Geeksforgeeks SCREEN 2"),
  
      ),
    );
  }
}

This is a straightforward file. In this file, we only have added the title bar that tells you that now you are on the second screen. The flutter itself adds the back icon button. No need to code that. Run this application and press the button in the Centre. It will take you to screen 2.

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :