我正在使用WidgetsBindingObserver
处理应用Resume
事件以打开深层链接。除非出现以下情况,否则效果很好:如果应用是第一次启动(例如,不是从后台返回),则不会调用didChangeAppLifecycleState
,因为没有恢复的事件。
从Flutter框架:
enum AppLifecycleState {
/// The application is visible and responding to user input.
resumed,
....
/// On Android, this corresponds to an app or the Flutter host view running
/// in the foreground inactive state. Apps transition to this state when
/// another activity is focused, such as a split-screen app, a phone call,
/// a picture-in-picture app, a system dialog, or another window.
和:
///
/// Apps in this state should assume that they may be [paused] at any time.
inactive,
因此,我在Statefull小部件中使用initState()
处理这种情况下的深层链接:
@override
void initState() {
super.initState();
_retrieveDynamicLinks();
WidgetsBinding.instance.addObserver(this);
}
效果很好,但这是另一个问题:现在,只要应用程序从后台返回,就会打开深层链接(即使没有深层链接,只要恢复即可)。
在这种情况下,await FirebaseDynamicLinks.instance.retrieveDynamicLink();
似乎不会清除内部缓冲区,并且始终会检索相同的深层链接。
有人经历过吗?如何解决这个问题?
这是简单的AppLifecycle Widget实现:
class AppLifecycle extends StatefulWidget {
final Widget child;
const AppLifecycle({Key key, @required this.child}) : super(key: key);
@override
_AppLifecycleState createState() => _AppLifecycleState();
}
class _AppLifecycleState extends State<AppLifecycle>
with WidgetsBindingObserver {
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
// if state RESUMED (back to foreground)
if (state == AppLifecycleState.resumed) {
await _retrieveDynamicLinks();
}
}
Future<dynamic> _retrieveDynamicLinks() async {
final PendingDynamicLinkData data =
await FirebaseDynamicLinks.instance.retrieveDynamicLink();
final Uri deepLink = data?.link;
if (deepLink != null) {
// handlers...
}
}
@override
void initState() {
super.initState();
_retrieveDynamicLinks();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}