Explore Widget Lifecycle In Flutter
Flutter is a mobile framework that helps to modernize both iOS and Android app from a single codebase. It is a combination of stateful and stateless widgets. Like all frameworks, Flutter also has a lifecycle associated with all the apps that our Flutter app uses. is managed by lifecycle In this article, we will take a look at different types of apps available in the flutter app, lifecycle.
In this article, we will explore the Widget Lifecycle in Flutter. We will also implement a Widget Lifecycle demo, describe its properties, and use them in your flutter applications. So let’s get started.
Table of Contents :
Flutter :
“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time, Flutter offers great developer tools, with amazing hot reload”
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: Stateless Widgets in Flutter are those widgets whose state once created cannot be changed, it becomes immutable like on variables, buttons, icons, etc., or any state that cannot be changed on the app to retrieve data. Returns a widget by overwriting the build method. We use it when the UI relies on the information inside 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: A Stateful widget maintains data and responds to whatever the data does inside the application. It is a mutable widget, so it is drawn multiple times in its lifetime.
We use this when the user dynamically updates the application screen. This is the most important of all the widgets, as it has a state widget, everyone knows that something has been updated on our 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();
}
}
The life cycle of the StatefulWidget Diagram.
=> A stateful widget has the following lifecycle stages:
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()
- > initState(): Flutter’s initState() method is the first method that is used while creating a stateful class, here we can initialize variables, data, properties, etc. for any widget.
int a;
@override
void initState() {
a= 0;
super.initState();
}
- > createState(): When we create a stateful widget, our framework calls a createState() method and it must be overridden.
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyScreenState();
}
- > build(): The build method is used each time the widget is rebuilt. This can happen either after calling initState, didChangeDependencies, didUpdateWidget, or when the state is changed via a call to setState
@override
Widget build(BuildContext context, MyButtonState state) {
return Container(color:Colors.red);
}
- > didChangeDependencies(): This method is called immediately after initState and when dependency of the State object changes via InheritedWidget.
@override
void didChangeDependencies() {
super.didChangeDependencies()
}
- > didUpdateWidget(): This method is called whenever the widget configuration changes. A typical case is when a parent passes some variable to the children() widget via the constructor.
@override
void didUpdateWidget(MyHomePage oldWidget) {
super.didUpdateWidget(oldWidget)
}
- > deactivate(): It is used when the state is removed from the tree but before the current frame change can be re-inserted into another part of the tree
@override
void deactivate() {
super.deactivate();
}
- > dispose(): We use this method when we remove permanently like should release resource created by an object like stop animation
@override
dispose() {
animationController.dispose(); // you need this
super.dispose();
}
Implement:
You need to implement it in your code respectively:
Create a new dart file calledwidget_lifecycle_demo
inside the lib
folder.
Now we first took a dart file as I have mentioned above and before the build method we have defined an integer type variable whose variable name is _counter, after that I have created an increment counter method inside it in setState() Defines a _counter variable that is of increment type.
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
In this, we have called the method initState(),didChangeAppLifecycleState(),
deactivate() etc. As soon as our app is created it will print a message in the accordion console of its lifecycle.
@override
void initState() {
super.initState();
WidgetsBinding.instance!.addObserver(this);
print("initState");
_counter++;
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
print('AppLifecycleState: $state');
}
After this, we have taken the column widget inside the build method inside which the increment value is defined inside a text and in it we have taken a FloatingActionButton() which is of increment type, pressing which will increase the value of the counter.
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:',
),
SizedBox(height: 8.0,),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Code File:
import 'package:flutter/material.dart';
class LifeCycleExm extends StatefulWidget {
@override
_LifeCycleExmState createState() => _LifeCycleExmState();
}
class _LifeCycleExmState extends State<LifeCycleExm> 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:
In this article, I have explained an Explore Widget Lifecycle in a flutter, which you can modify and experiment with according to your own, this little introduction was from the Explore Widget Lifecycle.
I hope this blog will provide you with sufficient information on Trying up the Explore Widget Lifecycle in your flutter project. We showed you the Explore Widget Lifecycle and worked on it in your flutter applications, So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Feel free to connect with us
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.