rameez khan
rameez khan

Reputation: 359

Flutter print a specific value

I have a very easy question dont know why I am not able to find it anywhere I just need to print the specific value of data

My code

  Future<http.Response> _trySubmit() async {
    final isValid = _formKey.currentState.validate();
    FocusScope.of(context).unfocus();

    if (isValid) {
      _formKey.currentState.save();

      print(_userEmail.trim());
      print(_userPassword.trim());

      var map = new Map<String, dynamic>();


      map['grant_type'] = 'password';
      map['username'] = _userEmail.trim();
      map['password'] = _userPassword.trim();


      http.Response res = await http.post(
        'http://sublimeapi.netcodesolution.com/token',
        headers: <String, String>{
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: map,
      );
      var data = res.body;
      print(data);
    }
    }

Its printing the value like this

I/flutter ( 5147):{"access_token":"FwYttAQIDDSRpuFFUgzznmMYgMNNfiW4OvQ4","token_type":"bearer","expires_in":86399}

I need to print just access_token value

Something like this print(data.access_token)

Upvotes: 1

Views: 217

Answers (3)

Tafadzwa L Nyamukapa
Tafadzwa L Nyamukapa

Reputation: 131

Your can try something like this: Decode the json response first then access the data in the Map

http.Response res = await http.post(
    'http://sublimeapi.netcodesolution.com/token',
    headers: <String, String>{
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: map,
  );
     var responseBody = json.decode(res.body);
     print(responseBody['access_token']); //This should return your token
 }
}

Upvotes: 0

Lapa Ny Aina Tanjona
Lapa Ny Aina Tanjona

Reputation: 1268

You need to decode the response result before printing the value :

 http.Response res = await http.post(
            'http://sublimeapi.netcodesolution.com/token',
            headers: <String, String>{
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: map,
          );
          var data = json.decode(res.body.toString());
          print(data["access_token"]);

Don't forget importing :

import 'dart:convert';

Upvotes: 0

Jigar Patel
Jigar Patel

Reputation: 5423

Here data is a Map. So if you want to print a specific value out of it, you need to mention the corresponding key name like this

print(data['access_token']);

Upvotes: 2

Related Questions