-
为了方便与h5的url进行交互,flutter项目的路由名称还是定义为
/product/detail
这种风格 -
每个页面定义一个常量变量
routeName
表示页面路由的地址,所有页面的参数都通过Map arguments
传递方便统一管理
(ps:这里没做抽象,可以定义一个interface,让所有页面实现它)
class UniqueProdListWidget extends StatefulWidget {
static const routeName = '/product/detail';
UniqueProdListWidget({this.arguments});
final Map arguments;
@override
_UniqueProdListWidgetState createState() =>
new _UniqueProdListWidgetState(arguments: this.arguments);
}
...具体的页面实现
- route映射
import 'package:flutter/material.dart';
/// 配置路由示例
///需要参数和不需要参数的配置方式
final Map<String, dynamic> routes = {
HomeTab.routeName: (context, {Map arguments}) => HomeTab(),
UserAgreementPage.routeName: (context) => UserAgreementPage(),
EventCollectListWidget.routeName: (context, {Map arguments}) =>
EventCollectListWidget(arguments: arguments)
};
//固定写法:
var onGenerateRoute = _onGenerateRoute;
Route<dynamic> _onGenerateRoute(RouteSettings settings) {
String name = settings.name;
dynamic routeData = Utility.formateUrlParams(name);
Map<String, String> arguments = settings.arguments;
if (routeData != null) {
name = routeData['routeName'];
arguments = routeData['paramObj'];
}
final Function pageContentBuilder = routes[name];
final Function noFoundBuilder = routes[NoExist.routeName];
if (pageContentBuilder != null) {
if (arguments != null) {
final Route route = MaterialPageRoute(builder: (context) {
//可以在此处做一些未登录的拦截判断
// if (!Utility.isEmpty(Global.token)) {
return pageContentBuilder(context, arguments: arguments);
// } else {
// return noFoundBuilder(context);
// }
});
return route;
} else {
final Route route = MaterialPageRoute(builder: (context) {
// if (!Utility.isEmpty(Global.token)) {
// // 统一处理
return pageContentBuilder(context);
// } else {
// return noFoundBuilder(context);
// }
});
return route;
}
} else {
final Route route = MaterialPageRoute(builder: (context) {
return noFoundBuilder(context);
});
return route;
}
}
- 实现main中
onGenerateRoute
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'test',
theme: ThemeData(
primarySwatch: Colors.blue, accentColor: Global.Color_Gold),
onGenerateRoute: onGenerateRoute,
home: Home());
}
}
网友评论