flutterdarthttp-posthttp-get

How I can get specific value from HTTP method in FLUTTER?


My output is like this:

{
"scope": [],
"_id": "62413827f85e740dd8af749d",
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOnsidXNlcklkIjoiNjI0MTM4MjdmODVlNzQwZGQ4YWY3NDlhIn0sImlhdCI6MTY0ODQ0MTM4M30.cNE32yojMlbohsOtgB2docCsZk8UPqEbPVTizV--rMs",
"user": {
    "_id": "62413827f85e740dd8af749a",
    "email": "ahmed@gmail.com",
    "password": "hello",
    "phone": "01723456789",
    "createdAt": "2022-03-28T04:23:03.334Z",
    "updatedAt": "2022-03-28T04:23:03.334Z",
    "__v": 0
},
"createdAt": "2022-03-28T04:23:03.348Z",
"updatedAt": "2022-03-28T04:23:03.348Z",
"__v": 0
}

How can I get the value of "email" from "user" in flutter? I am using the following code.

http
      .post(Uri.parse(url),
          headers: {"Content-type": "application/json;charset=UTF-8"},
          body: jsonEncode(model))
      .then((value) {
    var access = jsonDecode(value.body);

Solution

  • first you should use model . without using model it will help you

    it's only a example how to get value from map

    var apiResp = jsonDecode('''
        {
        "scope": [],
        "_id": "62413827f85e740dd8af749d",
        "access_token":
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOnsidXNlcklkIjoiNjI0MTM4MjdmODVlNzQwZGQ4YWY3NDlhIn0sImlhdCI6MTY0ODQ0MTM4M30.cNE32yojMlbohsOtgB2docCsZk8UPqEbPVTizV--rMs",
        "user": {
          "_id": "62413827f85e740dd8af749a",
          "email": "ahmed@gmail.com",
          "password": "hello",
          "phone": "01723456789",
          "createdAt": "2022-03-28T04:23:03.334Z",
          "updatedAt": "2022-03-28T04:23:03.334Z",
          "__v": 0
        },
        "createdAt": "2022-03-28T04:23:03.348Z",
        "updatedAt": "2022-03-28T04:23:03.348Z",
        "__v": 0
      }
      ''');
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('${apiResp['user']['email']}')),
    
    

    here jsonDecode accept string value so i did this way

    '''
        {
        "scope": [],
        "_id": "62413827f85e740dd8af749d",
        "access_token":
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOnsidXNlcklkIjoiNjI0MTM4MjdmODVlNzQwZGQ4YWY3NDlhIn0sImlhdCI6MTY0ODQ0MTM4M30.cNE32yojMlbohsOtgB2docCsZk8UPqEbPVTizV--rMs",
        "user": {
          "_id": "62413827f85e740dd8af749a",
          "email": "ahmed@gmail.com",
          "password": "hello",
          "phone": "01723456789",
          "createdAt": "2022-03-28T04:23:03.334Z",
          "updatedAt": "2022-03-28T04:23:03.334Z",
          "__v": 0
        },
        "createdAt": "2022-03-28T04:23:03.348Z",
        "updatedAt": "2022-03-28T04:23:03.348Z",
        "__v": 0
      }
      '''