颤振打印特定值

时间:2020-08-20 12:05:46

标签: flutter dart

我有一个非常简单的问题,不知道为什么我在只需要打印特定数据值的地方找不到它

我的代码

  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);
    }
    }

它打印出这样的值

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

我只需要打印access_token值

类似这样的打印内容(data.access_token)

3 个答案:

答案 0 :(得分:2)

这里dataMap。因此,如果要从中打印出特定的值,则需要提及类似的键名

print(data['access_token']);

答案 1 :(得分:0)

在打印值之前,您需要解码响应结果:

 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"]);

别忘了导入:

import 'dart:convert';

答案 2 :(得分:0)

您可以尝试执行以下操作:首先解码json响应,然后访问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
 }
}