Flutter网络请求插件requestor的使用

Requestor 是一个在 Flutter 中轻松高效地进行 HTTP 请求和文件下载的库。

安装

要使用此库,请在 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  requestor: last_version

然后运行命令 flutter pub get 来安装库。

基本用法

在 Dart 文件中导入库:

import 'package:requestor/requestor.dart';

创建一个 Requestor 实例并根据需求进行配置:

Requestor requestor = Requestor();
requestor.setOrigin('https://api.example.com');

requestor.addInterceptor((headers) {
  headers["request-token"] = "xxxxxxx"; // 示例
  return headers;
});

发起 GET 请求

Response response = await requestor.get('/endpoint');
print(response.data);

发起 POST 请求

Map<String, dynamic> data = {'key': 'value'};
Response response = await requestor.post('/endpoint', data);
print(response.data);

下载文件

List<DownloadItem> files = [
  DownloadItem(url: 'https://example.com/file1.txt'),
  DownloadItem(url: 'https://example.com/file2.txt'),
];

String outputPath = '/path/to/save/files';
await requestor.downloadFiles(files, output: outputPath);

可用方法

  • get(url, [headers]): 发起 GET 请求。
  • post(url, data, [headers]): 发起 POST 请求。
  • put(url, data, [headers]): 发起 PUT 请求。
  • delete(url, [headers]): 发起 DELETE 请求。
  • options(url, data, [headers]): 发起 OPTIONS 请求。
  • patch(url, data, [headers]): 发起 PATCH 请求。
  • downloadFiles(urls, {output, headers, threads, onProgress, onDownload}): 从 URL 列表下载文件。
  • getApplicationPath(): 获取应用程序路径。
  • getFilesByDirectory(path): 获取特定目录中的文件列表。

额外配置

可以配置下载线程数并为请求添加自定义头信息:

requestor.threads = 10;
requestor.setConfig({'token': 'your_auth_token'});

完整示例

以下是一个完整的示例,展示了如何使用 Requestor 库来执行不同的任务。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:requestor/requestor.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final req = Requestor();

  [@override](/user/override)
  void initState() {
    req.setOrigin("https://apiv2.tfdev.click");
    req.addInterceptor((p0) => p0);
    super.initState();
  }

  Future<void> post() async {
    String path = "/login";
    print("exec");
    final res = await req.post(
        path, {"rut": "13730077-k", "password": "12345678", "tenant": "agF"});
    print(res);
  }

  Future<void> getTenants() async {
    final res = req.post("/getorgs", {"rut": "12498916-7"});
    print(res);
  }

  Future<void> downloadFiles() async {
    List<DownloadItem> urls = [];

    int i = 0;

    while (i < 200) {
      urls.add(DownloadItem(
        url:
            "https://trainfes-storage-agf.s3.amazonaws.com/1655609972209_carbon+(2).png",
        overwrite: true,
        wildcard: "$i",
      ));
      i++;
    }

    final a = await req.downloadFiles(
      urls,
      onDownload: (p0) {
        print("::::::::::::");
        print("ID -> ${p0.id}");
        print("STATUS: ${p0.status}(${p0.statusCode})");
        print("WILDCARD: ${p0.wildcard}");
        print("::::::::::::");
      },
      onProgress: (p0) {
        print("descarga: ${p0.current} (${p0.progress})");
      },
    );

    print(a.data);
  }

  void multi() async {
    getTenants();
    downloadFiles();
    post();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Requestor example app'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: [
              ElevatedButton(
                onPressed: downloadFiles,
                child: const Text("DOWNLOAD FILES"),
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: post,
                child: const Text("POST"),
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: getTenants,
                child: const Text("GET TENANTS"),
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: multi,
                child: const Text("MULTI TASK"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter网络请求插件requestor的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络请求插件requestor的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


requestor 是一个轻量级的 Flutter 网络请求插件,它简化了 HTTP 请求的发送和处理过程。使用 requestor,你可以轻松地发送 GET、POST、PUT、DELETE 等请求,并处理响应数据。

安装 requestor

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

dependencies:
  flutter:
    sdk: flutter
  requestor: ^0.0.1  # 请使用最新版本

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

使用 requestor

1. 导入包

import 'package:requestor/requestor.dart';

2. 发送 GET 请求

void fetchData() async {
  var requestor = Requestor();
  var response = await requestor.get('https://jsonplaceholder.typicode.com/posts');

  if (response.statusCode == 200) {
    // 请求成功
    print('Response data: ${response.body}');
  } else {
    // 请求失败
    print('Request failed with status: ${response.statusCode}');
  }
}

3. 发送 POST 请求

void postData() async {
  var requestor = Requestor();
  var response = await requestor.post(
    'https://jsonplaceholder.typicode.com/posts',
    body: {
      'title': 'foo',
      'body': 'bar',
      'userId': 1,
    },
  );

  if (response.statusCode == 201) {
    // 请求成功
    print('Response data: ${response.body}');
  } else {
    // 请求失败
    print('Request failed with status: ${response.statusCode}');
  }
}

4. 发送 PUT 请求

void updateData() async {
  var requestor = Requestor();
  var response = await requestor.put(
    'https://jsonplaceholder.typicode.com/posts/1',
    body: {
      'id': 1,
      'title': 'foo',
      'body': 'bar',
      'userId': 1,
    },
  );

  if (response.statusCode == 200) {
    // 请求成功
    print('Response data: ${response.body}');
  } else {
    // 请求失败
    print('Request failed with status: ${response.statusCode}');
  }
}

5. 发送 DELETE 请求

void deleteData() async {
  var requestor = Requestor();
  var response = await requestor.delete('https://jsonplaceholder.typicode.com/posts/1');

  if (response.statusCode == 200) {
    // 请求成功
    print('Response data: ${response.body}');
  } else {
    // 请求失败
    print('Request failed with status: ${response.statusCode}');
  }
}

6. 设置请求头

void fetchDataWithHeaders() async {
  var requestor = Requestor();
  var response = await requestor.get(
    'https://jsonplaceholder.typicode.com/posts',
    headers: {
      'Authorization': 'Bearer your_token_here',
    },
  );

  if (response.statusCode == 200) {
    // 请求成功
    print('Response data: ${response.body}');
  } else {
    // 请求失败
    print('Request failed with status: ${response.statusCode}');
  }
}

处理 JSON 数据

requestor 返回的响应体是字符串格式,你可以使用 dart:convert 包将其解析为 JSON 对象。

import 'dart:convert';

void fetchJsonData() async {
  var requestor = Requestor();
  var response = await requestor.get('https://jsonplaceholder.typicode.com/posts');

  if (response.statusCode == 200) {
    // 解析 JSON 数据
    List<dynamic> data = json.decode(response.body);
    print('First post title: ${data[0]['title']}');
  } else {
    // 请求失败
    print('Request failed with status: ${response.statusCode}');
  }
}

错误处理

你可以使用 try-catch 块来捕获网络请求中的异常。

void fetchDataWithErrorHandling() async {
  var requestor = Requestor();
  try {
    var response = await requestor.get('https://jsonplaceholder.typicode.com/posts');
    if (response.statusCode == 200) {
      print('Response data: ${response.body}');
    } else {
      print('Request failed with status: ${response.statusCode}');
    }
  } catch (e) {
    print('An error occurred: $e');
  }
}
回到顶部