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

启用链接时Xamarin.Forms调用Firestore出现NullReferenceException无法获取Data

问题:启用链接时Firestore获取DocumentSnapshot的Data触发NullReferenceException

启用链接运行Android应用时,调用Firestore获取文档快照后出现异常:System.NullReferenceException: Object reference not set to an instance of an object.,具体表现:

  • 执行代码获取IDocumentSnapshot实例:
    IDocumentSnapshot myVariable = await CrossCloudFirestore.Current
                                                            .Instance
                                                            .Collection("myCollection")
                                                            .Document("myDocument")
                                                            .GetAsync();
    
  • myVariable.Exists值为true,但访问myVariable.Data时触发上述异常
  • 禁用链接后可正常获取Data

调试时myVariable的信息:

myVariable  {Plugin.CloudFirestore.DocumentSnapshotWrapper}
            Data       System.NullReferenceException: Object reference not set to an instance of an object.
            Exists     true
            Id         "myDocument"
            Reference  {Plugin.CloudFirestore.DocumentReferenceWrapper}

解决方案

  • 调整ProGuard配置:启用链接后ProGuard可能混淆了Firestore相关类,导致内部调用失败。在Android项目的proguard.cfg中添加规则:

    -keep class com.google.firebase.** { *; }
    -keep class com.google.android.gms.** { *; }
    -keep class Plugin.CloudFirestore.** { *; }
    
  • 升级插件版本:Plugin.CloudFirestore可能存在链接模式下的兼容性问题,升级到最新稳定版,同时确保和Xamarin.Forms、Firebase SDK版本匹配。

  • 改用实体类映射:避免直接访问Data属性,使用Get<T>()方法将文档数据映射到自定义实体类,示例:

    // 定义对应文档结构的实体类
    public class MyModel
    {
        public string Property1 { get; set; }
        public int Property2 { get; set; }
        // 其他对应字段
    }
    
    // 获取并映射数据
    var myModel = await CrossCloudFirestore.Current
                                            .Instance
                                            .Collection("myCollection")
                                            .Document("myDocument")
                                            .GetAsync()
                                            .ContinueWith(t => t.Result.Get<MyModel>());
    
  • 修改链接器行为:在Android项目属性的链接器行为选项中,选择「仅链接SDK程序集」,减少对第三方插件代码的混淆处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:20:09