gpt4 book ai didi

firebase - 参数类型 'Object?' 无法分配给参数类型 'Map'

转载 作者:行者123 更新时间:2023-12-05 08:16:49 25 4
gpt4 key购买 nike

我正在尝试使用 Widget 从 Firestore 中的文档检索数据。我过去用过这个,我猜是用不同版本的 Dart 或 flutter,它起作用了。现在当我使用 (doc.data()) 时显示以下错误参数类型“对象?”无法分配给参数类型“Map

这是代码

DriverProvider driverProvider;

void getDriverInfo() {
Stream<DocumentSnapshot> driverStream =
driverProvider!.getbyIdStream(FirebaseAuth.instance.currentUser!.uid);
driverStream.listen((DocumentSnapshot doc) {
driver = Driver.fromJson(doc.data());
});
}

这里是driverProvider所在的地方!来自

import 'package:brokerdrivers/models/user-models.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class DriverProvider {
CollectionReference? _ref;

DriverProvider() {
_ref = FirebaseFirestore.instance.collection('Drivers');
}

Future? create(Driver driver) {
String? errorMessage;

try {
return _ref!.doc(driver.id).set(driver.toJson());
} catch (e) {
print(e);
errorMessage = e.toString();
return Future.error(errorMessage);
}
}

Stream<DocumentSnapshot> getbyIdStream(String id) {
return _ref!.doc(id).snapshots(includeMetadataChanges: true);
}
}



这就是 getbyIdStream 的来源


Stream<DocumentSnapshot> getbyIdStream(String id) {
return _ref!.doc(id).snapshots(includeMetadataChanges: true);
}

这是我的 Json 模型

import 'dart:convert';

Driver driverFromJson(String str) => Driver.fromJson(json.decode(str));

String driverToJson(Driver data) => json.encode(data.toJson());

class Driver {
Driver({
required this.id,
required this.username,
required this.email,
required this.truck,
required this.carrier,
required this.insurance,
});

String id;
String username;
String email;
String truck;
String carrier;
String insurance;

factory Driver.fromJson(Map<String, dynamic> json) => Driver(
id: json["id"],
username: json["username"],
email: json["email"],
truck: json["truck"],
carrier: json["carrier"],
insurance: json["insurance"],
);

Map<String, dynamic> toJson() => {
"id": id,
"username": username,
"email": email,
"truck": truck,
"carrier": carrier,
"insurance": insurance,
};
}


这是错误的行

driver = Driver.fromJson(doc.data());

感谢大家的帮助。

最佳答案

此错误是 cloud_firestore API 的新更改导致的。您需要指定从 DocumentSnapshot

获取的数据类型

更新这一行:

    driver = Driver.fromJson(doc.data());

为此:

    driver = Driver.fromJson(doc.data() as Map<String, dynamic>);

查看 migration to cloud_firestore 2.0.0 的指南.

关于firebase - 参数类型 'Object?' 无法分配给参数类型 'Map<String, dynamic>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67757314/

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