Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onResume() method equivalent in Flutter

Tags:

flutter

dart

I am working on a Flutter app and need to pop the screen. I tried initState() method but no luck. initState() gets called when I open a class for the first time.

Do we have an equivalent of Android onResume() method in Flutter?

Any ideas?

like image 697
Satish Saini Avatar asked Nov 03 '18 04:11

Satish Saini


People also ask

How do you check widget visibility in Flutter?

Check if the widget is currently visible using bool isVisible() .

What is widget lifecycle in Flutter?

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

Why is Exit 0 not preferred for closing an app Flutter?

Close Android App With Code: exit(0) : This command also works but it is not recommended because it terminates the Dart VM process immediately and users may think that the app got crashed.


1 Answers

You can use the WidgetsBindingObserver and check the AppLifeCycleState like this example:

class YourWidgetState extends State<YourWidget> with WidgetsBindingObserver {    @override   void initState() {     WidgetsBinding.instance?.addObserver(this);     super.initState();   }      @override   void dispose() {     WidgetsBinding.instance?.removeObserver(this);     super.dispose();   }       @override   void didChangeAppLifecycleState(AppLifecycleState state) {     if (state == AppLifecycleState.resumed) {        //do your stuff     }   } } 

Take in mind that It will called every time you open the app or go the background and return to the app. (if your widget is active)

If you just want a listener when your Widget is loaded for first time, you can listen using addPostFrameCallback, like this example:

class YourWidgetState extends State<YourWidget> {    _onLayoutDone(_) {     //do your stuff   }    @override   void initState() {     WidgetsBinding.instance?.addPostFrameCallback(_onLayoutDone);     super.initState();   }   } 

Info : https://docs.flutter.io/flutter/widgets/WidgetsBindingObserver-class.html

Update: Null safety compliance

like image 100
diegoveloper Avatar answered Sep 19 '22 14:09

diegoveloper