未经处理的异常:"列表"类型<dynamic>不是类型"列表<字符串?>"的子类型



当我从FireStore获取数组数据时,我得到了一个错误。我添加了"blockUid"字段。但是它不工作,尽管其他的都在工作。

github: https://github.com/ATUSHIKADOWAKI/dance_4_life/tree/main/lib

(main_model.dart)
Future<void> fetchEvents() async {
final docs = await FirebaseFirestore.instance
.collection('event')
.orderBy('timestamp', descending: true)
.get();
final events = docs.docs.map((doc) => Events(doc)).toList();
this.events = events;
notifyListeners();
}

(events.dart)
class Events {
String? eventId;
String? title;
String? date;
String? imgURL;
String? detail;
//array is here.
List<String?> blockUid = [];
String? eventPlace;
String? eventAddress;
String? eventCategory;
String? eventPrice;
String? eventGenre;
Events(DocumentSnapshot doc) {
eventId = doc.id;
title = doc['title'];
eventPlace = doc['eventPlace'];
eventAddress = doc['eventAddress'];
eventCategory = doc['eventCategory'];
eventPrice = doc['eventPrice'];
eventGenre = doc['eventGenre'];
date = doc['date'];
imgURL = doc['imgURL'];
detail = doc['detail'];
blockUid = doc['blockUid'];
}
}

你需要改变这一行

blockUid = doc['blockUid'];

blockUid = doc['blockUid'] as List<String>;

请替换

blockUid = doc['blockUid'];

blockUid = List<String>.from(doc["data"].map((x) => x) ?? [])

确保Firestore中blockUid列表中的所有数据都是String,并尝试以下操作:

Future<void> fetchEvents() async {
final docs = await FirebaseFirestore.instance
.collection('event')
.orderBy('timestamp', descending: true)
.get();
final events = docs.docs.map((doc) => Events.fromDoc(doc)).toList();
this.events = events;
notifyListeners();
}
class Events {
Events({
this.eventId,
this.title,
this.date,
this.imgURL,
this.detail,
this.blockUid,
this.eventPlace,
this.eventAddress,
this.eventCategory,
this.eventPrice,
this.eventGenre,
});
String? eventId;
String? title;
String? date;
String? imgURL;
String? detail;
//array is here.
List<String>? blockUid;
String? eventPlace;
String? eventAddress;
String? eventCategory;
String? eventPrice;
String? eventGenre;
factory Events.fromDoc(DocumentSnapshot doc) => Events(
eventId: doc.id,
title: doc['title'],
eventPlace: doc['eventPlace'],
eventAddress: doc['eventAddress'],
eventCategory: doc['eventCategory'],
eventPrice: doc['eventPrice'],
eventGenre: doc['eventGenre'],
date: doc['date'],
imgURL: doc['imgURL'],
detail: doc['detail'],
blockUid: doc['blockUid'],
);
}

你只需要替换这个List<dynamic> blockUid = [];

将单个条目强制转换为String,如下所示:

Events(DocumentSnapshot doc) {
eventId = doc.id;
title = doc['title'];
...
blockUid = doc['blockUid'].map((item) => item as String).toList()
}

相关内容

最新更新