无法将 _InternalLinkedHashMap<Object?, Object?> 转换为任何内容

Nan*_*ame 3 dart firebase-realtime-database flutter

尽管我首先将其作为地图上传,但从 Firebase RealtimeDatabase 获取数据作为地图时遇到了一些问题。我看到的所有解决方案都是您应该将 snapshot.value 转换为传入的数据类型,但对我来说没有任何迭代。我已经能够调用toString()快照值,并且已经验证它是一个 Map,但编译器甚至不允许我将其转换为 Map,更不用说运行它了。如果我尝试使用动态来防止编译错误,我仍然会得到这个 Unhandled Exception: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>?' in type cast

这就是我所做的,

  Future<Map<String, dynamic>> getBasicDetail(
      DatabaseReference databaseReference) async {
    DatabaseReference imageURLevent = databaseReference.child('basicDetail');

    final snapShot = await imageURLevent.get();
    return Map<String, dynamic>.from(
        snapShot.value as Map<String, dynamic>? ?? {});
  }

  Future<void> readProfileData({required String userId}) async {

    DatabaseReference ref = FirebaseDatabase.instance.ref("users/$userId");

    final basicDetail = await getBasicDetail(ref);
    
    // Print the data of the snapshot
    debugPrint(basicDetail.toString());
  }
Run Code Online (Sandbox Code Playgroud)

我已经尝试了解析这些数据的所有可能的组合,但没有任何效果。由于某些原因,在示例和视频中,当您将右侧投射到右侧时,Map<String,dynamic>不会出现错误,但我的 IDE 甚至不允许我这样做。我也尝试过 Map.from() 似乎是一种流行的方法,但我的简单方法会引发运行时错误。

为什么会这样火播来自https://www.youtube.com/watch?v=sXBJZD0fBa4&ab_channel=Firebase

我的同时工作

代码没有吗?

event.snapshot.value 看起来也有效

[log] {bloodGroup: gh, imageURL: /data/user/0/com.piyushlimited.buzzai/app_flutter/image_picker7287835118545461685.jpg, fullName: Henry Nana Adu, weight: 523, dateOfBirth: 11/11/11, licenseNumber: 256489, age: 28}
Run Code Online (Sandbox Code Playgroud)

我可以通过引用数据的完整路径来访问数据的一个值,但我有一张大地图,我无法对每个类别中的每个值执行此操作。看起来既费钱又浪费时间。我花了几天时间尝试了很多事情,所以请记住这一点。

Nan*_*ame 12

谢谢你们的回复。特别感谢@Stelios Papamichail 3 个月前提供的解决方案。Firebase 的响应似乎不是有效的 JSON 格式,遗憾的是官方开发团队没有注意到这一点。jsonDecode(jsonEncode(event.snapshot.value)));工作完美。这可能是性能不佳的原因,但我现在并不关心这一点,我只是很高兴它确实如此。我也不知道为什么它有效。

现在效果很好

  Future<void> readProfileData({required String userId}) async {
    DatabaseReference ref = FirebaseDatabase.instance.ref("users/$userId");

    try {
      final DataSnapshot? snapShot = await ref.get();

      Map<String, dynamic> data = jsonDecode(jsonEncode(snapShot?.value));

      userProfile = UserProfile.fromMap(data);

      setGender(userProfile.gender);

      notifyListeners();

      log(userProfile.toString());
    } on Exception catch (e) {
      log(e.toString());
    }
  }
Run Code Online (Sandbox Code Playgroud)

希望更多的人看到这一点,不要像我一样浪费生命。