我正在尝试使用 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/
相关文章:
windows - 将 Systems Internals 列为制造商的 Windows 服务的名称
javascript - 接收错误 : xhr poll error socket. io 客户端
c# - 为什么将 List 转换为 Array 而不是在 C# 中引用?
typescript - noFallthroughCasesInSwitch - 明确允许失败
reactjs - 错误 : Final loader (./node_modules/awesom
c++ - 当我们已经拥有更强大的 vector 时,为什么还需要堆栈?