Skip to content

网络请求

如果是JSON格式的请求,可以直接套用下面的代码

dart
// 超时3秒会自动执行catch
// 你需要根据实际情况来确定返回值
Future<Map<String, dynamic>> httpRequest(String url, {int timeoutInSeconds = 3}) async {
  try {
    final response = await http.get(Uri.parse(url)).timeout(Duration(seconds: timeoutInSeconds));

    if (response.statusCode == 200) {
      String responseBody = utf8.decode(response.bodyBytes);
      Map<String, dynamic> data = json.decode(responseBody);
      return data;
    } else {
      Map<String, dynamic> data = {};
      throw Exception(data);
    }
  } on TimeoutException {
    // 请求超时处理逻辑
    Map<String, dynamic> data = {};
    return data;
  } catch (error) {
    // 其他错误处理逻辑
    Map<String, dynamic> data = {};
    return data;
  }
}

注意

新版本的Flutter在macOS平台上默认禁用了网络请求,因此你需要设置它

你需要在macos/Runner/Release.entitlementsmacos/Runner/DebugProfile.entitlements中添加

entitlements
<key>com.apple.security.network.client</key>
<true/>

Released under the MIT License.