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();
});
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> {
@override
void initState() {
super.initState();
final router = FluroRouter();
Application.router = router;
Routes.configureRoutes(router);
}
@override
Widget 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();
@override
void initState() {
myField.text = widget.id!;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: (){
Navigator.pop(context);
},
icon: Icon(Icons.backpack_rounded)
),
title: Text("设置"),
),
body: Container();
);
}
}
结局!
|