【问题标题】:how to get the values inside Instance of 'Future<Response<dynamic>?>' in Flutter?如何在 Flutter 中获取“Future<Response<dynamic>?>”实例中的值?
【发布时间】:2021-10-05 15:01:27
【问题描述】:

我使用 Dio 进行 http 请求,post 方法的功能是这样的:

  Future<Response?> post(String url, dynamic data) async {
    try {
      Response response = await baseAPI.post(url, data: data);
      return response;
    } on DioError catch(e) {
      throw Failure(e.message);
    }
  }

然后当我使用这个 post 方法时,我得到的响应是在 'Future' 的实例中。那么如何访问其中的响应数据呢?

void login(String email, String password) {
    dynamic data = jsonEncode(<String, String>{
      'email': email,
      'password':password,
    });

    Future<Response?> response = loginService.post('https://reqres.in/api/login',data) ;
    print(response);
    print('response data print');
   
    }

【问题讨论】:

    标签: flutter dio flutter-http


    【解决方案1】:

    由于您的loginService.post 正在返回一个future 类型,您可以通过在其前面添加await 来获取Response 值,但是您的登录函数将被声明为异步,例如:

    Future<void> login(String email, String password) async {
    dynamic data = jsonEncode(<String, String>{
      'email': email,
      'password':password,
    });
    
    Response? response = await loginService.post('https://reqres.in/api/login',data) ;
    print(response);
    print('response data print');
    
    }
    

    或者,如果您不希望异步登录功能,您可以将 .then 添加到您的帖子loginService.post,如下所示:

    Response? response;
    loginService.post('https://reqres.in/api/login',data).then((data) => response = data)
    

    【讨论】:

      猜你喜欢
      • 2019-09-08
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2019-07-01
      相关资源
      最近更新 更多