以前使用时MaterialApp
有一种方法可以GlobalContext
使用NavigatorKey
位于MaterialApp widget
.
然而现在看来这种替代方案不再可能了,我有这个结构,如下Navigator 2.0
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
restorationScopeId: 'app',
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
onGenerateTitle: (BuildContext context) =>
AppLocalizations.of(context)!.appTitle,
routeInformationParser: const RoutemasterParser(),
routeInformationProvider: routeInformationProvider,
routerDelegate: introductionRouteMap(context, ref));
}
Run Code Online (Sandbox Code Playgroud)
现在没有任何 NavigatorKey。所以我的问题是,如何使用设置 GlobalContext MaterialApp.router
?
Sab*_*med 11
您可以在 RouterDelegate 中添加 NavigatorKey(未测试)。对于那些正在寻找GoRouter的人,可以在GoRouter构造函数中添加navigatorKey。
如果你只想要一个 GlobalContext,你可以使用scaffoldMessengerKey
它来显示小吃店。
注意:这BuildContext
不适用于导航
final scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp.router(
scaffoldMessengerKey: scaffoldMessengerKey,
);
}
}
Run Code Online (Sandbox Code Playgroud)
访问全局上下文
final context = scaffoldMessengerKey.currentContext!;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7112 次 |
最近记录: |