从 api 中获取时在地图中使用 Flutter Map

Flutter Map inside a Map when fetching from api

我正在从 api 获取数据,但现在我正在使用其他 api,它在地图中有一个地图 我在访问时遇到问题,这是数据的处理方式看起来。

{
  "status": "string",
  "name": {
    "location": "string",
    "startTime": "2022-01-31T08:13:21.027Z",
    "endTime": "2022-01-31T08:13:21.027Z",
    "duration": "string"
  }
}

我正在尝试访问位置。

class WorkingLocationStatus {
  final String status;

  //final String location;

  WorkingLocationStatus({
    required this.status,
    // required this.location
  });

  factory WorkingLocationStatus.fromJson(Map<String, dynamic> json) {
    return WorkingLocationStatus(
      status: json['status'],
      //location: json['location']
    );
  }
}

body: FutureBuilder<Response>(
        future: futureDataForStatus,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            WorkingLocationStatus data4 = WorkingLocationStatus.fromJson(
              json.decode(snapshot.data!.body),
            );
            return Center(
              child: Text(data4.status),
            );
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }
          return const Center(child: CircularProgressIndicator());
        },
      ),

您可以使用 json to dart 工具从原始 json 制作模型 class。

这是完整的代码。

// To parse this JSON data, do
//
//     final workingLocationStatus = workingLocationStatusFromMap(jsonString);

import 'dart:convert';

class WorkingLocationStatus {
    WorkingLocationStatus({
        this.status,
        this.name,
    });

    final String status;
    final Name name;

    factory WorkingLocationStatus.fromJson(String str) => WorkingLocationStatus.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory WorkingLocationStatus.fromMap(Map<String, dynamic> json) => WorkingLocationStatus(
        status: json["status"],
        name: Name.fromMap(json["name"]),
    );

    Map<String, dynamic> toMap() => {
        "status": status,
        "name": name.toMap(),
    };
}

class Name {
    Name({
        this.location,
        this.startTime,
        this.endTime,
        this.duration,
    });

    final String location;
    final DateTime startTime;
    final DateTime endTime;
    final String duration;

    factory Name.fromJson(String str) => Name.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Name.fromMap(Map<String, dynamic> json) => Name(
        location: json["location"],
        startTime: DateTime.parse(json["startTime"]),
        endTime: DateTime.parse(json["endTime"]),
        duration: json["duration"],
    );

    Map<String, dynamic> toMap() => {
        "location": location,
        "startTime": startTime.toIso8601String(),
        "endTime": endTime.toIso8601String(),
        "duration": duration,
    };
}


body: FutureBuilder<Response>(
        future: futureDataForStatus,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            WorkingLocationStatus data4 = WorkingLocationStatus.fromJson(
              json.decode(snapshot.data!.body),
            );
            return Center(
              child: Text(data4.name.location),
            );
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }
          return const Center(child: CircularProgressIndicator());
        },
      ),


要访问 "location" 属性 您首先需要从字段 "name":

访问它
class WorkingLocationStatus {
  final String status;
  final String location;

  WorkingLocationStatus({
    required this.status,
    required this.location
  });

  factory WorkingLocationStatus.fromJson(Map<String, dynamic> json) {
    return WorkingLocationStatus(
      status: json['status'] as String,
      location: json['name']['location'] as String,
    );
  }
}

Try the full code example on DartPad

您将遵循这个基本步骤以您的方式实施

import 'dart:convert';

var jsonObj = """{
     "status": "string",
     "name": {
     "location": "string",
     "startTime": "2022-01-31T08:13:21.027Z",
     "endTime": "2022-01-31T08:13:21.027Z",
     "duration": "string"
     }
   }""";

    void main(){
    var resultBody = jsonDecode(jsonObj);

     print("Here is your location: " + resultBody["name"]["location"]);
  }

**你的结果是这样的**

这是您的位置:字符串