我应该如何使用在一个异步调用中返回的accessToken在另一个异步调用中?

时间:2020-07-31 20:55:56

标签: android-studio flutter

我对Flutter和AP​​I还是很陌生。这是我对登录API的调用,该API返回成功的jwt令牌,称为accessToken。现在,我需要在下一个呼叫中使用此acccessToken来创建联系人。如何在创建联系人范围内获取它?

Future<void> _login() async {
bool error = false;
String errorMsg = '';

{
  setState(() {
    this._isLoading = true;
  });
  final username = 'a316';
  final password = 'a316!!';
    final accessToken = await sl
        .get<UsersApi>()

        .login(LoginUserDTO.fromJson({
      "grantType": "password",
      "username": username,
      "password": password
    }))

        .then((resp) => resp.data.accessToken)
        .catchError((e) {
      error = false;
      errorMsg = e.toString();
    });
//  print(accessToken);
}

这是我想使用它的地方,但是超出范围。

 Future<void> _makePostRequest() async {
// set up POST request arguments
String url = 'https://myUrl';
Map<String, String> headers = {"Content-type": "application/json",  "Authorization": "Bearer " + accessToken}; 
//this is where I'd like to use it.
    String json = '{"title": "Hello", "body": "body text", "userId": 1}';
    // make POST request
    Response response = await post(url, headers: headers, body: json);
    // check the status code for the result
    int statusCode = response.statusCode;
    // this API passes back the id of the new item added to the body
    String body = response.body;
    
  }

1 个答案:

答案 0 :(得分:0)

将其存储在变量中:

var accessToken;

Future<void> _login() async {
bool error = false;
String errorMsg = '';

{
  setState(() {
    this._isLoading = true;
  });
  final username = 'a316';
  final password = 'a316!!';
  accessToken = await sl
        .get<UsersApi>()

        .login(LoginUserDTO.fromJson({
      "grantType": "password",
      "username": username,
      "password": password
    }))

        .then((resp) => resp.data.accessToken)
        .catchError((e) {
      error = false;
      errorMsg = e.toString();
    });
//  print(accessToken);
}

 Future<void> _makePostRequest() async {
// set up POST request arguments
String url = 'https://myUrl';
Map<String, String> headers = {"Content-type": "application/json",  "Authorization": "Bearer " + accessToken}; 
//this is where I'd like to use it.
    String json = '{"title": "Hello", "body": "body text", "userId": 1}';
    // make POST request
    Response response = await post(url, headers: headers, body: json);
    // check the status code for the result
    int statusCode = response.statusCode;
    // this API passes back the id of the new item added to the body
    String body = response.body;
    
  }