gpt4 book ai didi

firebase - Flutter 参数类型 'StreamTransformer' 无法赋值给参数类型 StreamTransformer>

转载 作者:行者123 更新时间:2023-12-05 01:06:55 25 4
gpt4 key购买 nike

我正在尝试使用 Flutter 和 Firebase 构建一个聊天应用程序,我从 Github 获取了以下代码并将其用于我的项目。在早期版本的 Flutter 上,它可以工作,在 2.0 上它显示以下错误:The argument type 'StreamTransformer<dynamic, dynamic>' can't be assigned to the parameter type 'StreamTransformer<QuerySnapshot, List<Message>>'

错误由以下行触发:

.transform(Utils.transformer(User.fromJson));

完整代码:

class FirebaseApi {
static Stream<List<User>> getUsers() => FirebaseFirestore.instance
.collection('users')
// .collection('ch ats')
.orderBy(UserField.timestamp, descending: true)
.snapshots()
.transform(Utils.transformer(User.fromJson));

static Future uploadMessage(String idUser, String message) async {
final refMessages =
FirebaseFirestore.instance.collection('chats/$idUser/messages');

final newMessage = Message(
// idUser: myId,
idUser: Globals.auth.currentUser!.uid,
// urlAvatar: myUrlAvatar,
urlAvatar: ChatPageState.photoUrl.toString(),
// username: myUsername,
username: ChatPageState.displayName.toString(),
message: message,
createdAt: DateTime.now(),
);
await refMessages.add(newMessage.toJson());

final refUsers = FirebaseFirestore.instance.collection('users');

await refUsers.doc(idUser).update({UserField.timestamp: DateTime.now()});
}

static Stream<List<Message>> getMessages(String idUser) {
return FirebaseFirestore.instance
.collection('chats/$idUser/messages')
.orderBy(MessageField.createdAt, descending: true)
.snapshots()
.transform(Utils.transformer(Message.fromJson));
}

}

class Utils {
static StreamTransformer transformer<T>(
T Function(Map<String, dynamic> json) fromJson) =>
StreamTransformer<QuerySnapshot, List<T>>.fromHandlers(
handleData: (QuerySnapshot data, EventSink<List<T>> sink) {
final snaps = data.docs.map((doc) => doc.data()).toList();
final users = snaps.map((json) => fromJson(json)).toList();

sink.add(users);
},
);

static DateTime toDateTime(Timestamp value) {
// if (value == null);

return value.toDate();
}

static dynamic fromDateTimeToJson(DateTime date) {
if (date == null) return null;

return date.toUtc();
}
}

最佳答案

添加 QuerySnapshot<Map<String, dynamic>>作为您的返回类型。为我工作。

static StreamTransformer<QuerySnapshot<Map<String, dynamic>>, List<T>> transformer<T>(
T Function(Map<String, dynamic> json) fromJson) =>
StreamTransformer<QuerySnapshot<Map<String, dynamic>>, List<T>>.fromHandlers(
handleData: (QuerySnapshot<Map<String, dynamic>> data, EventSink<List<T>> sink) {
final snaps = data.docs.map((doc) => doc.data()).toList();
final users = snaps.map((json) => fromJson(json)).toList();

sink.add(users);
},
);

关于firebase - Flutter 参数类型 'StreamTransformer<dynamic, dynamic>' 无法赋值给参数类型 StreamTransformer<QuerySnapshot List<Message>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68198697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com