0
votes

I've read and tried every post/vid but nothing is working. Please help a network admin interested in code.

I can't figure out how I get the json object that is returned, to a usable list/string that I can use. I just need Elements -> Distance -> Text & value to a Text widget.

The JSON object that is returned

{
   "destination_addresses" : [ "The destination address" ],
   "origin_addresses" : [ "The origin address" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "7 m",
                  "value" : 7
               },
               "duration" : {
                  "text" : "1 min.",
                  "value" : 1
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Code snippet (deleted previous tries):

Future<String> getLinkForCalculation() async{
    var _latUser = "INSERT LATUSER";
    var _lonUser = "INSERT LONUSER";
    var _latClient = "INSERT LATCLIENT";
    var _lonClient = "INSERT LONCLIENT";
    var _key = "INSERT_API_KEY";
    var link = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=$_latUser,$_lonUser&destinations=$_latClient,$_lonClient&key=$_key";
    print(link);
    return link;
  }


  Future<List> calculateDistanceFromLink()async{
    var link = await getLinkForCalculation();
    Dio finalLink = new Dio();
    Response distanceData = await finalLink.get(link);

    print(distanceData.data);

  }

I have read and tried:

2

2 Answers

0
votes

I am not a Flutter developer so I cannot help you with the Text widget part. But I have made this example of how you can get the value from your JSON:

import 'dart:convert';

class Element {
  final String text;
  final int value;

  Element.fromJson(dynamic json)
      : text = json['text'] as String,
        value = json['value'] as int;

  @override
  String toString() => 'text: $text\nvalue: $value';
}

void main() {
  const jsonString = '''
  {
   "destination_addresses" : [ "The destination address" ],
   "origin_addresses" : [ "The origin address" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "7 m",
                  "value" : 7
               },
               "duration" : {
                  "text" : "1 min.",
                  "value" : 1
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
''';

  final dynamic jsonObj = json.decode(jsonString);

  final list = Element.fromJson(jsonObj['rows'][0]['elements'][0]['distance']);
  print(list);
}

As you can see, if the data type is dynamic, it is really easy to browse through the JSON to get specific data from it. The side effect of this is that type safety is gone from the analyzer so you should only use the power of dynamic in small isolated areas e.g. parsing and then return normal type safe objects and use them in the rest of you code.

0
votes

save the following code as MapResponse.dart then parse your response body to this model using

final mapResponse = mapResponseFromJson(jsonString);

//
//     final mapResponse = mapResponseFromJson(jsonString);

import 'dart:convert';

class MapResponse {
    final List<String> destinationAddresses;
    final List<String> originAddresses;
    final List<Row> rows;
    final String status;

    MapResponse({
        this.destinationAddresses,
        this.originAddresses,
        this.rows,
        this.status,
    });

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

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

    factory MapResponse.fromMap(Map<String, dynamic> json) => MapResponse(
        destinationAddresses: json["destination_addresses"] == null ? null : List<String>.from(json["destination_addresses"].map((x) => x)),
        originAddresses: json["origin_addresses"] == null ? null : List<String>.from(json["origin_addresses"].map((x) => x)),
        rows: json["rows"] == null ? null : List<Row>.from(json["rows"].map((x) => Row.fromMap(x))),
        status: json["status"] == null ? null : json["status"],
    );

    Map<String, dynamic> toMap() => {
        "destination_addresses": destinationAddresses == null ? null : List<dynamic>.from(destinationAddresses.map((x) => x)),
        "origin_addresses": originAddresses == null ? null : List<dynamic>.from(originAddresses.map((x) => x)),
        "rows": rows == null ? null : List<dynamic>.from(rows.map((x) => x.toMap())),
        "status": status == null ? null : status,
    };
}

class Row {
    final List<Location> elements;

    Row({
        this.elements,
    });

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

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

    factory Row.fromMap(Map<String, dynamic> json) => Row(
        elements: json["elements"] == null ? null : List<Location>.from(json["elements"].map((x) => Location.fromMap(x))),
    );

    Map<String, dynamic> toMap() => {
        "elements": elements == null ? null : List<dynamic>.from(elements.map((x) => x.toMap())),
    };
}

class Location {
    final Distance distance;
    final Distance duration;
    final String status;

    Location({
        this.distance,
        this.duration,
        this.status,
    });

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

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

    factory Location.fromMap(Map<String, dynamic> json) => Location(
        distance: json["distance"] == null ? null : Distance.fromMap(json["distance"]),
        duration: json["duration"] == null ? null : Distance.fromMap(json["duration"]),
        status: json["status"] == null ? null : json["status"],
    );

    Map<String, dynamic> toMap() => {
        "distance": distance == null ? null : distance.toMap(),
        "duration": duration == null ? null : duration.toMap(),
        "status": status == null ? null : status,
    };
}

class Distance {
    final String text;
    final int value;

    Distance({
        this.text,
        this.value,
    });

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

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

    factory Distance.fromMap(Map<String, dynamic> json) => Distance(
        text: json["text"] == null ? null : json["text"],
        value: json["value"] == null ? null : json["value"],
    );

    Map<String, dynamic> toMap() => {
        "text": text == null ? null : text,
        "value": value == null ? null : value,
    };
}