【问题标题】:Dio not responding to closed APIDio 没有响应关闭的 API
【发布时间】:2021-05-23 18:26:48
【问题描述】:

我使用 API 来处理登录和存储令牌。如果凭据有效,响应将获得一个令牌,如果凭据无效,则返回一个错误。现在它工作正常,我得到了令牌,如果有错误,catch 方法会显示它,但是当我关闭 API 并发出 POST 请求时,我根本没有得到任何响应。如何处理与 DIO 的连接错误?

Future<bool> login(String email, String password) async {
  try {
    var data = {
      'email': email,
      'password': password,
      'device_name': 'mobile'
    };
    Response response = await _dio.post(
      url + 'sanctum/token',
      data: data,
      options: Options(
        headers: {
          'Accept': 'application/json',
        },
      ),
    );
    await _storage.write(key: 'token', value: response.toString());
    return true;
  } catch (e) {
    print(e.response.toString());
    return false;
  }
}

【问题讨论】:

  • 有错误日志吗?
  • 没有。没有@PreetShah
  • 那么,你怎么知道它不起作用?如果出现任何连接错误,Dio 会返回错误。

标签: flutter dio


【解决方案1】:

尝试使用finally而不是catch返回false:

Future<bool> login(String email, String password) async {
  try {
    // Make the request here like you already are
    return true;
  } catch (e) {
    print(e.response.toString());
  } finally {
    // This wouldn't get called if you already returned from the try block before, 
    // but would get called after catch if an exception was caught.
    return false; 
  }
}

【讨论】:

    猜你喜欢
    • 2014-07-21
    • 2016-03-26
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2018-05-13
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多