如何在 onGenerateRoute 中使用我的 UserProvider?我想检查用户是否使用 UserProvider.isLogged() 进行记录,但是当我尝试获取 Userprovider 时,我必须传递路由器中没有的上下文。
我已经尝试将 generateRoute 更改为非静态并通过构造函数将上下文传递给路由器,但它会抛出错误。
主要.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: <SingleChildCloneableWidget>[
ChangeNotifierProvider(builder: (_) => BottomNavigationBarProvider()),
ChangeNotifierProvider(builder: (_) => UserProvider()),
],
child: MaterialApp(
initialRoute: '/',
onGenerateRoute: Router.generateRoute,
title: 'Title,
theme: ThemeData(
primarySwatch: Colors.blue,
),
),);
}
}
路由器.dart
class Router {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (_) => HomePage());
break;
case '/login':
return MaterialPageRoute(builder: (_) => LoginPage());
break;
case '/register':
return MaterialPageRoute(builder: (_) => RegisterPage());
break;
case '/terms':
return MaterialPageRoute(builder: (_) => TermsPage());
break;
case '/home':
return MaterialPageRoute(builder: (_) {
return HomePage();
});
break;
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}')),
));
break;
}
}
}
===我的尝试===
主要.dart
onGenerateRoute: Router(context).generateRoute,
路由器.dart
class Router {
Router(this.context);
BuildContext context;
Route<dynamic> generateRoute(RouteSettings settings) {
final UserProvider userProvider = Provider.of<UserProvider>(context);
userProvider.isLogged();
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (_) => HomePage());
break;
case '/login':
return MaterialPageRoute(builder: (_) => LoginPage());
break;
case '/register':
return MaterialPageRoute(builder: (_) => RegisterPage());
break;
case '/terms':
return MaterialPageRoute(builder: (_) => TermsPage());
break;
case '/home':
return MaterialPageRoute(builder: (_) {
return HomePage();});
break;
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}')),
));
break;
}
}
}
这个“我的尝试”给了我错误。我怎样才能做到这一点?“在此 MyApp 小部件上方找不到正确的 ProviderProvider>。”