I am trying to retrieve data from a document in Firestore using a Widget. I used this in the past, I guess with a different version of Dart or flutter, and it worked. Now this is showing the following error when I use (doc.data())
The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic>'
Here's the code
DriverProvider driverProvider;
void getDriverInfo() {
Stream<DocumentSnapshot> driverStream =
driverProvider!.getbyIdStream(FirebaseAuth.instance.currentUser!.uid);
driverStream.listen((DocumentSnapshot doc) {
driver = Driver.fromJson(doc.data());
});
}
Here's where driverProvider! comes from
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);
}
}
and this is where getbyIdStream
comes from
Stream<DocumentSnapshot> getbyIdStream(String id) {
return _ref!.doc(id).snapshots(includeMetadataChanges: true);
}
This is my Json model
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,
};
}
and this is the line with the error
driver = Driver.fromJson(doc.data());
Thanks all for the help.
fromJson
method and show us the line where the error was given? – Benjamindriver
variable? And can you try printing outdoc.data()
and seeing what you get? – BenjaminContainer(child: Text(mapController.driver!.username,
I cannot really print the doc.data() because that is the error i need help with and the code editor won't let me compile. However, I do know it contains the fields inside the document – David Zapata