說明
很多時(shí)候我們需要對(duì)是否登錄進(jìn)行校驗(yàn)伸眶,有些頁(yè)面假如沒有登錄的話惊窖,不能進(jìn)行跳轉(zhuǎn),要先跳轉(zhuǎn)登錄頁(yè)厘贼,這里我們使用getx來實(shí)現(xiàn)路由的重定向
代碼實(shí)現(xiàn)
這里我們使用GetPage中間件(middlewares)來實(shí)現(xiàn)界酒,首先我們需要先繼承GetMiddleware實(shí)現(xiàn)自己的MyGetMiddleware,然后重寫redirect方法嘴秸,進(jìn)行校驗(yàn)并返回對(duì)應(yīng)的對(duì)象盾计,如果校驗(yàn)成功返回null即可就是走默認(rèn)的路由,如果校驗(yàn)失敗就返回RouteSettings對(duì)象重定向登錄頁(yè)(這里我用隨機(jī)數(shù)來模擬校驗(yàn))
class MyGetMiddleware extends GetMiddleware{
@override
RouteSettings? redirect(String? route) {
return Random().nextInt(2) == 1 ? RouteSettings(name: '/login') : null;
}
}
然后我們?cè)谂渲肎etPages的時(shí)候?qū)π枰r?yàn)的頁(yè)面設(shè)置中間件(這里我對(duì)SecondPage進(jìn)行校驗(yàn))
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => const MyHomePage(title: 'Flutter Demo Home Page')),
GetPage(name: '/second', page: () => SecondPage(),middlewares: [MyGetMiddleware()]),
GetPage(name: '/login', page: () => LoginPage()),
],
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
)
);
}
}
完整代碼如下
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => const MyHomePage(title: 'Flutter Demo Home Page')),
GetPage(name: '/second', page: () => SecondPage(),middlewares: [MyGetMiddleware()]),
GetPage(name: '/login', page: () => LoginPage()),
],
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
)
);
}
}
class Controller extends GetxController{
var count = 0.obs;
increment() => count++;
}
class MyGetMiddleware extends GetMiddleware{
@override
RouteSettings? redirect(String? route) {
return Random().nextInt(2) == 1 ? RouteSettings(name: '/login') : null;
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// 使用Get.put()實(shí)例化你的類赁遗,使其對(duì)當(dāng)下的所有子路由可用署辉。
final Controller c = Get.put(Controller());
int _counter = 0;
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5))
),
child: Container(
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
color: Colors.white
),
padding: EdgeInsets.fromLTRB(15, 20, 15, 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('添加標(biāo)簽', style: TextStyle(color: Colors.black, fontSize: 16),),
SizedBox(height: 20,),
Container(
height: 40,
decoration: BoxDecoration(
color: Color(0xFFF6F6F6),
borderRadius: BorderRadius.all(Radius.circular(10))
),
)
],
),
),
);
},
);
}
void _incrementCounter() async{
Get.toNamed('/second');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(child: Container(
color: Colors.blue,
child: Obx(() => Text("Clicks: ${c.count}")),
)),
Container(
width: 200,
child: AspectRatio(
aspectRatio: 2,
child: Image.asset("assets/images/ic_test.png",fit: BoxFit.fill,),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class SecondPage extends StatelessWidget {
// 你可以讓Get找到一個(gè)正在被其他頁(yè)面使用的Controller,并將它返回給你岩四。
final Controller c = Get.find();
SecondPage({super.key});
@override
Widget build(BuildContext context) {
// 訪問更新后的計(jì)數(shù)變量
return Scaffold(
body: Center(
child: Column(
children: [
Obx(()=>
Text("${c.count}")
),
ElevatedButton(onPressed: ()=>{
c.increment()
}, child: Text("點(diǎn)擊"))
],
)
)
);
}
}
class LoginPage extends StatelessWidget {
LoginPage({super.key});
@override
Widget build(BuildContext context) {
// 訪問更新后的計(jì)數(shù)變量
return Scaffold(
body: Center(
child:Text(
"登錄",style: TextStyle(fontSize: 50),
)
)
);
}
}