验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Flutter中如何处理网络请求

阅读:556 来源:乙速云 作者:代码code

Flutter中如何处理网络请求

在Flutter中,处理网络请求通常使用http库。以下是一个简单的示例,展示了如何使用http库发起GET和POST请求。

首先,需要在pubspec.yaml文件中添加http库的依赖:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

然后,导入http库:

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

接下来,创建一个函数来发起GET请求:

Future<String> fetchGetRequest(String url) async {
  // 发起GET请求
  final response = await http.get(Uri.parse(url));

  // 检查响应状态码
  if (response.statusCode == 200) {
    // 如果请求成功,返回响应数据
    return response.body;
  } else {
    // 如果请求失败,抛出异常
    throw Exception('Failed to load data');
  }
}

创建一个函数来发起POST请求:

Future<String> fetchPostRequest(String url, Map<String, String> headers, String body) async {
  // 发起POST请求
  final response = await http.post(
    Uri.parse(url),
    headers: headers,
    body: body,
  );

  // 检查响应状态码
  if (response.statusCode == 200) {
    // 如果请求成功,返回响应数据
    return response.body;
  } else {
    // 如果请求失败,抛出异常
    throw Exception('Failed to load data');
  }
}

现在,你可以在需要的地方调用这些函数来发起网络请求。例如:

void main() async {
  try {
    // 发起GET请求
    String getData = await fetchGetRequest('https://jsonplaceholder.typicode.com/todos/1');
    print('GET请求数据: $getData');

    // 发起POST请求
    Map<String, String> headers = {'Content-Type': 'application/json'};
    String postData = jsonEncode({'title': 'foo', 'body': 'bar', 'userId': '1'});
    String postResponse = await fetchPostRequest('https://jsonplaceholder.typicode.com/posts', headers, postData);
    print('POST请求数据: $postResponse');
  } catch (e) {
    print(e);
  }
}

这个示例展示了如何在Flutter中使用http库发起GET和POST请求。你可以根据需要修改这些函数以满足你的需求。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>