为什么我不能引用一个对象的另一个键中的一个键?

Why I can't refer to a key in an object's another key?

为什么我不能引用一个对象中已经放置在 另一个对象的键 中的键,同时映射如下:

var object = {
  "allStudents": [
    {
      "name": "John",
      "hobbies": {
        "sport": "Football",
        "music": "Piano"
      } ,
    },
    {
      "name": "Julyo",
      "hobbies": {
        "sport": "Vollyball",
        "music": "Guitar"
      } ,
    },
  ],
};

class Student {
  String name;
  dynamic hobbies;
  Student({this.name, this.hobbies});
}

class Hobbies {
  String sport;
  String music;
  Hobbies({this.sport, this.music});
}

List<Student> studentsList = [];

void getStudentsList () {
  studentsList = object["allStudents"].map((stu)=>
  Student(
    name: stu["name"] ,
    hobbies: Hobbies(
      sport: stu['hobbies']['sport'] ,
        music:stu['hobbies']['music'],
    ) ,
  )
  ).toList();
}

在我添加第二个运算符 ['sport']['music'][=22= 之前,一切都运行良好] 正如 IDE 一直告诉我的那样:

The operator '[]' is not defined for the class 'Object'. Try defining the operator '[]'.

见截图: can't refer to a key's value in another object's key

那是因为你的 var objectMap<String,Object> 类型,当你访问第一个 [] 时,你有 Object 作为a return,很快 Object 不是 map 或 iterable,第二个 [] 无法应用。您必须明确告诉您 objectMap<String, dynamic> 类型,如下例所示:

Map<String, dynamic> object = {
  "allStudents": [
    {
      "name": "John",
      "hobbies": {"sport": "Football", "music": "Piano"},
    },
    {
      "name": "Julyo",
      "hobbies": {"sport": "Vollyball", "music": "Guitar"},
    },
  ],
};

将您的解析代码更改为显式映射以与第二个 []:

一起使用
void getStudentsList() {
    final test = (object["allStudents"] as List)
        .map<Student>(
          (stu) => Student(
            name: stu["name"],
            hobbies: Hobbies(
              sport: stu['hobbies']['sport'],
              music: stu['hobbies']['music'],
            ),
          ),
        )
        .toList();

    print(test);
  }

现在可以了!

注意: 动态可以是所有可能的值类型,与 Object 类型不同,有关更多信息,请参阅讨论

Dart 不知道您的结构是什么样的,因此,您必须通过提供一个转换来让它知道。

void getStudentsList () {
  studentsList = (object["allStudents"] as List<Map<String,dynamic>>)
      .map((stu)=>
  Student(
    name: stu["name"] ,
    hobbies: Hobbies(
      sport: stu['hobbies']['sport'] ,
        music:stu['hobbies']['music'],
    ) ,
  )
  ).toList();
}

我在这个 dartPad 草稿上试过了,这很有效.. https://dartpad.dev/b338f2a46bcb361de5e05c5ea6b8c74f