flutter推荐路由器插件:go_router
安装
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 ()), ], ); }