使用GoRouter后Flutter中GetX Snackbar无法显示报空值错误
Flutter应用同时使用go_router和get包,集成go_router后将GetMaterialApp改为GetMaterialApp.router,此时无法正常调用Get.snackbar,抛出空值错误。代码中尝试用key: Get.key替代原有的navigationKey,相关代码如下:
child: GetMaterialApp.router( title: 'Wishlists', key: Get.key, // 怀疑此处是问题所在 routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate, translationsKeys: AppTranslation.translationsKeys, locale: locale, fallbackLocale: fallbackLocale, ),
报错信息:
Error: Unexpected null value.
at Object.throw_ [as throw] (http://localhost:51492/dart_sdk.js:5080:11)
at Object.nullCheck (http://localhost:51492/dart_sdk.js:5399:30)
at [_configureOverlay] (http://localhost:51492/packages/get/get_navigation/src/snackbar/snackbar_controller.dart.lib.js:2970:53)
at [_show] (http://localhost:51492/packages/get/get_navigation/src/snackbar/snackbar_controller.dart.lib.js:3113:30)
这个问题是因为使用GetMaterialApp.router时,Get框架的内部导航上下文未正确初始化,导致Get.snackbar找不到Overlay容器。可以通过以下几种方式解决:
方法一:手动关联全局导航Key
- 创建自定义全局
GlobalKey:
final GlobalKey<NavigatorState> _navKey = GlobalKey<NavigatorState>();
- 在
GetMaterialApp.router中设置该Key,并同步给Get框架:
GetMaterialApp.router( title: 'Wishlists', key: _navKey, navigatorKey: _navKey, // 让Get框架获取到导航上下文 routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate, translationsKeys: AppTranslation.translationsKeys, locale: locale, fallbackLocale: fallbackLocale, );
- 在应用初始化时(比如
main函数中),将该Key赋值给Get:
void main() { Get.navigatorKey = _navKey; runApp(MyApp()); }
方法二:调用Snackbar时显式传入上下文
在调用Get.snackbar时,通过自定义导航Key获取上下文并传入:
Get.snackbar( "提示标题", "提示内容", overlayContext: _navKey.currentContext, );
方法三:使用Get.rawSnackbar替代
如果上述方法无效,可以尝试使用Get.rawSnackbar,它允许更灵活地指定上下文:
Get.rawSnackbar( title: "提示标题", message: "提示内容", context: _navKey.currentContext, );
注:这并非Get或go_router的已知Bug,而是混合使用外部路由与Get框架时,上下文初始化不匹配导致的问题,通过手动关联上下文即可解决。
内容的提问来源于stack exchange,提问作者Chris

