go_router
是一款声明式的路由器插件。写过web项目的,如Python中的Django,前端中的Vue都有类似的声明式路由器,它使用直观、方便。go_router
就是在flutter中的这样一款路由器插件。
flutter pub add go_router
这将在你项目的pubspec.yaml
文依赖中增加以下内容:
dependencies:
go_router: ^3.0.4
// views.dart 用于定义视图
// 视图1
class View1 extends StatelessWidget {...}
// 视图2
class View2 extends StatelessWidget {...}
// routes.dart 用于定义路由器
import 'package:go_router/go_router.dart';
import './views' // 导入定义的视图
// 项目路由
class App extends StatelessWidget {
App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) => MaterialApp.router(
routeInformationParser: _router.routeInformationParser,
routerDelegate: _router.routerDelegate,
title: 'GoRouter Example',
);
final GoRouter _router = GoRouter(
routes: <GoRoute>[
GoRoute(path: '/', builder: (BuildContext context, GoRouterState state) => const View1()),
GoRoute(path: '/page2',builder: (BuildContext context, GoRouterState state) => const View2 ()),
],
);
}