[英]Define or Cast variable type dynamically in dart
So I have this func:所以我有这个功能:
Future<void> syncedData(String dataType, Map<String, dynamic> data) async {
// Open the Hive Box
await _openBoxByName(dataType);
// Put each data element in the Hive Box
data.forEach((k, v) {
Workout _v = v;
// var _v = v as Workout; - kinda same result
_putData(k, _v.toJson().toString(), dataType);
});
}
I also have 3 Model Classes: Workout
, Days
and Years
.我还有 3 个 Model 课程: Workout
、 Days
和Years
。
In order for me to get .toJson()
method from v, I need to do: Workout _v = v;
为了让我从 v 中获取.toJson()
方法,我需要做: Workout _v = v;
. . But I do not know how can I cast the type of v
dynamically from Workout
, Days
and Years
Model Classes?但我不知道如何从Workout
、 Days
和Years
Model 类中动态转换v
的类型?
If I do not cast v
explicit as Workout Class Model, dart doesn`t know about any of my WOrkouts methods.如果我不将v
显式转换为锻炼 Class Model,dart 不知道我的任何锻炼方法。
I have tried something like this, but it did not work:我尝试过这样的事情,但没有奏效:
if (dataType == 'workout') Workout _v = v;
if (dataType == 'days') Days _v = v;
if (dataType == 'years') Years _v = v;
Thank you谢谢
You should probably encode this as a Map that has values for keys of workout, days, or years.您可能应该将其编码为 Map,其中包含锻炼、天或年的键值。 I think that'll JSON quite nicely.我认为 JSON 会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.