I have the following Flutter code:
class Facility{
Facility({
required this.name,
required this.rooms
});
final String name;
final List<Map<String, dynamic>> rooms;
Map<String, dynamic> toFirestore() {
return {
'name': name,
'rooms': rooms,
};
}
factory Facility.fromDummy(Map<String, dynamic> data) {
return facilityModelFactory(data);
}
factory Facility.fromFirestore(
DocumentSnapshot<Map<String, dynamic>> snapshot,
SnapshotOptions? options,
) {
// get data from snapshot
final data = snapshot.data()!;
// make client instance
Facility facility = facilityModelFactory(data);
return facility;
}
}
Facility facilityModelFactory(Map<String, dynamic> data) {
return Facility(
name: data['name'],
rooms: data['rooms'] << -------------- ERROR
);
}
The problem is the line flagged with "Error" is rising the following error:
E/flutter ( 4179): [ERROR:flutter/runtime/dart_vm_initializer(40)] Unhandled Exception: type 'List' is not a subtype of type 'List<Map<String, dynamic>>'
How can I declare a Map with a key that is Dynamic
type, like rooms in the example, and assign a value as I'm attempting in method facilityModelFactory()
?
I have the following Flutter code:
class Facility{
Facility({
required this.name,
required this.rooms
});
final String name;
final List<Map<String, dynamic>> rooms;
Map<String, dynamic> toFirestore() {
return {
'name': name,
'rooms': rooms,
};
}
factory Facility.fromDummy(Map<String, dynamic> data) {
return facilityModelFactory(data);
}
factory Facility.fromFirestore(
DocumentSnapshot<Map<String, dynamic>> snapshot,
SnapshotOptions? options,
) {
// get data from snapshot
final data = snapshot.data()!;
// make client instance
Facility facility = facilityModelFactory(data);
return facility;
}
}
Facility facilityModelFactory(Map<String, dynamic> data) {
return Facility(
name: data['name'],
rooms: data['rooms'] << -------------- ERROR
);
}
The problem is the line flagged with "Error" is rising the following error:
E/flutter ( 4179): [ERROR:flutter/runtime/dart_vm_initializer(40)] Unhandled Exception: type 'List' is not a subtype of type 'List<Map<String, dynamic>>'
How can I declare a Map with a key that is Dynamic
type, like rooms in the example, and assign a value as I'm attempting in method facilityModelFactory()
?
1 Answer
Reset to default 0Try this:
Facility facilityModelFactory(Map<String, dynamic> data) {
List<Map<String, dynamic>> rooms = List.from(data['rooms']);
return Facility(name: data['name'], rooms: rooms);
}
List<Map<String, dynamic>> rooms
should really beList<Room>
, and create a data class to hold Room. – Randal Schwartz Commented Feb 15 at 19:30