0

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}]

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • What's the point of decoding the encoded body? Isn#t the body already json encoded? Please see [the flutter documentation](https://flutter.dev/docs/cookbook/networking/fetch-data) on how to do this. – nvoigt Aug 12 '21 at 14:45
  • I don't know the point of decoding and encoding the body but when I try to post in anther method is not working only with this way that's why I try to do it another time – youssef11511 Aug 12 '21 at 14:49

2 Answers2

2

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

esentis
  • 4,190
  • 2
  • 12
  • 28
1

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)
mutantkeyboard
  • 1,614
  • 1
  • 16
  • 44
  • in the `Year.formJson(Mapjson)` I get this error under the `Year` `Non-nullable instance field 'year' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.` – youssef11511 Aug 12 '21 at 15:03
  • and I have to make the `constructor` like this `Year({required this.year});` – youssef11511 Aug 12 '21 at 15:04