Life Cycle in flutter

Shahzeb Naqvi
6 min readApr 28, 2022

--

What is Flutter?

Flutter is an open source UI software development kit developed by Google. Used to develop cross-platform applications for Android, iOS, Linux, macOS, Windows, and the Web from a single code base

What is Program Life Cycle ?

The program lifecycle phase is the phase from the initial creation of a computer program to its deployment and execution. The phases are processing time, compile time, link time, distribution time, installation time, load time, and execution time.

The state in which the application can be written is the enumeration class AppLifecycleState. The observable life cycle events are:

Inactive : The application is inactive and is not receiving user input. This event only works on iOS as there is no corresponding event to map to Android

Pause : The application is currently not visible to the user, is not responding to user input, and is running in the background. This corresponds to Android onPause ()

Resume : The application is displayed and responds to user input. This corresponds to Android onPostResume ()

Paused : The application is temporarily suspended. This corresponds to Android onStop. It is not triggered on iOS because there is no corresponding event to map to iOS.

Widget Lifecycle :

Everything in Flutter is a Widget, so before knowing about Lifecycle, we should know about Widgets in Flutter.

There are two types of widgets in Flutter.

  • Stateless Widgets.
  • Stateful Widgets.

Before knowing about the Lifecycle, we need to understand the difference between the two widgets.

= Stateless Widgets: Flutter’s stateless widgets are widgets that are once created and cannot be changed, widgets that are immutable, such as variables, buttons, and icons, or widgets that cannot be changed by the app to retrieve data. Overrides the Build method and returns the widget. Use when the UI depends on the information of the object itself.

import ‘package:flutter/material.dart’;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}

= Stateful Widget: Stateful widgets manage data and respond to everything that data does within your application. Since this is a volatile widget, it will be drawn multiple times during its lifetime. This is used when the user dynamically updates the application screen. This is the most important of all widgets as there is a status widget and everyone knows that something has been updated on the screen.

import ‘package:flutter/material.dart’;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Container();
}
}

Widget Lifecycle Methods:

The life cycle is based on the state and how it changes. A stateful widget has a state so we can explain the life cycle of flutter based on it. Stage of the life cycle:

createState

initState()

didChangeDependencies()

build()

didUpdateWidget()

setState()

deactivate()

dispose()

  1. createState(): When the Framework is instructed to build a StatefulWidget, it immediately calls createState()
  2. mounted is true: When createState creates your state class, a buildContext is assigned to that state. buildContext is, overly simplified, the place in the widget tree in which this widget is placed. Here's a longer explanation. All widgets have a bool this.mounted property. It is turned true when the buildContext is assigned. It is an error to call setState when a widget is unmounted.
  3. initState(): This is the first method called when the widget is created (after the class constructor, of course.) initState is called once and only once. It must call super.initState().
  4. didChangeDependencies(): This method is called immediately after initState on the first time the widget is built.
  5. build(): This method is called often. It is required, and it must return a Widget.
  6. didUpdateWidget(Widget oldWidget): If the parent widget changes and has to rebuild this widget (because it needs to give it different data), but it's being rebuilt with the same runtimeType, then this method is called. This is because Flutter is re-using the state, which is long lived. In this case, you may want to initialize some data again, as you would in initState.
  7. setState(): This method is called often from the framework itself and from the developer. Its used to notify the framework that data has changed
  8. deactivate(): Deactivate is called when State is removed from the tree, but it might be reinserted before the current frame change is finished. This method exists basically because State objects can be moved from one point in a tree to another.
  9. dispose(): dispose() is called when the State object is removed, which is permanent. This method is where you should unsubscribe and cancel all animations, streams, etc.
  10. mounted is false: The state object can never remount, and error will be thrown if setState is called.

1 — initState()

int a;
@override
void initState() {
a= 0;
super.initState();
}

2 — createState():

class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyScreenState();
}

3 — build():

@override
Widget build(BuildContext context, MyButtonState state) {
return Container(color:Colors.red);
}

4 — didChangeDependencies():

@override
void didChangeDependencies() {
super.didChangeDependencies()
}

5 — didUpdateWidget():

@override
void didUpdateWidget(MyHomePage oldWidget) {
super.didUpdateWidget(oldWidget)
}

6 — deactivate():

@override
void deactivate() {
super.deactivate();
}

7 — dispose():

@override
dispose() {
animationController.dispose(); // you need this
super.dispose();
}

Implementation Code

import 'package:flutter/material.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with WidgetsBindingObserver {

@override
void initState() {
super.initState();
WidgetsBinding.instance!.addObserver(this);
print("initState");
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
print('AppLifecycleState: $state');
}

@override
void dispose() {
WidgetsBinding.instance!.removeObserver(this);
super.dispose();
}

@override
void deactivate() {
// TODO: implement deactivate
print("deactivate");
super.deactivate();
}

int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
print("build");
return Scaffold(
appBar: AppBar(title: Text("Flutter Widget Lifecycle")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),

Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
SizedBox(height: 8.0,),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Conclusion :

I have described the life cycle of a flutter widget that you can modify and experiment with to your liking. This little introduction comes from the life cycle of the Explore widget.

Thanks for reading this article

--

--

Shahzeb Naqvi

Currently I am looking for a job that will be related to my field of work. Looking forward to work in Development environment that gives me scope to enhance me.