要在Flutter中保持子路由状态的有状态壳路由,可以使用Go Router库。下面是一个包含代码示例的解决方法:
首先,需要在pubspec.yaml
文件中添加Go Router库的依赖:
dependencies:
go_router: ^0.4.0
然后,创建一个ShellRouter
类作为有状态壳路由:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class ShellRouter extends StatefulWidget {
final Widget initialPage;
final Map routes;
const ShellRouter({
Key? key,
required this.initialPage,
required this.routes,
}) : super(key: key);
@override
_ShellRouterState createState() => _ShellRouterState();
}
class _ShellRouterState extends State {
late GoRouter _router;
@override
void initState() {
super.initState();
_router = GoRouter(
initialLocation: '/',
routes: widget.routes,
);
}
@override
void dispose() {
_router.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerDelegate: _router.routerDelegate,
routeInformationParser: _router.routeInformationParser,
routeInformationProvider: _router.routeInformationProvider,
builder: (context, router) {
return widget.initialPage;
},
);
}
}
在ShellRouter
类中,我们使用GoRouter
来处理子路由的状态保持。initialPage
参数用于指定初始页面,routes
参数是一个包含所有子路由的映射。
使用ShellRouter
时,可以将初始页面和子路由作为参数传递给ShellRouter
的构造函数。例如:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ShellRouter(
initialPage: HomePage(),
routes: {
'/': (context, state) => MaterialPage(child: HomePage()),
'/profile': (context, state) => MaterialPage(child: ProfilePage()),
'/settings': (context, state) => MaterialPage(child: SettingsPage()),
},
);
}
}
在routes
参数中,我们使用了MaterialPage
来定义每个子路由的页面。你可以根据需要更改为其他类型的页面。
通过这种方式,子路由的状态将在页面之间保持,并且可以在不同的子路由之间导航而不会丢失状态。
上一篇:保持子进程程序运行并接受新的参数