简体   繁体   English

在 dart 中动态定义或转换变量类型

[英]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 课程: WorkoutDaysYears

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?但我不知道如何从WorkoutDaysYears 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.

相关问题 如何在Dart 2中为我的用例键入强制类型转换 - How to type cast for my use case in Dart 2 “bool”类型不是“List”类型的子类型<string> ' 在类型转换中 - flutter/dart</string> - type 'bool' is not a subtype of type 'List<String>' in type cast - flutter/dart Flutter/Dart:类型“int”不是类型转换中“String”类型的子类型 - Flutter/Dart: Type 'int' is not a subtype of type 'String' in type cast Dart:是否可以将泛型类型作为变量传递给 class? - Dart: Is it possible to pass a generic type to a class as a variable? 如何比较 Dart 中“is”运算符中的类型变量 - How to compare the type variable in "is" operator in Dart Dart type_test_with_non_type 在变量中存储类型时 - Dart type_test_with_non_type when storing type in variable Dart,Flutter:异常:键入“列表”<dynamic> &#39; 不是类型 &#39;Map 的子类型<String, dynamic> &#39; 在类型转换中 - Dart,Flutter: Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast dart/flutter :: type 'Null' is not a subtype of type 'String' in type cast ERRor,无法获取数据 - dart/flutter:: type 'Null' is not a subtype of type 'String' in type cast ERRor, not able to fetch data Flutter/Dart 未处理异常:“String”类型不是“Map”类型的子类型<String, dynamic> &#39; 在类型转换中 - Flutter/Dart Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast 手势捕获的异常:类型“_RegExpMatch”不是 Flutter/Dart 中类型转换中类型“double”的子类型 - Exception caught by gesture: type '_RegExpMatch' is not a subtype of type 'double' in type cast in Flutter/Dart
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM