创建一个CxbRouterManager类如下
// import 'package:fluttet_base/main.dart';
import 'package:flutter/material.dart';
import 'package:fluttet_base/pages/chooselang_page.dart';
import 'package:fluttet_base/pages/home_page.dart';
import 'package:fluttet_base/pages/login_page.dart';
import 'package:fluttet_base/pages/tabbar_page.dart';
class CxbRouterManager extends NavigatorObserver {
/// 配置路径
// static const String mainPage = '/main';
static const String loginPage = '../pages/login_page.dart';
static const String tabbarPage = '../pages/tabbar_page.dart';
static const String homePage = '../pages/home_page.dart';
static const String chooselangPage = '../pages/chooselang_page.dart';
static const String rootPage = tabbarPage;
/// 配置初始化方法
static Map routesMap = {
// mainPage: (contxt, {arguments}) => MyHomePage(arguments: arguments ?? {}),
tabbarPage: ({arguments}) => TabBarPage(),
loginPage: ({arguments}) => LoginPage(),
homePage: ({arguments}) => HomePage(arguments: arguments ?? {}),
chooselangPage: ({arguments}) => ChooselangPage(),
// playdetailPage: ({arguments}) => PlayDetailPage(arguments: arguments ?? {}),
};
// 单例
static final CxbRouterManager _instance = CxbRouterManager._internal();
factory CxbRouterManager() {
return _instance;
}
CxbRouterManager._internal() {
// 初始化代码
}
/// 路由钩子
/// 配置onGenerateRoute 固定写法 这个方法也相当于一个中间件,这里可以做权限判断
var onGenerateRoute = (RouteSettings settings) {
final String? name = settings.name; // /news 或者 /search
final Function? pageContentBuilder =
routesMap[name]; // Function = (contxt) { return const NewsPage()}
print('onGenerateRoute:${settings.name}');
if (pageContentBuilder != null) {
Widget page;
if (settings.arguments != null) {
page = pageContentBuilder(arguments: settings.arguments);
} else {
page = pageContentBuilder();
}
PageRoute route = MaterialPageRoute(builder: (context) => page);
// /// 使用自定义Route
// PageRoute route = CustomPageRoute(page);
/// 不是根页的情况下,进行路由跳转,如果还没登录,总是跳转到登录页
/// 也可以在下面的push方法对跳转进行拦截,也可以添加一些不用拦截的页面,以后如果有需要的话
// if (name != homePage) {
// var isLogined = false;
// if (!isLogined) {
// Widget page = LoginPage();
// route = MaterialPageRoute(builder: (context) => page);
// return route;
// }
// }
return route;
}
return null;
};
/// push
Future<T?> push<T extends Object?>(BuildContext context, Widget page) async {
return await Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
return page;
}));
// /// 使用自定义Route
// return await Navigator.of(context).push(CustomPageRoute(page) as Route<T>);
}
/// 跳到指定页
Future<T?> pushNamed<T extends Object?>(
BuildContext context,
String routeName, {
Object? arguments,
}) async {
var isLogined = false;
/// 进行路由跳转,如果还没登录,总是跳转到登录页
/// 也可以添加一些不用拦截的页面,比如设置语言页面
if (routeName != chooselangPage) {
if (!isLogined) {
routeName = loginPage;
}
}
return await Navigator.pushNamed(context, routeName, arguments: arguments);
}
/// 替换本页
Future<T?> pushReplacementNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
Object? arguments,
}) async {
return await Navigator.pushReplacementNamed(context, routeName,
arguments: arguments);
}
/// 返回上一页
void pop(BuildContext context, dynamic) {
Navigator.pop(context, dynamic);
}
/// 返回到根
Future<T?> pushAndRemoveUntil<T extends Object?>(
BuildContext context, Widget page, RoutePredicate predicate) async {
/// 它自己的Route
return await Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (BuildContext context) {
return page;
}), predicate);
// /// 使用自定义Route
// return await Navigator.of(context)
// .pushAndRemoveUntil(CustomPageRoute(page) as Route<T>, predicate);
// return await Navigator.of(context).pushAndRemoveUntil(
// MaterialPageRoute(builder: (BuildContext context) {
// return Tabs(index: 3);
// }), (route) => false);
}
}
/// 自定义路由,可以设置转场动画
class CustomPageRoute extends PageRouteBuilder {
final Widget widget;
CustomPageRoute(this.widget)
: super(
transitionDuration: Duration(milliseconds: 500), // 动画时长
pageBuilder: (
BuildContext context,
Animation<double> animation1,
Animation<double> animation2,
) {
return widget;
},
transitionsBuilder: (BuildContext context,
Animation<double> animation1,
Animation<double> animation2,
Widget child) {
/// 在这里定义转场动画
return SlideTransition(
// 左右滑动
position:
Tween<Offset>(begin: Offset(1.0, 0.0), end: Offset(0.0, 0.0))
.animate(CurvedAnimation(
parent: animation1, curve: Curves.fastOutSlowIn)),
child: child,
);
// return FadeTransition(
// // 渐进
// opacity: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
// parent: animation1, curve: Curves.fastOutSlowIn)),
// child: child,
// );
// return ScaleTransition(
// // 缩放
// scale: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
// parent: animation1, curve: Curves.fastOutSlowIn)),
// child: child,
// );
// return RotationTransition(
// // 旋转
// turns: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(
// parent: animation1, curve: Curves.fastOutSlowIn)),
// child: child,
// );
},
);
}
在main.dart中使用,看CxbRouterManager,其他不用管
import 'package:flutter/material.dart';
import 'package:fluttet_base/cxb_util/user_settings/app_box.dart';
import 'package:fluttet_base/language/messages.dart';
import 'package:fluttet_base/routers/cxb_router_manager.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
// CXBRouter router = CXBRouter();
void main() async {
await Hive.initFlutter();
await Hive.openBox('appBox');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
Locale? getLocale() {
Locale? appLocale;
switch (AppBox.shared.language) {
case 0: //跟隨系統
appLocale = Get.deviceLocale;
break;
case 1: //简体中文
appLocale = const Locale('zh', 'CN');
break;
case 2: //English
appLocale = const Locale('en', 'US');
break;
default:
appLocale = Get.deviceLocale;
break;
}
return appLocale;
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
/// 使用GetX的GetMaterialApp做多语言国际化
return GetMaterialApp(
translations: Messages(), // 多语言
locale: getLocale(),
fallbackLocale: Locale("zh", "CN"), // 支持的语言
darkTheme: ThemeData.dark(),
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
// theme: ThemeData.light(),
theme: ThemeData(
// colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
platform: TargetPlatform.iOS, // 使页面跳转时从左至右滑动
),
initialRoute: CxbRouterManager.rootPage, // 根页面
onGenerateRoute: CxbRouterManager().onGenerateRoute, // 路由钩子
navigatorObservers: [CxbRouterManager()], // 路由观察者
);
}
}