Fluro 2.0版本与1.0的使用有些差异,所以现在网上大多数的教程已不适用,特出此简易教程供大家参考。
为了方便管理路由中不同类型的方法,建议是分开多个文件写,特定文件写特定的内容,虽然路由可以写在一个文件里,但是当路由过多时文件会很大,不方便维护。
我的写法是一个route文件夹,下面三个文件,分别是application.dart、route.dart、route_handlers.dart
首先,在 application.dart中
import 'package:fluro/fluro.dart';class Application {static late final FluroRouter router;}
在route.dart中 定义路由
import 'package:fluro/fluro.dart';import 'package:flutter/cupertino.dart';import 'package:flutter_demo/components/not_found.dart';import 'package:flutter_demo/route/route_handlers.dart';class Routes {static String setting = "/setting"; //定义路由static void configureRoutes(FluroRouter router) {//处理未匹配到路由时展示的页面router.notFoundHandler = Handler(handlerFunc: (BuildContext? context, Map<String, List<String>> params) {return NotFoundPage();});//注册路由并指向所对应的handler(Handler对应的是界面)router.define(setting, handler: settingHandler);}}
接着 route_handlers.dart
import 'package:fluro/fluro.dart';import 'package:flutter/material.dart';import 'package:flutter_demo/screens/setting/setting.dart';var settingHandler = Handler(handlerFunc: (BuildContext? context, Map<String, List<String>> params) {final args = params['id']!.first; //接收传的参数return Setting(id: args);});
最重要的来了,此时此刻读文章的小伙伴希望你能不急不躁一步步读完,因为缺少一步这个封装都不可能完成!
在项目入口文件中main.dart:
import 'package:fluro/fluro.dart';import 'package:flutter/material.dart';import 'package:flutter_demo/components/tab.dart';import 'package:flutter_demo/route/application.dart';import 'package:flutter_demo/route/route.dart';void main() {runApp(MyApp());}class MyApp extends StatefulWidget {MyApp({Key? key}) : super(key: key);@override_MyAppState createState() => _MyAppState();}class _MyAppState extends State<MyApp> {@overridevoid initState() {super.initState();final router = FluroRouter();Application.router = router; //一定要先写这行Routes.configureRoutes(router); //再写这一行,因为我们在application中为给router初始值,如果先使用它肯定报错,所以要先赋值再使用}@overrideWidget build(BuildContext context) {return MaterialApp(home: const Tabs(),debugShowCheckedModeBanner: false,darkTheme: ThemeData.dark(),onGenerateRoute: Application.router.generator, //全局注册);}}
接着就是在组件中的使用了:
//在方法中使用下面这个跳转Application.router.navigateTo(context, "/setting?id=123", transition: TransitionType.inFromRight);
最后是接收参数,在上面的示例中,我们传参给setting页面,所以我们来到setting界面:
setting.dart
import 'package:date_format/date_format.dart';import 'package:flutter/material.dart';class Setting extends StatefulWidget {const Setting({Key? key, this.id}) : super(key: key);final String? id;@override_SettingState createState() => _SettingState();}class _SettingState extends State<Setting> {var myField = TextEditingController();@overridevoid initState() {//这里使用 widget接收参数myField.text = widget.id!;}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(leading: IconButton(onPressed: (){Navigator.pop(context);}, icon: Icon(Icons.backpack_rounded)),title: Text("设置"),),body: Container(););}}
结局!