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

Flutter实现首次登录强制用户重置密码的方案咨询

实现Flutter首次登录强制重置密码功能

修改后的登录方法代码

Future<void> login({
  required BuildContext context,
  required Map<String, dynamic> map,
}) async {
  EasyLoading.show();
  var response = await loginUsecase.call(map);
  response.fold((l) {
    Logger().d('Error');
    EasyLoading.dismiss();
  }, (r) async {
    SharedPref.setString(kEMAIL, map[kEMAIL]);
    SharedPref.setString(kPASSWORD, map[kPASSWORD]);
    SharedPref.setBool(kLocalAuthSetted, true);
    EasyLoading.dismiss();

    // 查询Firestore用户文档,检查是否需要强制改密码
    try {
      final userEmail = map[kEMAIL];
      final userQuery = await FirebaseFirestore.instance
          .collection('Users')
          .where('email', isEqualTo: userEmail)
          .limit(1)
          .get();

      if (userQuery.docs.isNotEmpty) {
        final changePassword = userQuery.docs.first.data()['ChangePassword'] as bool?;
        
        if (changePassword == true) {
          // 弹出强制修改提示
          await showDialog(
            context: context,
            barrierDismissible: false,
            builder: (ctx) => AlertDialog(
              title: const Text('密码重置提醒'),
              content: const Text('您需要重置密码才能使用应用,请点击确定完成修改'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(ctx);
                    Get.toNamed(AppRoutes.forgotPassword);
                  },
                  child: const Text('确定'),
                ),
              ],
            ),
          );
          return; // 阻止跳转主页面
        }
      }
    } catch (e) {
      Logger().d('查询用户信息失败: $e');
    }

    // 无需改密码,正常进入主页面
    Get.toNamed(AppRoutes.main);
  });
}

关键逻辑说明

  • Firestore查询:登录成功后,通过用户邮箱查询Users集合中的对应文档,用limit(1)保证只返回唯一用户(需确保邮箱在数据库中唯一)。
  • 字段校验:取出ChangePassword字段值,若为true则触发强制改密码流程。
  • 流程拦截:触发改密码时,弹出不可关闭的弹窗引导用户,跳转至忘记密码页面后用return终止后续主页面跳转。
  • 异常处理:用try-catch包裹Firestore查询,避免因网络或权限问题导致应用崩溃。

注意事项

  1. 确保已正确集成Firestore依赖,并配置好数据库访问权限。
  2. 确认AppRoutes.forgotPassword路由已在项目中定义。
  3. 若需更换提示样式,可将AlertDialog替换为Get.snackbar或其他自定义组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:57:34