【问题标题】:flutter - errors event.snapshot.value since updating to firebase 9.0.X颤振 - 错误 event.snapshot.value 自更新到 firebase 9.0.X
【发布时间】:2022-05-04 09:24:12
【问题描述】:

自从更新到 firebase 9.0.5 后,我在 event.snapshot.value 上遇到了错误。 我有很多这样的功能,在 firebase 8.X 中运行良好。

  Stream<List<MentorModel>> mentorStream() {
    final stream = _database.onValue;

    final Stream<List<MentorModel>> resultStream = stream.map((event) {
      List<MentorModel> _mentorList = [];
      Map<String, dynamic>.from(event.snapshot.value).forEach((key, value) => _mentorList.add(MentorModel.fromRTDB(key, value)));
      return _mentorList;
    });

    return resultStream;
  }

现在我在event.snapshot.value 上有错误标记,android studio 说

Error: The argument type 'Object?' can't be assigned to the parameter type 'Map<dynamic, dynamic>'.
 - 'Object' is from 'dart:core'.
 - 'Map' is from 'dart:core'.
      Map<String, dynamic>.from(event.snapshot.value).forEach((key, value) => _mentorList.add(MentorModel.fromRTDB(key, value)));

当我尝试时

Map<String, dynamic>.from(event.snapshot.value as Map<String, dynamic>).forEach((key, value) => 

然后错误标记消失了,但是当我运行应用程序时它返回

E/flutter (16737): [ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>' in type cast, stack trace: 

firebase 9.0 到底发生了什么变化?如何在 firebase 9.0 中遍历 event.snapshot.value?

【问题讨论】:

  • Firebase v9 正常运行,v8 和下面是 OOP。

标签: firebase flutter firebase-realtime-database


【解决方案1】:

从 Firebase v9 开始,他们从使用 dynamic 转移到 Object?,开始将 Object? 转换为 Map 可能会很麻烦,正如您所经历的那样。只需将对象 dynamic消除麻烦。

试试:

Map<String, dynamic>.from(event.snapshot.value as dynamic).forEach((key, value) => _mentorList.add(MentorModel.fromRTDB(key, value)));

【讨论】:

  • 有效!而且我不知道它为什么会起作用。你能再解释一下吗?
  • 从 Firebase v9 开始,从使用 dynamic 转移到 Object?,开始将 Object? 转换为 Map 可能会很麻烦,就像您所经历的那样......只需制作对象dynamic 将消除麻烦。
  • event.snapshot.value as dynamic 有效,但 snapshot.value as dynamic 无效。代码如下所示:FirebaseDatabase.instance.ref().child('/users/$userID').get().then((snapshot) { return UserProfileModel.fromRTDB(userID, snapshot.value as dynamic); 有什么想法吗?
  • 没关系。已解决Map&lt;String, dynamic&gt;.from(snapshot.value as dynamic)
  • 完整代码发布@Misho
【解决方案2】:

statut: json['statut'] != null ? (json['statut'] as List).map((i) => Statut.fromJson(Map.from(i as dynamic))).toList() : null,

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 2020-08-23
    • 2021-08-21
    • 1970-01-01
    • 2021-07-04
    • 2021-06-11
    • 2020-11-14
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多