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

Firebase Storage报错[firebase_storage/object-not-found]:指定引用无对象存在

解决Firebase Storage切换账号时头像不存在导致的崩溃问题

问题核心:切换到未上传过头像的账号时,initState里调用的getUrl()方法直接尝试获取不存在的文件下载链接,触发firebase_storage/object-not-found异常且未捕获,导致应用崩溃。

解决方案:添加异常捕获+安全空处理

修改getUrl()方法,捕获Storage异常,同时对用户ID做空安全校验;另外优化文件上传前的空判断,避免late变量未初始化报错。

修改后的完整代码:

late File uploadFile;
FirebaseAuth auth = FirebaseAuth.instance;
String? downloadUrl;

@override
void initState() {
  WidgetsBinding.instance.addPostFrameCallback((_) => getUrl());
  super.initState();
}

void getUrl() async {
  final userId = auth.currentUser?.uid;
  if (userId == null) return; // 用户未登录时直接返回

  try {
    String con = await FirebaseStorage.instance
        .ref()
        .child("profilePics")
        .child(userId)
        .child("profilePic.png")
        .getDownloadURL();

    setState(() {
      downloadUrl = con;
    });
  } on FirebaseException catch (e) {
    // 捕获Storage相关异常
    if (e.code == 'object-not-found') {
      // 文件不存在,保持downloadUrl为null,显示默认头像
      setState(() {
        downloadUrl = null;
      });
    } else {
      // 处理其他异常,比如权限问题等
      print("获取头像链接失败: ${e.message}");
    }
  } catch (e) {
    // 捕获其他未知异常
    print("未知错误: $e");
  }
}

void gallery() async {
  var getDoc = await ImagePicker().pickImage(source: ImageSource.gallery);
  if (getDoc == null) return; // 用户取消选择时直接返回

  setState(() {
    uploadFile = File(getDoc.path);
  });

  final userId = auth.currentUser?.uid;
  if (userId == null) return;

  final ref = FirebaseStorage.instance
      .ref()
      .child("profilePics")
      .child(userId)
      .child("profilePic.png");

  UploadTask uploadTask = ref.putFile(uploadFile);
  String url = await (await uploadTask).ref.getDownloadURL();
  
  setState(() {
    downloadUrl = url;
  });
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: Column(
        children: [
          ElevatedButton(
            onPressed: () => FirebaseAuth.instance.signOut(),
            child: Text('Çıkış'),
          ),
          ElevatedButton(
            onPressed: gallery,
            child: Text('Upload'),
          ),
          downloadUrl != null ? Image.network(downloadUrl!) : CircleAvatar()
        ],
      ),
    ),
  );
}

关键修改点说明:

  • 在getUrl()中加入try-catch块,专门捕获FirebaseException,当遇到object-not-found错误时,主动将downloadUrl设为null,确保UI显示默认的CircleAvatar而不是崩溃。
  • 增加auth.currentUser?.uid的空判断,避免用户未登录时出现空指针异常。
  • 在gallery()中先判断getDoc是否为null,防止用户取消图片选择后给late File uploadFile赋值null导致报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:12:34