How can I access this JSON response that I am getting from an HTTP POST request in Flutter?

Viewed 36

I have a log in page and I make an HTTP POST request to post the data of the user in the API and I get back a response which I want to access and save into my app. Here is my code:

Here is the JSON response:


{
    "code": 200,
    "status": "succes",
    "message": "You are now logged in",
    "name": "Robert Doctor",
    "phone": "0756374360",
    "role": "doctor",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI",
    "connCode": 233121
}

1 Answers

They are a few ways, and you might want to look at others if you have lots of these to do, but a simple manual way is:

import 'dart:convert';

// response being the response object you got back from your http call
var payload = MyResponse.fromJson(json.decode(response.body))

class MyResponse {
  final String message;
  final String name;
  final String phone;
  // etc ....

  MyResponse(this.message, this.name, this.phone);

  MyResponse.fromJson(Map<String, dynamic> json)
      : message = json['message'],
        name = json['name'],
        phone = json['phone'];
}
Related