Flutter导航管理插件voyager的使用
Flutter导航管理插件voyager的使用
示例代码
import 'package:voyager/voyager.dart';
import 'package:flutter/material.dart';
/// voyager生成代码
part 'main.voyager.dart';
/// 导航地图,一个yaml文件,可以提供为三重引号字符串
String requirements() {
return '''
---
'/home' :
widget: HomeWidget
title: "This is Home"
'/other/:title' :
widget: OtherWidget
title: "This is %{title}"
'/fab' :
widget: MakeMeFab
target: /other/thing
icon: e88f #检查icons.dart中的参考
'/talks' :
widget: ListWidget
title: "Voyager Talks"
items:
- city: "Berlin"
event: Droidcon
date: July 1, 20119
- city: "London"
event: FlutterLDN
date: October 21, 2019
- city: "Łódź"
event: Mobilization
date: October 26, 2019
- city: "San Francisco"
event: Droidcon
date: November 225-26, 2019
'/_object/Talk':
widget: TalkWidget
'/stay/safe':
redirect: '/home'
'/:notfound:':
title: "Not Found"
widget: PageWidget
body: "Path /%{notfound} not found. Sorry!"
''';
}
/// 导航路径列表(上面的yaml但解析为对象)
List<VoyagerPath> paths() {
return loadPathsFromYamlSync(requirements());
}
/// 插件,如requirements中提到
List<VoyagerPlugin> plugins() => [
/// 提供在yaml中使用的表达式构建器
generatedVoyagerWidgetPlugin(),
generatedVoyagerPagePlugin(),
const RedirectPlugin(),
];
void main() {
/// 初始化路由器
final router = VoyagerRouter.from(paths(), plugins());
/// 运行应用
runApp(VoyagerStackApp(
router: router,
stack: MyStack.initialValue,
onBackPressed: () {
MyStack.pop();
},
onInitialPage: (page) {
if (page is VoyagerPage) {
if (page.path == '/' || page.path == pathHome) {
// 如果初始页面是 '/',我们只会使用默认初始堆栈状态
MyStack.value = MyStack.initialValue;
} else {
// 如果初始页面是其他内容,我们在初始堆栈上添加页面
MyStack.value = MyStack.initialValue.mutate((items) {
items.add(page);
});
}
}
},
onNewPage: (page) {
if (page is VoyagerStack) {
// 堆栈覆盖 - 这发生在例如你处理onInitialPage时
MyStack.value = page;
} else if (page is VoyagerPage) {
// 这发生在某些系统事件中,例如你不处理onInitialPage
MyStack.add(page);
}
},
createApp: (context, parser, delegate) => MaterialApp.router(
title: "Voyager Demo",
routeInformationParser: parser,
routerDelegate: delegate,
theme: ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.blue,
canvasColor: Colors.black,
accentColor: Colors.red,
),
),
));
}
使用说明
-
添加依赖:
dependencies: voyager: ^latest_release
-
定义导航地图:
--- '/home' : widget: HomeWidget title: "This is Home" '/other/:title' : widget: OtherWidget title: "This is %{title}" '/fab' : widget: MakeMeFab target: /other/thing icon: e88f '/talks' : widget: ListWidget title: "Voyager Talks" items: - city: "Berlin" event: Droidcon date: July 1, 2019 - city: "London" event: FlutterLDN date: October 21, 2019 - city: "Łódź" event: Mobilization date: October 26, 2019 - city: "San Francisco" event: Droidcon date: November 25-26, 2019 '/_object/Talk': widget: TalkWidget '/stay/safe': redirect: '/home' '/:notfound:': title: "Not Found" widget: PageWidget body: "Path /%{notfound} not found. Sorry!"
-
初始化路由器:
final router = VoyagerRouter.from(paths(), plugins());
-
选择API:
- Voyager Widget:
VoyagerWidget(path: "/home", router: router);
- Navigator 1.0:
Provider<VoyagerRouter>.value( value: router, child: MaterialApp( home: VoyagerWidget(path: "/my/fancy/super/path"), onGenerateRoute: router.generator() ) );
- Navigator 2.0:
VoyagerStackApp( router: router, stack: VoyagerStack[ VoyagerPage("/my/fancy/super/path"), ], createApp: (context, parser, delegate) => MaterialApp.router( routeInformationParser: parser, routerDelegate: delegate, theme: themeData(), ), );
- Voyager Widget:
-
使用预定义插件:
- Widget Plugin:
WidgetPlugin({ "HomeWidget": (context) => HomeWidget() });
- Page Plugin:
PagePlugin({ "slideFromTop": slideFromTop });
- Widget Plugin:
-
自定义插件:
class TitlePlugin extends RouterPlugin { TitlePlugin() : super("title"); // YAML节点以拦截 @override void outputFor(RouterContext context, dynamic config, Voyager voyager) { voyager["title"] = config.toString(); // 输出此插件 } }
-
依赖注入:
final voyager = context.voyager;
-
代码生成:
flutter packages pub run voyager:codegen --run-once
这将创建
lib/navigation.voyager.dart
文件。 -
Schema 验证:
- name: Voyager source: lib/main.dart target: lib/navigation.voyager.dart schema: icon: pluginStub: true # 添加如果要生成一个插件 stub output: Icon # 相关的 Dart 类由插件生成 input: # 写入节点的 JSON Schema (draft-07 布局) type: string pattern: "^[a-fA-F0-9]{4}$"
更多关于Flutter导航管理插件voyager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter导航管理插件voyager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,Voyager 是一个强大的路由和导航管理插件,它基于 Flutter 的 Navigator 2.0,提供了声明式的路由配置和灵活的权限管理。下面是一个简单的代码示例,展示了如何在 Flutter 应用中使用 Voyager 进行导航管理。
1. 添加依赖
首先,在你的 pubspec.yaml
文件中添加 Voyager 及其依赖:
dependencies:
flutter:
sdk: flutter
voyager: ^x.y.z # 请替换为最新版本号
provider: ^6.0.0 # Voyager 可能依赖此包,具体版本视需求而定
然后运行 flutter pub get
来获取依赖。
2. 配置路由
在你的 Flutter 项目中创建一个 routes.dart
文件来定义你的路由配置。例如:
import 'package:voyager/voyager.dart';
import 'package:flutter/material.dart';
import 'screens/home_screen.dart';
import 'screens/about_screen.dart';
class MyRoutes extends VoyagerRoutes {
@override
List<RouteDef> get routes => [
RouteDef(path: '/', builder: (_, __) => HomeScreen(), name: 'home'),
RouteDef(path: '/about', builder: (_, __) => AboutScreen(), name: 'about'),
// 可以继续添加更多路由
];
}
3. 创建主应用
在你的 main.dart
文件中,设置 Voyager 并运行应用:
import 'package:flutter/material.dart';
import 'package:voyager/voyager.dart';
import 'routes.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return VoyagerMaterialApp(
title: 'Flutter Voyager Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: MyRoutes(),
// 如果需要权限管理,可以在这里配置 VoyagerGuard
// guard: VoyagerGuard(
// user: ...,
// roles: ...,
// ),
home: VoyagerNavigator(
initialPath: '/',
),
);
}
}
4. 创建屏幕
创建 screens/home_screen.dart
和 screens/about_screen.dart
文件,分别定义你的 HomeScreen 和 AboutScreen。例如:
// screens/home_screen.dart
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).pushNamed('/about');
},
child: Text('Go to About'),
),
),
);
}
}
// screens/about_screen.dart
import 'package:flutter/material.dart';
class AboutScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('About Screen'),
),
body: Center(
child: Text('This is the About Screen'),
),
);
}
}
5. 运行应用
现在,你可以运行你的 Flutter 应用,并通过点击 Home Screen 上的按钮导航到 About Screen。
总结
以上代码展示了如何使用 Voyager 插件在 Flutter 应用中进行路由管理。Voyager 提供了灵活的路由配置和声明式语法,使得路由管理更加简单和直观。如果你需要更高级的权限管理功能,可以进一步探索 Voyager 的 VoyagerGuard
和其他高级特性。