Reputation: 109
I am facing a problem in my app after updating to new version of flutter (null safety).
i have router and navigator set up as described in code below, when i run the app the router returns error: "type Null is not a subtipe of type ScreenArgs in type cast"
this is probably caused by not initializing any instance of class ScreenArgs, but i can't figure out where is the error.
Layout:
final _navigatorKey = GlobalKey<NavigatorState>();
...
return Scaffold(
backgroundColor: Colors.white,
body: Navigator(
key: _navigatorKey,
initialRoute: profileRoute,
onGenerateRoute: generateRoute,
),
bottomNavigationBar: navBar(),
);
void _onItemTapped(int index) {
setState(() {
_screenIndex = index;
});
switch (index) {
case 0:
_navigatorKey.currentState!.pushNamed(coursesRoute);
break;
}
}
Router:
Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments as ScreenArgs;
switch (settings.name) {
...
case profileRoute:
return PageTransition(
child: const ProfileScreen(), type: PageTransitionType.fade);
case coursesRoute:
return PageTransition(
child: CoursesScreen(
entityId: args.entityId,
),
type: PageTransitionType.fade);
...
}
}
ScreenArgs:
class ScreenArgs {
final String quizId;
final String courseId;
final String entityId;
final numOfQuestions = numberOfQuestions;
ScreenArgs(this.quizId, this.entityId, this.courseId);
}
i tried to initialize instance of ScreenArgs in Layout and pass it in the navigater as followed:
final args = ScreenArgs("","","");
Navigator(
key: _navigatorKey,
initialRoute: profileRoute,
onGenerateRoute: (args) {generateRoute(args);}
),
bottomNavigationBar: navBar(),
);
or in the itemTapped switcher as follows:
switch (index) {
case 0:
_navigatorKey.currentState!.pushNamed(profileRoute, arguments: args);
break;
but nothing worked and i got the same error message and i am stuck onto this for several hours. If anyone sees where i went wrong, please let me know, thanks in advance.
Upvotes: 0
Views: 819
Reputation: 109
problem has been solved. The cause was initializing multiple GlobalKey and the statement that caused the error was
_navigatorKey.currentState!.pushNamed(profileRoute, arguments: args);
namely check
.currentState!.
moved GlobalKey declaration into global variables and used it for both navigator and locator of router and everything is working fine now.
Upvotes: 1