youssef11511
youssef11511

Reputation: 31

How to change to type of response to Map in flutter

I try to make a GET http call from flutter to Nodejs. The data I get is in json form but when I try to manipulate it with flutter I can't because the response is of type RESPONSE or I can change it to string I don't know how to change the response to type Map to help me manipulate the data I get.

here the code :

Future getYear() async {
    var url = "http://192.168.1.19:3000/getyear";
    var response = await http.get(Uri.parse(url));
    var jsonresponse = await json.decode(json.encode(response.body));
  }

and here the data I get but I can't manipulate it [{"year":2019},{"year":2020}]

Upvotes: 0

Views: 4376

Answers (2)

mutantkeyboard
mutantkeyboard

Reputation: 1714

You can create a class for it that would look like so:

class Year {
  int year;

  Year({this.year});

  Year.fromJson(Map<String, dynamic> json) {
    year = json['year'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['year'] = this.year;
    return data;
  }
}

Than you simply call

Year.fromJson(jsonresponse)

Upvotes: 1

esentis
esentis

Reputation: 4666

jsonDecode(response.body) decodes the response to Map<String,dynamic>.

Upvotes: 2

Related Questions