Flutter登录校验路由重定向

2023-07-03  本文已影响0人  itfitness

说明

很多时候我们需要对是否登录进行校验,有些页面假如没有登录的话,不能进行跳转,要先跳转登录页,这里我们使用getx来实现路由的重定向

代码实现

这里我们使用GetPage中间件(middlewares)来实现,首先我们需要先继承GetMiddleware实现自己的MyGetMiddleware,然后重写redirect方法,进行校验并返回对应的对象,如果校验成功返回null即可就是走默认的路由,如果校验失败就返回RouteSettings对象重定向登录页(这里我用随机数来模拟校验)

class MyGetMiddleware extends GetMiddleware{
  @override
  RouteSettings? redirect(String? route) {
    return Random().nextInt(2) == 1 ? RouteSettings(name: '/login') : null;
  }
}

然后我们在配置GetPages的时候对需要校验的页面设置中间件(这里我对SecondPage进行校验)

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()实例化你的类,使其对当下的所有子路由可用。
  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('添加标签', 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找到一个正在被其他页面使用的Controller,并将它返回给你。
  final Controller c = Get.find();
  SecondPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 访问更新后的计数变量
    return Scaffold(
        body: Center(
            child: Column(
              children: [
                Obx(()=>
                    Text("${c.count}")
                ),
                ElevatedButton(onPressed: ()=>{
                  c.increment()
                }, child: Text("点击"))
              ],
            )
        )
    );
  }
}

class LoginPage extends StatelessWidget {
  LoginPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 访问更新后的计数变量
    return Scaffold(
        body: Center(
            child:Text(
              "登录",style: TextStyle(fontSize: 50),
            )
        )
    );
  }
}
上一篇下一篇

猜你喜欢

热点阅读