【问题标题】:Flutter get Object property NameFlutter 获取 Object 属性名称
【发布时间】:2018-09-26 22:36:12
【问题描述】:

我传递了以下对象:

var myVar = { typeA: { option1: "one", option2: "two" } }

我希望能够从上面的结构中取出key typeA。

这个值每次都可以改变,所以下次可能是typeB。

所以我想知道有没有办法做到这一点

【问题讨论】:

  • 您想要的结果到底是什么?是{ option 1: "one", option2: "two" }吗?你试过什么?有什么问题?
  • 我想要对象名称``` { typeA: { option1: "one", option2: "two" } , typeB: { option1: "one", option2: "two" } ,typeC: { option1: "one", option2: "two" } } ``` 我想要 TypeA 和 TypeB 等等
  • 抱歉,还是不知道这个问题是关于什么的。
  • api.github.com/users/nitishk72/gists 我想从此 URL 获取文件名。此返回文件名是 JSON 对象键。怎么办?
  • json[0]['files']['Sum_pointer_object.cpp']['filename']

标签: json object dart flutter


【解决方案1】:

要获取您可以使用的所有文件名:

var data = ...
 
var filenames = [];
for(var i = 0; i < data.length; i++) {
  var item = data[0]['files'];
  var key = item.keys.first;
  var filename = item[key]['filename'];
  filenames.add(filename);
}

print(filenames);

【讨论】:

  • 我和 Dart 合作很久了。我对 Flutter 还是比较陌生。
【解决方案2】:

我能够使用'keys'解决

对于这样的 json 示例:

{
"1-0001": {
  "name": "red",
  "hex": "FF0000"
 },
"1-0002": {
  "name": "blue",
  "hex": "0000FF"
 },
"1-0003": {
  "name": "green",
  "hex": "008000"
 }
}

我可以使用

Map<String, dynamic> decoded = json.decode(jsonString);
for (var colour in decoded.keys) {
  print(colour);                   // prints 1-0001
  print(decoded[colour]['name']);  // prints red
  print(decoded[colour]['hex']);   // prints FF0000
}

【讨论】:

  • 不能将参数类型'Map>'分配给参数类型'String'
【解决方案3】:

您需要定义数据类型。 它基本上是(键值对)的映射,其中键已更改,如问题 typeA 或 typeB 中所述 这个对象有 2 个属性 option1 和 option2 也是字符串。

这是构建模型的示例代码以及如何使用它

import 'package:TestDart/TestDart.dart' as TestDart;

main(List<String> arguments) {
  var  map = new Map<String, MyObject>();
  map['typeA'] = new MyObject("one", "two");
  map['typeB'] = new MyObject("one", "two");

  print(map['typeA'].toString());
  print(map['typeA'].toString());
}

class MyObject {
  String _option1;
  String _option2;

  MyObject(this._option1, this._option2);

  String get option2 => _option2;

  String get option1 => _option1;

  @override
  String toString() {
    return 'MyObject{option1: $_option1, option2: $_option2}';
  }


}

相关答案

 map.forEach((key, value) {
    print("Key : ${key} value ${value}");
  });

【讨论】:

  • 其实我想要的是键名。我得到了正确的解决方案,但也感谢您的尝试
  • 我已经更新了我的答案,使其更准确,并在问题的上下文中查看
  • 我会试一试,如果有效我一定会接受。
猜你喜欢
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多