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

Flutter应用Firebase登录/注册加载过慢问题求助

Flutter登录/注册后返回首页耗时过长问题解决

我是新手,这是第一个问题。我开发的Flutter应用默认先显示首页,点击头像图标后需要登录来创建个人资料并保存工作内容。现在遇到的问题是,登录或注册后要等3-5分钟才能回到首页,耗时太长了。

AuthService代码

class AuthService{

  final FirebaseAuth _auth = FirebaseAuth.instance;

  // 根据FirebaseUser创建用户对象
  UserModel? _userFromFirebaseUser (User? user){
    return user != null ? UserModel(uid: user.uid) : null;
  }  

  // 使用邮箱密码注册
  Future signUp(String email, String password) async {
    try{
      UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
     return _userFromFirebaseUser(user);
    } 
    on FirebaseAuthException catch (e){
      Utils.showSnackBar(e.message, Colors.red);
    }
  }


  // 使用邮箱密码登录
  Future logIn(String email, String password) async {
    try{
      UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
      return _userFromFirebaseUser(user);
    } 
    on FirebaseAuthException catch (e){
      Utils.showSnackBar(e.message, Colors.red);
    }
  }

}

注册按钮实现代码

ElevatedButton(
                   onPressed: () async {
                      final isValid = _formKey.currentState!.validate();
                      if(!isValid) return;
                      showDialog(
                        context: context,
                        builder: (context) => const Center(child: CircularProgressIndicator()),
                      );
                      await _auth.signUp(_emailCont.text.trim(), _passwordCont.text.trim());
                      navigatorKey.currentState!.popUntil((route) => route.isFirst);
                    },
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 138, vertical: 13),
                      shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30)),
                    ),
                    child: const Text(
                      'Sign Up',
                      style: TextStyle(fontSize: 22, letterSpacing: 1.5),
                    ),
                  ),

问题排查与解决办法

1. 先关闭加载弹窗再执行导航

当前代码中,注册完成后直接调用popUntil返回首页,但加载弹窗还停留在导航栈中,可能导致导航逻辑阻塞。修改注册按钮的onPressed逻辑:

onPressed: () async {
  final isValid = _formKey.currentState!.validate();
  if(!isValid) return;
  
  // 显示加载弹窗
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (context) => const Center(child: CircularProgressIndicator()),
  );
  
  try {
    await _auth.signUp(_emailCont.text.trim(), _passwordCont.text.trim());
    // 先关闭加载弹窗
    Navigator.of(context).pop();
    // 再返回首页
    navigatorKey.currentState!.popUntil((route) => route.isFirst);
  } catch (e) {
    // 出错时也要关闭弹窗
    Navigator.of(context).pop();
    // 确保页面挂载时显示错误提示
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(e.toString()), backgroundColor: Colors.red)
      );
    }
  }
},

2. 修复AuthService的异常返回逻辑

当前signUp和logIn方法捕获异常后无明确返回值,会导致await调用出现不可预期的等待。修改方法:

Future<UserModel?> signUp(String email, String password) async {
  try{
    UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
    User? user = result.user;
    return _userFromFirebaseUser(user);
  } 
  on FirebaseAuthException catch (e){
    Utils.showSnackBar(e.message, Colors.red);
    return null; // 明确返回null
  }
}

Future<UserModel?> logIn(String email, String password) async {
  try{
    UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
    User? user = result.user;
    return _userFromFirebaseUser(user);
  } 
  on FirebaseAuthException catch (e){
    Utils.showSnackBar(e.message, Colors.red);
    return null; // 明确返回null
  }
}

3. 检查Utils.showSnackBar的实现

如果Utils.showSnackBar未在Flutter主线程执行,会阻塞UI导致延迟。修改实现确保主线程执行:

// 修改Utils.showSnackBar
static void showSnackBar(String? message, Color color) {
  if (message == null) return;
  
  WidgetsBinding.instance.addPostFrameCallback((_) {
    if (navigatorKey.currentContext != null) {
      ScaffoldMessenger.of(navigatorKey.currentContext!).showSnackBar(
        SnackBar(content: Text(message), backgroundColor: color)
      );
    }
  });
}

4. 排查网络与Firebase配置问题

如果以上修改后仍有延迟,检查:

  • 设备网络连接是否稳定,切换网络测试
  • Firebase控制台是否正确配置了应用的SHA-1指纹(Android)或团队ID(iOS)
  • 确认Firebase Auth服务已在控制台启用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:40:27