Let’s Utilize the Flutter App Lifecycle

Clear guidance to detect mobile app lifecycle changes

Flutter is an open-source mobile framework used to create native apps for Android and iOS. When you deal with mobile applications it is important to know about app lifecycle when implementing some features. Therefore this article will describe Flutter App Lifecycle methods in a detailed manner.

Why do we need to focus on the app life cycle?

Actually when dealing with mobile applications there are some major concerns like if a particular app is running background or foreground. Therefore this can be easy to deal with Flutter AppLifecycleState and 4 major lifecycle states are:

detached → const AppLifecycleState:

If an app is in this state, the flutter engine is running but we cannot see the view. Simply assume that any app is in the mobile phone but you have not opened it. Therefore if the application is hosted in the flutter engine, it is detached from any host view.

inactive → const AppLifecycleState:

If an app is in this state, it is not receiving user input. Simply we can say the app is in the foreground and not running in the background on your mobile phone. As an example if we press the back button and move to a new app then the previously working app goes to foreground inactive state and does not receive user input. Therefore apps in state should assume that they may be paused at any time.

paused → const AppLifecycleState:

If an app is in this state it is not visible to the user and not responding to user input. But it is important to notice that it is running in the background. As an example, assume that you are on Facebook, you receive a notification from WhatsApp then you click on that chat notification and go to WhatsApp. In this situation Facebook is in the paused state and it is running in the background but not visible to the user.

resumed → const AppLifecycleState:

If an app is in this state it responds to the user’s inputs and visible app in the background. Assume that you are working with WhatsApp instant messaging.

Now I think you can get a clear idea about App Lifecycle then let’s move to code implementation.

1. Create a demo application.

2. Create a StatefulWidget and WidgetsBinindingObserver

StatefulWidget and WidgetsBinindingObserver

3. Then you need to manage the observer by adding and removing using addObserver method and removeObserver respectively:

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().

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.

deactivate(): called when State is removed from the tree. This method exists basically because State objects can be moved from one point in a tree to another.

setState(): called often from the Flutter framework itself and from the developer. It is used to notify the framework that “data has changed”, and the widget at this build context should be rebuilt.

See more…..

Image by Author

4. Create didChangeAppLifecycleState which takes AppLifecycleState as object argument and it is used to check each various states in the app lifecycle. didChangeAppLifecycleState is called when a dependency of [State] object changes.

Further, didChangeAppLifecycleState is called immediately after the initState on the first time the widget is built.

didChangeAppLifecycleState Method

