You need to enable JavaScript to run this app. Flutter非Widget Auth类如何透传Firebase认证真实异常到UI展示
优惠活动
大模型
产品
解决方案
定价
更多

Flutter非Widget Auth类如何透传Firebase认证真实异常到UI展示

Flutter 认证模块开发问题梳理

核心待解决问题

  • 非Widget结构的AuthService类无法将Firebase认证流程的精准异常信息透传到UI层,导致登录/注册失败时只能展示固定提示,无法反馈“邮箱格式错误”这类细分异常
  • 依赖版本不兼容触发dart:js相关编译错误
  • 升级依赖后Auth类内出现用户类型不匹配、方法参数定义错误的编译问题

开发卡点记录

  • 尝试添加FirebaseAuthException类型判断的异常捕获逻辑时,无论是否添加类型判断,均触发依赖相关编译错误,反复调整后仍未解决
  • 升级firebase_auth版本后,出现用户类型不匹配、signUp方法参数定义错误的编译问题

当前已实现的代码逻辑

1. 登录按钮组件实现

Widget _buildLoginBtn() {
  return Container(
    padding: EdgeInsets.symmetric(vertical: 25.0),
    width: double.infinity,
    child: RawMaterialButton(
        elevation: 5.0,
        padding: EdgeInsets.all(15.0),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(30.0),
        ),
        fillColor: Colors.white,
        child: Text(
          'LOGIN',
          style: TextStyle(
            color: Color(0xFF527DAA),
            letterSpacing: 1.5,
            fontSize: 18.0,
            fontWeight: FontWeight.bold,
            fontFamily: 'OpenSans',
          ),
        ),
        onPressed: () async {
          if (_formKey.currentState.validate()) {
            print('valid');
            setState(() => loading = false);
            dynamic result = await _auth.signIN(email, password);
            if (result == null) {
              setState(() => error = 'Check your Input');
              loading = false;
            }
          }
        }),
  );
}

2. 最初版本的signIN方法实现

Future<String> signIN(String email, String password) async {
  try {
    FirebaseUser user = (await _auth.signInWithEmailAndPassword(
            email: email.trim(), password: password)).user;
  } catch (e) {
    return null;
  }
  if (user != null) {
    print(user);
  }
  return null;
}

该实现的问题是catch块直接返回null,丢失了捕获到的真实异常信息


开发过程中遇到的报错

1. 升级前的依赖配置

cupertino_icons: ^1.0.2
firebase_auth: ^0.14.0+5
cloud_firestore: ^0.12.9+4
firebase_core_web: ^0.2.1+3
provider: ^4.3.3
flutter_svg: ^0.19.2+1
flutter_spinkit: ^4.1.2
auto_size_text: ^2.1.0
firebase_core: ^0.4.0
get_it: ^5.0.6

2. 对应编译报错

