使用 Flutter Riverpod 的 StreamProvider 从 Firestore 中获取特定文档

Using Flutter Riverpod's StreamProvider to fetch a specific document from Firestore

我正在使用 Riverpod 的 StreamProvider 从 Firestore 中获取一个包含数组的字段,然后将其映射到 class,如下所示。

final firebaseFollowingProvider = StreamProvider<List<Following>>((ref) {
  final stream = FirebaseFirestore.instance.collection('following').doc('d48391af-380d-4377-a3f9-d38cf5af7923').snapshots();
  return stream.map((snapshot) => snapshot.data()!.map((doc) => Following.fromDocument(doc)).toList());
});

我的模型是这样的

class Following {
  dynamic following;

  Following({this.following});

  Following.fromJson(Map<String, dynamic> json)
      : following = json['isFollowing'];

  Map<String, dynamic> toJson() => {
        'isFollowing': following,
      };

  factory Following.fromDocument(DocumentSnapshot doc) {
    return Following(following: doc['isFollowing']);
  }
}

我得到的错误是

The argument type 'MapEntry<_, > Function(String)' can't be assigned to the parameter type 'MapEntry<dynamic, dynamic> Function(String, dynamic)'. (Documentation) The return type 'Following' isn't a 'MapEntry<, _>', as required by the closure's context. (Documentation)

由于 snapshot.data() 已经 returns 一个 Map,如何将从 StreamProvider 返回的数据映射到 class?

我正在使用cloud_firestore: ^2.3.0

非常感谢。

Structure of the Database

不要在模型 class 中将变量定义为 dynamic。模型 classes 旨在为您提供类型安全,并且 dynamic 变量避开类型系统。

这样会更好(没测试过):

class Following {
  final String following;

  Following({required this.following});

  Following.fromJson(Map<String, dynamic> json)
      : following = json['isFollowing'] as String;

  Map<String, dynamic> toJson() => {
        'isFollowing': following,
      };

  factory Following.fromDocument(DocumentSnapshot doc) {
    return Following(following: doc['isFollowing'] as String);
  }
}

问题是我返回的是以下类型的列表,即 <List<Following>> 而不是返回 Following

final firebaseFollowingProvider = StreamProvider.autoDispose<Following>((ref) {
  final stream = followingRef.doc('d48391af-380d-4377-a3f9-d38cf5af7923').snapshots();
  return stream.map((snapshot) => Following.fromDocument(snapshot));
});