You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Firebase登录逻辑中添加if else判断区分用户类型跳转对应首页

解决方法

核心逻辑:登录获取Firebase Auth生成的用户uid后,通过判断uid归属的集合,执行对应跳转逻辑:

  1. 若uid在users集合中存在,说明是普通用户,跳转MainPage
  2. 若uid在agencies集合中存在(匹配aid字段),说明是机构用户,跳转AgencyHomepage

前置准备

确保已导入Cloud Firestore依赖包:

import 'package:cloud_firestore/cloud_firestore.dart';

修改后的登录函数代码

替换你现有的signIn函数即可:

void signIn(String email, String password) async {
  if (_formKey.currentState!.validate()) {
    try {
      // 执行邮箱密码登录,获取用户凭证
      UserCredential userCredential = await _auth.signInWithEmailAndPassword(
        email: email,
        password: password
      );
      // 获取当前登录用户的uid
      String? currentUid = userCredential.user?.uid;
      if (currentUid == null) return;

      // 第一步:查询普通用户集合
      DocumentSnapshot userDoc = await FirebaseFirestore.instance
          .collection('users')
          .doc(currentUid)
          .get();

      // 显示登录成功提示
      Fluttertoast.showToast(
        timeInSecForIosWeb: 2,
        gravity: ToastGravity.CENTER,
        msg: "登录成功"
      );

      // 普通用户存在,跳转普通用户首页
      if (userDoc.exists) {
        if (!mounted) return;
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => MainPage())
        );
        return;
      }

      // 第二步:普通用户不存在,查询机构用户集合
      QuerySnapshot agencySnapshot = await FirebaseFirestore.instance
          .collection('agencies')
          .where('aid', isEqualTo: currentUid)
          .limit(1)
          .get();

      if (!mounted) return;
      // 机构用户存在,跳转机构首页
      if (agencySnapshot.docs.isNotEmpty) {
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => AgencyHomepage())
        );
      }
    } catch (e) {
      Fluttertoast.showToast(
        timeInSecForIosWeb: 3,
        gravity: ToastGravity.CENTER,
        msg: "邮箱或密码无效,请检查后重试",
      );
    }
  }
}

可选优化

如果你在注册机构用户时,直接把Firebase Auth生成的uid作为agencies集合的文档ID存储,可把机构查询的代码简化为如下写法,查询性能更高:

DocumentSnapshot agencyDoc = await FirebaseFirestore.instance
    .collection('agencies')
    .doc(currentUid)
    .get();

if (agencyDoc.exists) {
  // 跳转机构首页
  Navigator.of(context).pushReplacement(
    MaterialPageRoute(builder: (context) => AgencyHomepage())
  );
}

内容的提问来源于stack exchange,提问作者user17043594

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:36:05