Fluro
做爲 一個Flutter
的 企業級的路由框架 ,確實不錯,能夠解決多變的需求狀況 ,是時候搞一波了。 我看了官方的demo
,寫的有點亂(反正我是這樣感受的,老外的代碼老是有點抽象),順便擴展一下傳參的問題和使用 Flutter
的 cupertino
轉場動畫。寫了一個demo
, 地址在:在這裏在這裏,快點我,快快快 git
本文基於 Fluro 目前版本 1.4.0 pub.dev/packages/fl…github
class Application {
static Router router;
}
複製代碼
在routes.dart
文件中配置路由,這裏須要注意的事首頁必定要用「/」配置json
class Routes {
static String root = "/";
static String home = "/home";
static String demoParams = "/deme_params";
static String returnParams = "/return_params";
static String transitionDemo = "/transitionDemo";
static String transitionCustomDemo = "/transitionCustomDemo";
static String transitionCupertinoDemo = "/transitionCupertinoDemo";
static void configureRoutes(Router router) {
router.notFoundHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
print("ROUTE WAS NOT FOUND !!!");
});
/// 第一個參數是路由地址,第二個參數是頁面跳轉和傳參,第三個參數是默認的轉場動畫,能夠看上圖
/// 我這邊先不設置默認的轉場動畫,轉場動畫在下面會講,能夠在另一個地方設置(能夠看NavigatorUtil類)
router.define(root, handler: splashHandler);
router.define(home, handler: homeHandler);
router.define(demoParams, handler: demoParamHandler);
router.define(returnParams, handler: returnParamHandler);
router.define(transitionDemo, handler: transitionDemoHandler);
router.define(transitionCustomDemo, handler: transitionDemoHandler);
router.define(transitionCupertinoDemo, handler: transitionDemoHandler);
}
}
複製代碼
void main() {
// 註冊 fluro routes
Router router = Router();
Routes.configureRoutes(router);
Application.router = router;
runApp(MyApp());
}
複製代碼
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Weather App',
/// 生成路由
onGenerateRoute: Application.router.generator,
);
}
}
複製代碼
只摘取相關代碼,完整代碼去 github
查看,在文章最頂部微信
首先App啓動,先進入 首頁Splash 頁面,而後 倒計時2秒,再進入home頁面markdown
/// 這邊設置了首頁,固定寫法 /
static String root = "/";
/// home 頁面的 路由地址
static String home = "/home";
/// splashHandler 就是頁面跳轉,在route_handlers.dart
router.define(root, handler: splashHandler);
/// homeHandler home頁面
router.define(home, handler: homeHandler);
複製代碼
/// 跳轉到首頁Splash
var splashHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
return new SplashPag();
});
/// 跳轉到主頁
var homeHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
return HomePage();
});
複製代碼
class SplashPag extends StatefulWidget {
@override
_SplashPagState createState() => _SplashPagState();
}
class _SplashPagState extends State<SplashPag> {
@override
void initState() {
// Future.delayed(Duration(seconds: 5),(){
// NavigatorUtil.goHomePage(context);
// });
/// 2秒後跳轉到主頁面,上面註釋的代碼也能夠作到倒計時
Observable.timer(0, Duration(seconds: 2)).listen((_){
/// 而後看 NavigatorUtil.dart
NavigatorUtil.goHomePage(context);
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: Text('我是歡迎頁面'),
),
),
);
}
}
複製代碼
/// 跳轉到主頁面
static void goHomePage(BuildContext context) {
/// Routes.home 路由地址
/// replace:true 就是將 splash 頁面給移除掉了,這點後退鍵的時候就不會再出現Splash頁面
Application.router.navigateTo(context, Routes.home, replace: true);
}
複製代碼
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
String name = "來自第一個界面測試一下";
int age = 14;
double score = 6.4;
bool sex = true;
Person person = new Person(name: 'Zeking', age: 18, sex: true);
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(child: Text('這是主頁')),
RaisedButton(
child: Text('傳遞參數string ,int,double,bool ,自定義類型'),
onPressed: () {
NavigatorUtil.goDemoParamsPage(
context, name, age, score, sex, person);
},
),
RaisedButton(
child: Text('傳遞參數,接受返回值'),
onPressed: () {
NavigatorUtil.goReturnParamsPage(context).then((result) {
debugPrint('${result.runtimeType}');
String message ;
/// 若是是 自定義的 Person 類
if (result.runtimeType == Person) {
message = result.toJson().toString();
debugPrint('${result.toJson().toString()}');
} else {
message = '$result';
debugPrint('$result');
}
showResultDialog(context, message);
});
},
),
RaisedButton(
child: Text('框架 自帶 轉場動畫 演示'),
onPressed: () {
NavigatorUtil.gotransitionDemoPage(context,
/// 這邊進行了 String 編碼
FluroConvertUtils.fluroCnParamsEncode("框架 自帶 轉場動畫 演示 \n\n\n "
"這邊只展現 inFromLeft ,剩下的本身去嘗試下,\n\n\n "
"架自帶的有 native,nativeModal,inFromLeft,inFromRight,inFromBottom,fadeIn,custom"));
},
),
RaisedButton(
child: Text('框架 自定義 轉場動畫 演示'),
onPressed: () {
NavigatorUtil.gotransitionCustomDemoPage(context,
FluroConvertUtils.fluroCnParamsEncode('框架 自定義 轉場動畫 演示'));
},
),
RaisedButton(
child: Text('修改源碼,添加使用 Flutter 的 cupertino 轉場動畫'),
onPressed: () {
NavigatorUtil.gotransitionCupertinoDemoPage(
context,
FluroConvertUtils.fluroCnParamsEncode(
"修改源碼,添加使用 Flutter 的 cupertino 轉場動畫"));
},
),
],
),
);
}
/// 顯示一個Dialgo
void showResultDialog(BuildContext context,String message){
showDialog(
context: context,
builder: (context) {
return new AlertDialog(
title: new Text(
"Hey Hey!",
style: new TextStyle(
color: const Color(0xFF00D6F7),
fontFamily: "Lazer84",
fontSize: 22.0,
),
),
content: new Text("$message"),
actions: <Widget>[
new Padding(
padding: new EdgeInsets.only(bottom: 8.0, right: 8.0),
child: new FlatButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: new Text("OK"),
),
),
],
);
},
);
}
}
複製代碼
Fluro
路由地址,只能傳遞String
類型(而且不支持中文),因此須要對 中文,int
,double
,bool
,自定義類型進行一個轉換 , 寫了一個 轉換類 fluro_convert_util.dart
app
import 'dart:convert';
/// fluro 參數編碼解碼工具類
class FluroConvertUtils {
/// fluro 傳遞中文參數前,先轉換,fluro 不支持中文傳遞
static String fluroCnParamsEncode(String originalCn) {
return jsonEncode(Utf8Encoder().convert(originalCn));
}
/// fluro 傳遞後取出參數,解析
static String fluroCnParamsDecode(String encodeCn) {
var list = List<int>();
///字符串解碼
jsonDecode(encodeCn).forEach(list.add);
String value = Utf8Decoder().convert(list);
return value;
}
/// string 轉爲 int
static int string2int(String str) {
return int.parse(str);
}
/// string 轉爲 double
static double string2double(String str) {
return double.parse(str);
}
/// string 轉爲 bool
static bool string2bool(String str) {
if (str == 'true') {
return true;
} else {
return false;
}
}
/// object 轉爲 string json
static String object2string<T>(T t) {
return fluroCnParamsEncode(jsonEncode(t));
}
/// string json 轉爲 map
static Map<String, dynamic> string2map(String str) {
return json.decode(fluroCnParamsDecode(str));
}
}
複製代碼
class Person{
String name;
int age;
bool sex;
Person({this.name, this.age,this.sex});
Person.fromJson(Map<String, dynamic> json) {
name = json['name'];
age = json['age'];
sex = json['sex'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
data['sex'] = this.sex;
return data;
}
}
複製代碼
/// 配置路由地址 和 跳轉類和參數handler
static String demoParams = "/deme_params";
router.define(demoParams, handler: demoParamHandler);
複製代碼
/// 參數傳遞 int ,double,bool,自定義類型
var demoParamHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<Object>> params) {
/// params["name"]?.first 至關於 params["name"][0] ,打個debug 你就知道爲何了是個list
String name = params["name"]?.first;
String age = params["age"]?.first;
String sex = params["sex"]?.first;
String score = params["score"]?.first;
String personjson = params['personjson']?.first;
/// 下面轉換爲真實想要的類型
return DemoParamsPage(
name: name,
age: FluroConvertUtils.string2int(age),
score: FluroConvertUtils.string2double(score),
sex: FluroConvertUtils.string2bool(sex),
personJson: personjson,
);
});
複製代碼
/// 跳轉到 傳參demo 頁面
static void goDemoParamsPage(BuildContext context, String name, int age,
double score, bool sex, Person person) {
/// 對中文進行編碼
String mName = FluroConvertUtils.fluroCnParamsEncode(name);
/// 對自定義類型 轉爲 json string
String personJson = FluroConvertUtils.object2string(person);
Application.router.navigateTo(
context,
Routes.demoParams +
"?name=$name&age=$age&score=$score&sex=$sex&personjson=$personJson");
}
複製代碼
String name = "來自第一個界面測試一下";
int age = 14;
double score = 6.4;
bool sex = true;
Person person = new Person(name: 'Zeking', age: 18, sex: true);
RaisedButton(
child: Text('傳遞參數string ,int,double,bool ,自定義類型'),
onPressed: () {
NavigatorUtil.goDemoParamsPage(
context, name, age, score, sex, person);
},
),
複製代碼
class DemoParamsPage extends StatefulWidget {
final String name;
final int age;
final double score;
final bool sex;
final String personJson;
DemoParamsPage({this.name, this.age, this.score, this.sex, this.personJson});
@override
_DemoParamsPageState createState() => _DemoParamsPageState();
}
class _DemoParamsPageState extends State<DemoParamsPage> {
@override
Widget build(BuildContext context) {
/// 對 中文 進行解碼
String mName = FluroConvertUtils.fluroCnParamsDecode(widget.name);
/// 對自定義類 進行解析
Person person =
Person.fromJson(FluroConvertUtils.string2map(widget.personJson));
print(person.name);
print(person.age);
print(person.sex);
/// 下面的寫法也能夠
Map<String, dynamic> data = FluroConvertUtils.string2map(widget.personJson);
print(data["name"]);
print(data["age"]);
print(data["sex"]);
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('name:$mName'),
Text('age:${widget.age}'),
Text('score:${widget.score}'),
Text('sex:${widget.sex}'),
Text('Person:${person.toJson().toString()}'),
RaisedButton(
child: Text('返回'),
onPressed: () {
NavigatorUtil.goBack(context);
},
)
],
),
),
);
}
}
複製代碼
static String returnParams = "/return_params";
router.define(returnParams, handler: returnParamHandler);
複製代碼
/// 關閉頁面,返回參數
var returnParamHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<Object>> params) {
return ReturnParamsPage();
});
複製代碼
/// 跳轉到 會返回參數的 頁面
static Future goReturnParamsPage(BuildContext context) {
return Application.router.navigateTo(context, Routes.returnParams);
}
複製代碼
RaisedButton(
child: Text('傳遞參數,接受返回值'),
onPressed: () {
NavigatorUtil.goReturnParamsPage(context).then((result) {
debugPrint('${result.runtimeType}');
String message ;
/// 若是是 自定義的 Person 類
if (result.runtimeType == Person) {
message = result.toJson().toString();
debugPrint('${result.toJson().toString()}');
} else {
message = '$result';
debugPrint('$result');
}
showResultDialog(context, message);
});
},
)
/// 顯示一個Dialgo
void showResultDialog(BuildContext context,String message){
showDialog(
context: context,
builder: (context) {
return new AlertDialog(
title: new Text(
"Hey Hey!",
style: new TextStyle(
color: const Color(0xFF00D6F7),
fontFamily: "Lazer84",
fontSize: 22.0,
),
),
content: new Text("$message"),
actions: <Widget>[
new Padding(
padding: new EdgeInsets.only(bottom: 8.0, right: 8.0),
child: new FlatButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: new Text("OK"),
),
),
],
);
},
);
}
複製代碼
class ReturnParamsPage extends StatefulWidget {
@override
_ReturnParamsPageState createState() => _ReturnParamsPageState();
}
class _ReturnParamsPageState extends State<ReturnParamsPage> {
@override
Widget build(BuildContext context) {
Person person = new Person(name: "returnName", age: 23, sex: false);
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: RaisedButton(
child: Text('返回,而且返回string'),
onPressed: () {
NavigatorUtil.goBackWithParams(context, "我是返回值哦");
},
),
),
RaisedButton(
child: Text('返回,而且返回int'),
onPressed: () {
NavigatorUtil.goBackWithParams(context, 12);
},
),
RaisedButton(
child: Text('返回,而且返回double'),
onPressed: () {
NavigatorUtil.goBackWithParams(context, 3.1415926);
},
),
RaisedButton(
child: Text('返回,而且返回bool'),
onPressed: () {
NavigatorUtil.goBackWithParams(context, true);
},
),
RaisedButton(
child: Text('返回,而且返回自定義類型'),
onPressed: () {
NavigatorUtil.goBackWithParams(context, person);
},
)
],
),
);
}
}
複製代碼
static String transitionDemo = "/transitionDemo";
router.define(transitionDemo, handler: transitionDemoHandler);
複製代碼
/// 轉場動畫 頁面
var transitionDemoHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<Object>> params) {
String title = params["title"]?.first;
return TransitionDemoPage(title);
});
複製代碼
/// 跳轉到 轉場動畫 頁面 , 這邊只展現 inFromLeft ,剩下的本身去嘗試下,
/// 框架自帶的有 native,nativeModal,inFromLeft,inFromRight,inFromBottom,fadeIn,custom
static Future gotransitionDemoPage(BuildContext context, String title) {
return Application.router.navigateTo(
context, Routes.transitionDemo + "?title=$title",
/// 指定了 轉場動畫 inFromLeft
transition: TransitionType.inFromLeft);
}
複製代碼
RaisedButton(
child: Text('框架 自帶 轉場動畫 演示'),
onPressed: () {
NavigatorUtil.gotransitionDemoPage(context,
/// 這邊進行了 String 編碼
FluroConvertUtils.fluroCnParamsEncode("框架 自帶 轉場動畫 演示 \n\n\n "
"這邊只展現 inFromLeft ,剩下的本身去嘗試下,\n\n\n "
"架自帶的有 native,nativeModal,inFromLeft,inFromRight,inFromBottom,fadeIn,custom"));
},
),
複製代碼
場景五 ,場景六 ,用到同樣的 transition_demo_page 後面就不展現了框架
class TransitionDemoPage extends StatefulWidget {
final String title;
TransitionDemoPage(this.title);
@override
_TransitionDemoPageState createState() => _TransitionDemoPageState();
}
class _TransitionDemoPageState extends State<TransitionDemoPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text(
/// string 解碼
FluroConvertUtils.fluroCnParamsDecode(widget.title),
textAlign: TextAlign.center,
)),
RaisedButton(
child: Text('返回'),
onPressed: () {
NavigatorUtil.goBack(context);
},
)
],
),
);
}
}
複製代碼
static String transitionCustomDemo = "/transitionCustomDemo";
router.define(transitionCustomDemo, handler: transitionDemoHandler);
複製代碼
/// 轉場動畫 頁面
var transitionDemoHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<Object>> params) {
String title = params["title"]?.first;
return TransitionDemoPage(title);
});
複製代碼
/// 自定義 轉場動畫
static Future gotransitionCustomDemoPage(BuildContext context, String title) {
var transition = (BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) {
return new ScaleTransition(
scale: animation,
child: new RotationTransition(
turns: animation,
child: child,
),
);
};
return Application.router.navigateTo(
context, Routes.transitionCustomDemo + "?title=$title",
transition: TransitionType.custom, /// 指定是自定義動畫
transitionBuilder: transition, /// 自定義的動畫
transitionDuration: const Duration(milliseconds: 600)); /// 時間
}
複製代碼
RaisedButton(
child: Text('框架 自定義 轉場動畫 演示'),
onPressed: () {
NavigatorUtil.gotransitionCustomDemoPage(context,
FluroConvertUtils.fluroCnParamsEncode('框架 自定義 轉場動畫 演示'));
},
),
複製代碼
看下圖,發現它自帶的 轉場動畫 只有 這幾個,沒有我喜歡的Flutter
的cupertino
轉場動畫,側滑關閉頁面,less
繼續看源碼 ,看下圖,最後也是調用了系統的MaterialPageRoute
和 PageRouteBuilder
ide
看下圖,本身添加 cupertino
類型 工具
CupertinoPageRoute
static String transitionCupertinoDemo = "/transitionCupertinoDemo";
router.define(transitionCupertinoDemo, handler: transitionDemoHandler);
複製代碼
/// 轉場動畫 頁面
var transitionDemoHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<Object>> params) {
String title = params["title"]?.first;
return TransitionDemoPage(title);
})
複製代碼
/// 使用 IOS 的 Cupertino 的轉場動畫,這個是修改了源碼的 轉場動畫
/// Fluro自己不帶,可是 Flutter自帶
static Future gotransitionCupertinoDemoPage(
BuildContext context, String title) {
return Application.router.navigateTo(
context, Routes.transitionCupertinoDemo + "?title=$title",
transition: TransitionType.cupertino);
}
複製代碼
RaisedButton(
child: Text('修改源碼,添加使用 Flutter 的 cupertino 轉場動畫'),
onPressed: () {
NavigatorUtil.gotransitionCupertinoDemoPage(
context,
FluroConvertUtils.fluroCnParamsEncode(
"修改源碼,添加使用 Flutter 的 cupertino 轉場動畫"));
},
複製代碼