首页 > 解决方案 > 从未来中提取价值

问题描述

我想从 api 调用中提取响应的值。

  import 'package:http/http.dart' as http;

  refreshToken() {
  Future<http.Response> _response = _httpClient.callApi(
      endPoint: refreshTokenEndpoint, variables: refreshTokenVariables);

  http.Response _tokenResponse;
  _response.then((http.Response value) => _tokenResponse = value);

  print(_tokenResponse.body);
  }

但是当我尝试访问正文时,我得到一个错误 body was called on null 。

标签: flutterdart

解决方案


你需要等待,_tokenResponse因为来自未来。

refreshTokenSolution() async {
    Future<bool> _response = Future.delayed(Duration(seconds: 2), () => true);
    bool _tokenResponse = await _response; // Wait this response and after go next line
    print(_tokenResponse); //TRUE
  }

推荐阅读