如何从响应主体获取令牌值?

时间:2019-08-30 03:22:09

标签: json flutter dart

我试图从response.body获取令牌值,并存储在共享首选项中。

这是我得到的JSON响应:

{"meta":{"error":false,"message":"","statusCode":200},"response":{"token":"JhbGciOiJIUzI1NiJ9.MiOiJodHRwczovL3N0Z62Q_NQJcK0dFCKiUOsl-k","user":{"id":12,"name":"suuu","firstName":"sss","lastName":"ss","icNumber":null,"email":"wew@example.com","description":"Retails Test","gender":"Male","phoneNumber":"0123456789","website":"retailsexample.com","createdAt":"2017-09-15 11:27:42","updatedAt":"2019-08-21 16:08:32","oldEmailData":null,"profilePictures":[{"width":795,"height":800

我试图这样打印令牌,但结果显示为空:

  print('access token is -> ${json.decode(response.body)[ 'token']}');

所以我有以下代码来获取和存储令牌:

  if(request.statusCode == 200) {
  jsonResponse = json.decode(response.body);
  if(jsonResponse != null) {
    setState(() {
      _isLoading = false;
    });
    sharedPreferences.setString("token", jsonResponse['token']);
    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => MainPage()), (Route<dynamic> route) => false);
  }

那么,如何从response.body获取令牌?

1 个答案:

答案 0 :(得分:0)

下面的代码行会将令牌放入字符串变量中:

arr.flat[0]

在您的代码中,只需替换

String token = jsonResponse['response']['token']

sharedPreferences.setString("token", jsonResponse['token'])