5. Your app for detecting app lifecycle changes is ready now. Full code implementation as follows.

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
print("InitState");
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
print("DidChangeDependencies");
}
@override
void setState(fn) {
print("SetState");
super.setState(fn);
}
@override
void deactivate() {
print("Deactivate");
super.deactivate();
}
@override
void dispose() {
print("Dispose");
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.inactive:
print('appLifeCycleState inactive');
break;
case AppLifecycleState.resumed:
print('appLifeCycleState resumed');
break;
case AppLifecycleState.paused:
print('appLifeCycleState paused');
break;
case AppLifecycleState.detached:
print('appLifeCycleState detached');
break;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
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,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

6. You can run your app and can observe app lifecycle changes. Sample snippet for Lifecycle changes as follows:

Image by Author

Conclusion

Detecting app lifecycle is a simple approach but it is really useful when you are dealing with mobile applications and when you need to implement some special native app related developments.

Thanks for reading this article and if you enjoyed the article or learned something new, show your support by clapping as many times as possible. ??


Let’s Utilize the Flutter App Lifecycle was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Sajeevan Wickramarathna

Clear guidance to detect mobile app lifecycle changes

Flutter is an open-source mobile framework used to create native apps for Android and iOS. When you deal with mobile applications it is important to know about app lifecycle when implementing some features. Therefore this article will describe Flutter App Lifecycle methods in a detailed manner.

Why do we need to focus on the app life cycle?

Actually when dealing with mobile applications there are some major concerns like if a particular app is running background or foreground. Therefore this can be easy to deal with Flutter AppLifecycleState and 4 major lifecycle states are:

detached → const AppLifecycleState:

If an app is in this state, the flutter engine is running but we cannot see the view. Simply assume that any app is in the mobile phone but you have not opened it. Therefore if the application is hosted in the flutter engine, it is detached from any host view.

inactive → const AppLifecycleState:

If an app is in this state, it is not receiving user input. Simply we can say the app is in the foreground and not running in the background on your mobile phone. As an example if we press the back button and move to a new app then the previously working app goes to foreground inactive state and does not receive user input. Therefore apps in state should assume that they may be paused at any time.

paused → const AppLifecycleState:

If an app is in this state it is not visible to the user and not responding to user input. But it is important to notice that it is running in the background. As an example, assume that you are on Facebook, you receive a notification from WhatsApp then you click on that chat notification and go to WhatsApp. In this situation Facebook is in the paused state and it is running in the background but not visible to the user.

resumed → const AppLifecycleState:

If an app is in this state it responds to the user’s inputs and visible app in the background. Assume that you are working with WhatsApp instant messaging.

Now I think you can get a clear idea about App Lifecycle then let’s move to code implementation.

1. Create a demo application.

2. Create a StatefulWidget and WidgetsBinindingObserver

StatefulWidget and WidgetsBinindingObserver

3. Then you need to manage the observer by adding and removing using addObserver method and removeObserver respectively:

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().

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.

deactivate(): called when State is removed from the tree. This method exists basically because State objects can be moved from one point in a tree to another.

setState(): called often from the Flutter framework itself and from the developer. It is used to notify the framework that “data has changed”, and the widget at this build context should be rebuilt.

See more…..

Image by Author

4. Create didChangeAppLifecycleState which takes AppLifecycleState as object argument and it is used to check each various states in the app lifecycle. didChangeAppLifecycleState is called when a dependency of [State] object changes.

Further, didChangeAppLifecycleState is called immediately after the initState on the first time the widget is built.

didChangeAppLifecycleState Method

5. Your app for detecting app lifecycle changes is ready now. Full code implementation as follows.

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
print("InitState");
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
print("DidChangeDependencies");
}
@override
void setState(fn) {
print("SetState");
super.setState(fn);
}
@override
void deactivate() {
print("Deactivate");
super.deactivate();
}
@override
void dispose() {
print("Dispose");
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.inactive:
print('appLifeCycleState inactive');
break;
case AppLifecycleState.resumed:
print('appLifeCycleState resumed');
break;
case AppLifecycleState.paused:
print('appLifeCycleState paused');
break;
case AppLifecycleState.detached:
print('appLifeCycleState detached');
break;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
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,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

6. You can run your app and can observe app lifecycle changes. Sample snippet for Lifecycle changes as follows:

Image by Author

Conclusion

Detecting app lifecycle is a simple approach but it is really useful when you are dealing with mobile applications and when you need to implement some special native app related developments.

Thanks for reading this article and if you enjoyed the article or learned something new, show your support by clapping as many times as possible. ??


Let’s Utilize the Flutter App Lifecycle was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Sajeevan Wickramarathna


Print Share Comment Cite Upload Translate Updates
APA

Sajeevan Wickramarathna | Sciencx (2021-06-07T15:48:03+00:00) Let’s Utilize the Flutter App Lifecycle. Retrieved from https://www.scien.cx/2021/06/07/lets-utilize-the-flutter-app-lifecycle/

MLA
" » Let’s Utilize the Flutter App Lifecycle." Sajeevan Wickramarathna | Sciencx - Monday June 7, 2021, https://www.scien.cx/2021/06/07/lets-utilize-the-flutter-app-lifecycle/
HARVARD
Sajeevan Wickramarathna | Sciencx Monday June 7, 2021 » Let’s Utilize the Flutter App Lifecycle., viewed ,<https://www.scien.cx/2021/06/07/lets-utilize-the-flutter-app-lifecycle/>
VANCOUVER
Sajeevan Wickramarathna | Sciencx - » Let’s Utilize the Flutter App Lifecycle. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/07/lets-utilize-the-flutter-app-lifecycle/
CHICAGO
" » Let’s Utilize the Flutter App Lifecycle." Sajeevan Wickramarathna | Sciencx - Accessed . https://www.scien.cx/2021/06/07/lets-utilize-the-flutter-app-lifecycle/
IEEE
" » Let’s Utilize the Flutter App Lifecycle." Sajeevan Wickramarathna | Sciencx [Online]. Available: https://www.scien.cx/2021/06/07/lets-utilize-the-flutter-app-lifecycle/. [Accessed: ]
rf:citation
» Let’s Utilize the Flutter App Lifecycle | Sajeevan Wickramarathna | Sciencx | https://www.scien.cx/2021/06/07/lets-utilize-the-flutter-app-lifecycle/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.