Invalid depfile: /Users/MYUSERNAME/Desktop/project neu2/flutter_application_2/.dart_tool/flutter_build/7e96e6ced6aa40f9bcd60c2328bbea3e/kernel_snapshot.d
../../../flutter/.pub-cache/hosted/pub.dartlang.org/js-0.6.3/lib/js.dart:8:1: Error: Not found: 'dart:js'
export 'dart:js' show allowInterop, allowInteropCaptureThis;
../../../flutter/.pub-cache/hosted/pub.dartlang.org/js-0.6.3/lib/js_util.dart:8:1: Error: Not found: 'dart:js_util'
export 'dart:js_util';
../../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-0.2.1+3/lib/src/interop/utils/js_interop.dart:24:7: Error: Method not found: 'hasProperty'.
 if (util.hasProperty(jsObject, 'toDateString')) {
../../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-0.2.1+3/lib/src/interop/utils/utils.dart:39:26: Error: Method not found: 'getProperty'.
     map[key] = dartify(util.getProperty(jsObject, key), customDartify);
../../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-0.2.1+3/lib/src/interop/utils/utils.dart:65:17: Error: Method not found: 'newObject'.
   var jsMap = util.newObject();
../../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-0.2.1+3/lib/src/interop/utils/utils.dart:67:7: Error: Method not found: 'setProperty'.
     util.setProperty(jsMap, key, jsify(value, customJsify));
../../../flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-0.2.1+3/lib/src/interop/utils/utils.dart:73:12: Error: Method not found: 'allowInterop'.

升级依赖后的AuthService类代码

1. 带异常捕获逻辑的版本

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core_web/firebase_core_web_interop.dart';
import 'package:flutter_application_2/models/user.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  String error;

  // 基于FirebaseUser生成自定义User模型
  User _userFromFirebaseUser(FirebaseUser user) {
    return user != null ? User(uid: user.uid) : null;
  }

  // 认证状态监听流
  Stream<User> get user {
    return _auth.onAuthStateChanged.map(_userFromFirebaseUser);
  }

  // 匿名登录
  Future signInAnon() async {
    try {
      AuthResult result = await _auth.signInAnonymously();
      FirebaseUser user = result.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // 邮箱密码登录
  Future<String> signIN(String email, String password) async {
    try {
      FirebaseUser user = (await _auth.signInWithEmailAndPassword(
        email: email.trim(), 
        password: password,
      )).user;
    } on FirebaseAuthException catch (e) {
      switch(e.code) {
        case 'user-not-found': {
          return 'No user found';
        }
        default: {
          return 'Unexpected error!';
        }
      }
    }
    return null;
  }

  // 邮箱密码注册
  Future<String> signUp(String email, String password) async {
    FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
            email: email, password: password)).user;
    try {
      await user.sendEmailVerification();
      return user.uid;
    } catch (e) {
      print(e.toString);
      return null;
    }
  }

  // 退出登录
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // 发送密码重置邮件
  Future<void> sendPasswordResetEmail(String email) async {
    try {
      return await _auth.sendPasswordResetEmail(email: email);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}

2. 调整命名空间后的版本(仍存在类型不匹配报错)

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_application_2/models/user.dart' as Model;

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  String error;

  // 基于FirebaseUser生成自定义User模型
  Model.User _userFromFirebaseUser(Model.User user) {
    return user != null ? Model.User(uid: user.uid) : null;
  }

  // 认证状态监听流
  Stream<Model.User> get user {
    return _auth.onAuthStateChanged.map(_userFromFirebaseUser);
  }

  // 匿名登录
  Future signInAnon() async {
    try {
      UserCredential result = await _auth.signInAnonymously();
      User user = result.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // 邮箱密码登录
  Future<String> signIN(String email, String password) async {
    try {
      User user = (await _auth.signInWithEmailAndPassword(
        email: email.trim(), 
        password: password,
      )).user;
    } on FirebaseAuthException catch (e) {
      switch(e.code) {
        case 'user-not-found': {
          return 'No user found';
        }
        default: {
          return 'Unexpected error!';
        }
      }
    }
    return null;
  }

  // 邮箱密码注册
  Future<String> signUp(String email, String password) async {
    User user = (await _auth.createUserWithEmailAndPassword(
            email: email, password: password)).user;
    try {
      await user.sendEmailVerification();
      return user.uid;
    } catch (e) {
      print(e.toString);
      return null;
    }
  }

  // 退出登录
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // 发送密码重置邮件
  Future<void> sendPasswordResetEmail(String email) async {
    try {
      return await _auth.sendPasswordResetEmail(email: email);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}

signUp方法的实现差异对比

当前编写的版本(存在参数定义错误)

Future<String> signUp(String email, String password, String fullname, String user) async {
  try {
    (await _auth.createUserWithEmailAndPassword(
            email: email.trim(), password: password,)).user.sendEmailVerification();
    await DatbaseService(uid: user.uid).updateUserData('username', 'fullname', 'Passwort', 'Email');
  } on FirebaseAuthException catch (e) {

该版本的参数定义存在问题:user参数声明为String类型,却在代码中取.uid属性,触发类型不匹配报错

参考教程的实现版本

Future registerWithEmailAndAPassword(String email, String passwort) async {
  try {
    AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
    FirebaseUser user = result.user;
    await DatabaseService(uid: user.uid).updateUserData('0', 'new crew member', 100);
    return _userFromFirebaseUser(user);
  } catch (e) {

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 10:24:03