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

Flutter中Firebase数据上传的错误处理与加载进度显示实现

给Firebase数据上传添加加载进度与错误处理

针对你的需求,我们可以通过状态管理实现加载进度显示,用try-catch捕获异常处理错误,下面是修改后的完整实现:

1. 基础准备

确保你的页面是StatefulWidget(如果当前是无状态组件,需要转换成它,因为要动态更新加载状态)。

2. 修改后的代码

floatingActionButton: FloatingActionButton(
  onPressed: () async {
    // 弹出加载弹窗,禁止点击外部关闭
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

    try {
      final newHome = Home(
        urlPhotohome: urlPhotohome,
        urlPhotoStreet: urlPhotoStreet,
        dateTime: DateTime.now(),
        isFavorite: false,
      );

      // 执行Firebase数据上传操作
      await FirebaseFirestore.instance
          .collection('city')
          .doc(userId)
          .collection('home')
          .add(newHome.toMap());

      // 上传成功,关闭加载弹窗
      Navigator.pop(context);

      // 显示成功提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("房屋信息保存成功"),
          duration: Duration(milliseconds: 900),
        ),
      );
    } catch (e) {
      // 上传出错,关闭加载弹窗
      Navigator.pop(context);

      // 区分异常类型,生成对应提示文本
      String errorMessage;
      if (e is FirebaseException) {
        errorMessage = e.message ?? "Firebase上传失败";
      } else {
        errorMessage = "未知错误:${e.toString()}";
      }

      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(errorMessage),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 2),
        ),
      );
    }
  },
  backgroundColor: Colors.blueGrey,
  child: const Icon(Icons.save),
),

关键改动说明

  • 加载进度显示:点击按钮后立刻弹出环形加载弹窗,设置barrierDismissible: false避免用户误触关闭,上传完成或出错后再关闭弹窗。
  • 错误处理:用try-catch包裹Firebase操作,优先捕获FirebaseException(可获取平台返回的具体错误信息),再兜底处理其他未知异常,通过SnackBar展示清晰的错误提示。
  • 代码规范:将newHome改为局部变量并添加final修饰符,符合Dart最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:10:44