Dart GetX页面刷新时出现Unexpected Null Value错误求助
解决Flutter GetX跳转后刷新页面出现Unexpected Null Value错误
错误根源
你遇到的是GetX 4.6.5版本在Web端的路由恢复bug:使用匿名路由(Get.to(() => AirView()))跳转后刷新页面,路由状态恢复过程中会触发空值异常,进而引发"No Directionality used"提示。
具体解决方案
1. 升级GetX到最新稳定版
旧版本GetX存在Web路由恢复的已知问题,升级到5.x系列稳定版可直接修复。修改pubspec.yaml的依赖配置:
dependencies: get: ^5.0.0 # 替换为最新稳定版本
执行命令更新依赖:
flutter pub get
2. 禁用路由历史恢复
若暂时无法升级,可在GetMaterialApp中关闭路由恢复功能,添加restoreRouteHistory: false参数:
GetMaterialApp( restoreRouteHistory: false, home: HomeView(), // 其他原有配置 )
3. 改用命名路由跳转
注册命名路由替代匿名路由,避免刷新时的状态恢复异常:
- 第一步:在
GetMaterialApp中注册路由表
GetMaterialApp( initialRoute: '/home', getPages: [ GetPage(name: '/home', page: () => HomeView()), GetPage(name: '/air', page: () => AirView()), ], )
- 第二步:修改HomeView中的跳转逻辑
ElevatedButton( onPressed: () { Get.toNamed('/air'); }, child: Text("GO NEXT"), )
4. 检查自定义Scaffold的Directionality
确认CustomScaffold内部已包含Directionality(Material组件通常自动提供,但自定义实现可能缺失),若缺失需手动包裹:
class CustomScaffold extends StatelessWidget { final Widget body; const CustomScaffold({Key? key, required this.body}) : super(key: key); @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Scaffold( body: body, // 其他自定义布局内容 ), ); } }
内容的提问来源于stack exchange,提问作者CodeDon
相关产品推荐
相关产品推荐

