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?
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