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?
Check if the widget is currently visible using bool isVisible() .
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()
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With