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

如何修改Flutter Firebase UI界面中的错误提示信息?

自定义Firebase UI Auth的错误提示

要替换Cloud Functions返回的原始错误信息为友好提示,可通过以下步骤实现:

1. 编写错误转换函数

创建一个函数,根据Firebase错误码映射为用户友好的提示文本:

String getFriendlyErrorMessage(dynamic exception) {
  if (exception is FirebaseAuthException) {
    switch (exception.code) {
      // 通用Auth错误码
      case 'invalid-email':
        return '请输入有效的邮箱地址';
      case 'user-not-found':
        return '该账号不存在,请检查输入';
      case 'wrong-password':
        return '密码错误,请重新输入';
      case 'user-disabled':
        return '您的账号已被禁用,请联系客服';
      // 自定义Cloud Functions错误码(需与后端抛出的code一致)
      case 'insufficient-permissions':
        return '您没有权限执行此操作';
      case 'operation-not-allowed':
        return '当前功能暂未开放,请稍后尝试';
      default:
        return '操作失败,请稍后再试';
    }
  }
  // 处理其他类型错误
  return '操作失败,请稍后再试';
}

2. 在Firebase UI组件中配置错误构建器

在使用SignInScreen、RegisterScreen等Firebase UI组件时,通过errorBuilder属性自定义错误显示:

SignInScreen(
  // 其他配置项(如provider、header等)
  errorBuilder: (context, exception, stackTrace) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Text(
        getFriendlyErrorMessage(exception),
        style: const TextStyle(color: Colors.red),
      ),
    );
  },
)

3. 确保Cloud Functions错误抛出规范

在Cloud Functions中,使用functions.https.HttpsError抛出错误并指定明确的错误码,这样前端才能正确捕获并映射:

// Cloud Functions示例代码
exports.updateUserProfile = functions.https.onCall((data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError(
      'unauthenticated', 
      '用户未登录,无法执行此操作'
    );
  }
  // 业务逻辑校验失败时抛出对应错误
  if (!data.nickname) {
    throw new functions.https.HttpsError(
      'invalid-argument', 
      '请输入昵称'
    );
  }
  // 其他业务逻辑...
});

这样配置后,当Cloud Functions返回错误时,Firebase UI会显示你定义的友好提示,而非原始错误信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:33:20