当用户打开应用程序时,我显示一个闪屏,同时它加载一些数据。当它完成时,我想显示一个基于该数据的页面。用go_router
包做这件事的正确方法是什么?下面的代码或多或少就是我要做的:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
final GoRouter _router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const SplashScreen(),
),
GoRoute(
path: '/a',
builder: (context, state) => const ScreenA(),
)
],
);
@override
Widget build(BuildContext context) =>
MaterialApp.router(routerConfig: _router);
}
class SplashScreen extends StatelessWidget {
const SplashScreen({super.key});
@override
Widget build(BuildContext context) {
Future.delayed(const Duration(seconds: 1))
.then((value) => GoRouter.of(context).go('/a')); // !!!
return const Center(child: FlutterLogo());
}
}
class ScreenA extends StatelessWidget {
const ScreenA({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Text('Screen A'),
),
);
}
}
代码按预期工作,但我得到错误消息:
Error: Looking up a deactivated widget's ancestor is unsafe.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dar
t 266:49 throw_
packages/flutter/src/widgets/framework.dart 4241:9
<fn>
packages/flutter/src/widgets/framework.dart 4254:14
[_debugCheckStateIsActiveForAncestorLookup]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 557:7 [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future.dart 421:15 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 48:19 internalCallback
怎么了?我该如何解决这个问题?
为了修复它,在文件的顶部创建一个密钥
final GlobalKey<NavigatorState> _rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
并将其作为键添加到_router
定义的根路径中:
navigatorKey: _rootNavigatorKey,
取代
GoRouter.of(context).go('/a')
GoRouter.of(_rootNavigatorKey.currentContext!).go('/a'))