Flutter App Lifecycle

ariba.dev
2 min readApr 30, 2023
life cycle in flutter

In this article, I would like to raise the issue of listening to the events of the life cycle. Flutter handles the life cycle so to speak under the hood. Only a small selection of application life cycle events is available to the developer. If you need to observe the lifecycle to acquire or release any native resources, you should likely be doing it from the native side, at any rate.

The state in which the application can be described is the enum class AppLifecycleState.

The observable lifecycle events are:

  • inactive — The application is in an inactive state and is not receiving user input. This event only works on iOS, as there is no equivalent event to map to on Android
  • paused — The application is not currently visible to the user, not responding to user input, and running in the background. This is equivalent to onPause() in Android
  • resumed — The application is visible and responding to user input. This is equivalent to onPostResume() in Android
  • suspending — The application is suspended momentarily. This is equivalent to onStop in Android; it is not triggered on iOS as there is no equivalent event to map to on iOS

Let’s create a simple application in which we will visually consider methods for obtaining a vital state:

Step 1. Create a new application. The main screen in which will be StatefulWidget. Which should implement the WidgetsBindingObserver interface. Next, we get the instance of WidgetBinding and add an observer to it.

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Tutorial Lifecycle'),
),
body: Center(),
);
}
}

Step 2. Now we have the didChangeAppLifecycleState method available. In this example, we simply print a state change to the thermal.

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print('state = $state');

Coming out and going back into the application, we get the following results:

At first glance, the topic covered in this article is not very complicated, but I think it can be useful!

--

--

ariba.dev

⚡Dart makes my heart Flutter 💙🧑‍💻 • ✨ Software developer🧑‍💻 • Looking for the best remote opportunity in EUROPE