Flutter数据获取插件ac_fetch的使用

Flutter数据获取插件ac_fetch的使用

这是一个易于使用的HTTP数据获取插件,支持HTTP1/2以及内置HTTP缓存。

特性

该插件基于ac_httpx_client包。它继承了所有其特性,并增加了以下功能:

  • Content-Type字符集编码/解码;
  • Content-Type结构化数据编解码器(更多信息见下文);
  • 自定义类型化数据支持;

目前尚未实现的功能:

  • WHATWG fetch-like缓存模式;

使用

请求

final options = FetchOptions(
  method: 'POST',
  url: Uri.parse('https://www.example.com'),
  headers: HttpxHeaders.fromMap({
    'Content-Type': 'application/json; charset=utf-8',
    'Accept': 'application/json',
  }),
);

final request = fetch(options);

final requestData = {
  'data': 'Hello world!',
};

final response = await request.writeStructuredData(structuredData);

final responseData = await response.waitStructuredData();

// responseData是一个经过字符集解码和JSON解码后的值
print(responseData);

辅助函数

无数据发送

final options = FetchOptions(
  method: 'GET',
  url: Uri.parse('https://www.example.com'),
  headers: HttpxHeaders.fromMap({
    'Accept': 'application/json',
  }),
);

final response = await fetchWithNoData(options);

final responseData = await response.waitStructuredData();

print(responseData);

发送结构化数据

final options = FetchOptions(
  method: 'GET',
  url: Uri.parse('https://www.example.com'),
  headers: HttpxHeaders.fromMap({
    'Accept': 'application/json',
  }),
);

final requestData = {
  'data': 'Hello world!',
};

final response = await fetchWithStructuredData(options, requestData);

final responseData = await response.waitStructuredData();

print(responseData);

发送类型化数据

class RequestData {
  final String data;

  RequestData(this.data);

  @override 
  Map<String, dynamic> toJson() => {
    'data': data,
  };
}

class ResponseData {
  final String data;

  ResponseData.fromJson(Map<String, dynamic> json)
    : data = json['data'];
}

dynamic typedDataEncoder(
  dynamic typedData,
  Type typedDataType,
) {
  if (typedData is RequestData) {
    return typedData.toJson();
  }

  return typedData;
}

dynamic typedDataDecoder(
  dynamic structuredData,
  Type typedDataType,
) {
  if (typedDataType == ResponseData) {
    return ResponseData.fromJson(structuredData as Map<String, dynamic>);
  }

  return structuredData;
}

final options = FetchOptions(
  method: 'POST',
  url: Uri.parse('https://www.example.com'),
  headers: HttpxHeaders.fromMap({
    'Content-Type': 'application/json; charset=utf-8',
    'Accept': 'application/json',
  }),
  defaultTypedDataEncoder: typedDataEncoder,
  defaultTypedDataDecoder: typedDataDecoder,
);

final requestData = RequestData('Hello world!');

final response = fetchWithTypedData(options, requestData);

final responseData = await response.waitTypedData<ResponseData>();

print(responseData);

HTTP客户端

默认的HttpxClient可以通过FetchGlobals单例类访问:

final myHttpxClient = HttpxClient();

FetchGlobals().defaultHttpxClient = myHttpxClient;

你也可以在调用fetch或辅助函数时指定要使用的HttpxClient

final myHttpxClient = HttpxClient();

final options = FetchOptions(
  method: 'GET',
  url: Uri.parse('https://www.example.com'),
);

final response = await fetchWithNoData(options, httpxClient: myHttpxClient);

...

更多关于Flutter数据获取插件ac_fetch的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据获取插件ac_fetch的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


ac_fetch 是一个用于 Flutter 的数据获取插件,它简化了网络请求和数据获取的过程。通过 ac_fetch,你可以轻松地发送 HTTP 请求并处理响应数据。以下是如何使用 ac_fetch 插件的详细步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 ac_fetch 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  ac_fetch: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入包

在你的 Dart 文件中导入 ac_fetch 包:

import 'package:ac_fetch/ac_fetch.dart';

3. 发送 GET 请求

使用 ac_fetch 发送一个简单的 GET 请求:

void fetchData() async {
  try {
    final response = await AcFetch.get('https://jsonplaceholder.typicode.com/posts');
    if (response.statusCode == 200) {
      // 请求成功
      print('Response data: ${response.body}');
    } else {
      // 请求失败
      print('Failed to load data: ${response.statusCode}');
    }
  } catch (e) {
    // 处理异常
    print('Error: $e');
  }
}

4. 发送 POST 请求

发送 POST 请求并传递数据:

void postData() async {
  try {
    final response = await AcFetch.post(
      'https://jsonplaceholder.typicode.com/posts',
      body: {
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
      },
      headers: {
        'Content-Type': 'application/json',
      },
    );
    if (response.statusCode == 201) {
      // 请求成功
      print('Response data: ${response.body}');
    } else {
      // 请求失败
      print('Failed to post data: ${response.statusCode}');
    }
  } catch (e) {
    // 处理异常
    print('Error: $e');
  }
}

5. 处理响应数据

ac_fetch 的响应对象 Response 包含了请求的状态码、响应体等信息。你可以根据需要处理这些数据。

void fetchAndProcessData() async {
  try {
    final response = await AcFetch.get('https://jsonplaceholder.typicode.com/posts/1');
    if (response.statusCode == 200) {
      // 解析 JSON 数据
      final Map<String, dynamic> data = response.body;
      print('Post title: ${data['title']}');
    } else {
      print('Failed to load data: ${response.statusCode}');
    }
  } catch (e) {
    print('Error: $e');
  }
}

6. 处理错误和异常

ac_fetch 会自动处理一些常见的网络错误,但你仍然需要捕获并处理可能的异常。

void fetchDataWithErrorHandling() async {
  try {
    final response = await AcFetch.get('https://jsonplaceholder.typicode.com/invalid-endpoint');
    if (response.statusCode == 200) {
      print('Response data: ${response.body}');
    } else {
      print('Failed to load data: ${response.statusCode}');
    }
  } on SocketException catch (e) {
    print('Network error: $e');
  } on HttpException catch (e) {
    print('HTTP error: $e');
  } on FormatException catch (e) {
    print('Data parsing error: $e');
  } catch (e) {
    print('Unknown error: $e');
  }
}

7. 配置全局选项

你可以通过 AcFetchConfig 配置全局选项,例如设置默认的请求头、超时时间等。

void configureGlobalOptions() {
  AcFetchConfig(
    baseUrl: 'https://jsonplaceholder.typicode.com',
    headers: {
      'Authorization': 'Bearer your_token',
    },
    timeout: Duration(seconds: 10),
  );
}

8. 使用拦截器

ac_fetch 支持请求和响应拦截器,你可以在发送请求或处理响应之前进行一些操作。

void setupInterceptors() {
  AcFetch.interceptors.add(
    InterceptorsWrapper(
      onRequest: (options, handler) {
        // 在发送请求之前做一些事情
        print('Request URL: ${options.url}');
        return handler.next(options);
      },
      onResponse: (response, handler) {
        // 在处理响应之前做一些事情
        print('Response status code: ${response.statusCode}');
        return handler.next(response);
      },
      onError: (error, handler) {
        // 处理请求错误
        print('Error: $error');
        return handler.next(error);
      },
    ),
  );
}
回到顶部