Flutter中如何处理网络请求

发布时间:2025-04-15 15:21:46 作者:小樊
来源:亿速云 阅读:96

在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请求。你可以根据需要修改这些函数以满足你的需求。

推荐阅读:
  1. 如何使用Flutter实现网络请求
  2. 使用Flutter怎么实现一个网络请求

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

flutter

上一篇:Flutter项目如何进行国际化支持

下一篇:如何自定义OpenHarmony进度条

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》