Reputation: 4172
Working on a Flutter app, I am handling deeplinks with a SDK for which I am given a listener that I must handle as soon as the app starts, therefore in the main()
.
Once a deeplink is received, I must navigate to the proper screen, based on the parameters passed along the deeplink data.
Since I receive the deeplink in the main function, I am detached from the Context of the app, therefore to access the NavigatorState
I used a navigation singleton with a GlobalKey
passed to my CupertinoApp
's navigatorKey
. I later use this key to retrieve the NavigatorState
and call push. (instead of Navigator.of(context)...
.
However, if opening the app from a deeplink, it is very likely that the navigatorKey
does not contain anything (yet).
How can I detect/wait until the Navigator is ready ?
As of right now my approach is to add a WidgetsBinding.instance.addPostFrameCallback
in my App
's initState
, that resolves a promise to indicate when the GlobalKey
pointing to the NavigatorState
can be used... I'm sure there is a beter way to achieve this.
Upvotes: 1
Views: 991
Reputation: 3686
For this i make the initialRoute as a Loading screen and execute all my logic inside it , that way i can have different initialRoutes and i don't have to worry about not having MediaQuery, or Navigator, or even ThemeData.
However the question specifies a way to know if the navigator is available, for this i would use the builder
function of MaterialApp/WidgetsApp/CupertinoApp, it's used to override the navigator altought i use it to add pading and a global background color and even override the navigator widget with a custom one,
CupertinoApp(
...
builder: (context, child){
//The navigator is ready
Future.delayed(Duration.zero,
() => print(navigatorKey.currentContext)); //We use a delayed since the child needs to be returned first. It's kinda like a hack 7u7
return child;
}
Upvotes: 1