Last active
July 21, 2020 19:01
-
-
Save shinayser/5b06d65792bb84ca9dde1fdef0944887 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
/*This must be added to your MaterialApp`s navigatorObservers, like: | |
* navigatorObservers: [routeObserver] | |
*/ | |
final routeObserver = RouteObserver<PageRoute>(); | |
abstract class VisibilityAwareState<T extends StatefulWidget> | |
extends State<T> with WidgetsBindingObserver, RouteAware { | |
bool _isOnScreen = true; | |
bool _isAppResumed = true; | |
@override | |
void initState() { | |
WidgetsBinding.instance.addObserver(this); | |
super.initState(); | |
} | |
@override | |
void dispose() { | |
WidgetsBinding.instance.removeObserver(this); | |
routeObserver.unsubscribe(this); | |
super.dispose(); | |
} | |
@override | |
void didChangeDependencies() { | |
super.didChangeDependencies(); | |
routeObserver.subscribe(this, ModalRoute.of(context)); | |
} | |
@override | |
void didChangeAppLifecycleState(AppLifecycleState state) { | |
if (state == AppLifecycleState.paused) { | |
_isAppResumed = false; | |
} | |
if (state == AppLifecycleState.resumed) { | |
_isAppResumed = true; | |
} | |
onVisibilityChanged(_isOnScreen && _isAppResumed); | |
} | |
@override | |
void didPush() { | |
_isOnScreen = true; | |
onVisibilityChanged(_isOnScreen && _isAppResumed); | |
} | |
@override | |
void didPushNext() { | |
_isOnScreen = false; | |
onVisibilityChanged(_isOnScreen && _isAppResumed); | |
} | |
@override | |
void didPop() { | |
_isOnScreen = false; | |
onVisibilityChanged(_isOnScreen && _isAppResumed); | |
} | |
@override | |
void didPopNext() { | |
_isOnScreen = true; | |
onVisibilityChanged(_isOnScreen && _isAppResumed); | |
} | |
void onVisibilityChanged(bool isVisible); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment