我有和对象,我想知道是否有一种简单的方法来迭代键和值?
class Post {
String id;
String title;
String article;
Post(
{
this.id,
this.title,
this.article
}
);
}
Run Code Online (Sandbox Code Playgroud)
这几乎每天都困扰着我。这也是 Dart 的 web 端的一个问题。在我看来,这是 Dart 的主要缺点之一......
但是 - 这是我的解决方案。我正在为这些“可序列化”类使用接口类。
abstract class JsonTO {
Map<String, dynamic> toJson();
}
class Device implements JsonTO {
Map<String, dynamic> toJson() {
return ... Your serialization thing
}
}
main() {
final device = Device();
final json = device.toJson();
json.forEach((final String key, final value) {
_logger.info("Key: {{$key}} -> value: ${value}");
// do with this info whatever you want
});
}
Run Code Online (Sandbox Code Playgroud)
那没有。
您要的是反思。dart:mirrors如果库在您的平台上可用(它不在Flutter中),则可以使用该API。您可能可以使用为其生成代码package:reflectable。或者您可以用来从一个对象package:json_serializable生成一个Map。
如果您只是想为一个特定的类做某事,我只是手动编写:
dart
Map<String, dynamic> toJson() => {"id": id, "title": title, "article": article};
然后在您要迭代时使用它。
| 归档时间: |
|
| 查看次数: |
4238 次 |
| 最近记录: |