如何使用 flutter 数据建模技术访问“HH”和“mm”。我一直在尝试按以下方式使用它,但是下面给出了错误。
我的数据模型当前为它的简化版本。
class Week {
final String label;
final String value;
Week({@required this.label, @required this.value});
factory Week.fromJson(Map<String, dynamic> doc) {
return Week(
label: doc['label'] ?? '',
value: doc['value'] ?? 0,
);
}
}
class IntervalTime {
final String hh;
final String mm;
IntervalTime({@required this.hh, @required this.mm});
factory IntervalTime.fromJson(Map<String, dynamic> doc) {
return IntervalTime(
hh: doc['HH'] ?? '',
mm: doc['mm'] ?? '',
);
}
}
class Diary {
final String message;
final List<Week> weeklyFreq;
final Timestamp annualFreq;
final IntervalTime start;
Diary(
{@required this.message,
@required this.weeklyFreq,
@required this.annualFreq,
@required this.start});
factory Diary.fromFirestore(DocumentSnapshot doc) {
Map data = doc.data;
return Diary(
message: data['message'] ?? '',
weeklyFreq: data['weeklyFreq'].cast<List<Week>>() ?? [],
annualFreq: data['annualFreq'] ?? Timestamp,
start: data['start'].cast<IntervalTime>() ?? '',
);
}
}
和日志记录在下面。 [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'CastList<dynamic, List<Week>>' is not a subtype of type 'List<Week>'
最佳答案
解决方法在下面。最重要的是在数据声明中再次转换json数据。同样,序列化数据对象内部的数据也是一种困惑,因为有足够的资源将对象映射到对象内部。
class Week {
final String label;
final int value;
Week({@required this.label, @required this.value});
factory Week.fromJson(Map<String, dynamic> data) {
// Map<String, dynamic> data = json.decode(doc);
return Week(
label: data['label'] ?? '',
value: data['value'] ?? 0,
);
}
}
class IntervalTime {
final String hh;
final String mm;
IntervalTime({@required this.hh, @required this.mm});
factory IntervalTime.fromJson(Map data) {
return IntervalTime(
hh: data['HH'] ?? '',
mm: data['mm'] ?? '',
);
}
}
class Diary {
final String message;
final List<Week> weeklyFreq;
final Timestamp annualFreq;
final IntervalTime start;
Diary(
{@required this.message,
@required this.weeklyFreq,
@required this.annualFreq,
@required this.start});
factory Diary.fromFirestore(DocumentSnapshot doc) {
Map data = doc.data;
return Diary(
message: data['message'] ?? '',
weeklyFreq: (data['weeklyFreq'] as List)
?.map((e) => e == null ? null : Week.fromJson(e))
?.toList(), // Workaround
annualFreq: data['annualFreq'] ?? Timestamp,
start: IntervalTime.fromJson(data['start']), // workaround
);
}
}
关于json - 如何在Fluter上从Firestore中的模型json数据内部序列化/建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63645108/