Flutter增强型网络请求插件enhanced_http的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter增强型网络请求插件enhanced_http的使用

enhanced-http

这是一个围绕Google提供的dart http包(https://pub.dev/packages/http)的包装器,灵感来自axios。

Pub GitHub license

Getting started

创建一个enhanced http实例如下:

// 创建EnhancedHttp实例
EnhancedHttp http = EnhancedHttp(baseURL: "https://dog.ceo/api");

可以通过’name’参数提供自定义头(默认的内容类型指定为application/json):

// 带有自定义头的EnhancedHttp实例
EnhancedHttp http = EnhancedHttp(
  baseURL: "https://dog.ceo/api",
  headers: {'Authorization': "Bearer $token"}
);

可以按如下方式提供可选的拦截器:

// 使用拦截器的EnhancedHttp实例
EnhancedHttp http = EnhancedHttp(
    baseURL: "https://dog.ceo/api",
    interceptors: InterceptorOptions(
      response: (dynamic res) {
        print("Status ${res["status"]}");
        print("Headers ${res["headers"]}");
        print("Data ${res["data"]}");
        return res["data"];
      },
      error: (dynamic e) {
        print(e);
        return "An error has occurred please try again later";
      }
    )
);

Usage

从API端点获取数据 - GET

// GET 请求示例
final res = await http.get("/path");

向API端点发送数据 - POST

// POST 请求示例
final res = await http.post("/path", payload: {
    "data": "This is some sample data to send to a server"
});

在API端点更新数据 - PUT

// PUT 请求示例
final res = await http.put("/path", payload: {
    "data": "This is some sample data to update at a server"
});

部分更新API端点的数据 - PATCH

// PATCH 请求示例
final res = await http.patch("/path", payload: {
    "data": "This is some sample data to update at a server"
});

删除API端点的数据 - DELETE

// DELETE 请求示例
final res = await http.delete("/path");

请求API端点的头部信息 - HEAD

// HEAD 请求示例
final res = await http.head("/path");

Additional Parameters

http posthttp puthttp patch方法上的files属性可用于将文件发送到服务器:

// 发送文件示例
final res = await http.post("/path",
    payload: {
        "data": "This is some sample data to update at a server"
    },
    headers: {
      "Content-Type": "multipart/form-data"
    },
    files: [
        {
            "array_key": "file",
            "file": File("path_to_file")
        }
    ],
);

Access to the underlying http package

通过以下方式访问底层的http包,绕过传递依赖导入警告:

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

final res = await http.get("/path");

完整示例Demo

import 'package:flutter/material.dart';
import 'package:enhanced_http/enhanced_http.dart';

void main() {
  // 创建EnhancedHttp实例
  EnhancedHttp http = EnhancedHttp(baseURL: "https://dog.ceo/api");

  runApp(MyApp(http: http));
}

class MyApp extends StatelessWidget {
  final EnhancedHttp http;

  const MyApp({Key? key, required this.http}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Enhanced HTTP Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(http: http),
    );
  }
}

class HomeScreen extends StatefulWidget {
  final EnhancedHttp http;

  const HomeScreen({Key? key, required this.http}) : super(key: key);

  [@override](/user/override)
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String _response = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      // 执行GET请求
      final res = await widget.http.get("/breeds/list/all");
      setState(() {
        _response = res.toString();
      });
    } catch (e) {
      setState(() {
        _response = "Error: $e";
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Enhanced HTTP Demo'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(_response),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用enhanced_http插件进行网络请求的示例代码。enhanced_http是一个增强型的HTTP客户端,提供了更灵活和强大的功能,比如请求拦截、响应转换等。

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

dependencies:
  flutter:
    sdk: flutter
  enhanced_http: ^x.y.z  # 请替换为最新版本号

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

接下来是一个简单的使用示例:

import 'package:flutter/material.dart';
import 'package:enhanced_http/enhanced_http.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Enhanced HTTP Example'),
        ),
        body: Center(
          child: MyHttpWidget(),
        ),
      ),
    );
  }
}

class MyHttpWidget extends StatefulWidget {
  @override
  _MyHttpWidgetState createState() => _MyHttpWidgetState();
}

class _MyHttpWidgetState extends State<MyHttpWidget> {
  String responseData = '';

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: () => fetchData(),
          child: Text('Fetch Data'),
        ),
        SizedBox(height: 20),
        Text(responseData),
      ],
    );
  }

  void fetchData() async {
    // 初始化EnhancedHttp实例
    final http = EnhancedHttp.builder()
      ..baseUrl = 'https://jsonplaceholder.typicode.com' // 设置基础URL
      ..addRequestInterceptor((RequestOptions options) {
        // 在请求发送之前修改请求选项
        print('Sending request: ${options.path}');
        return options;
      })
      ..addResponseInterceptor((ResponseData response) {
        // 在响应返回之前处理响应数据
        if (response.statusCode == 200) {
          print('Received successful response');
        } else {
          print('Received error response: ${response.statusCode}');
        }
        return response;
      })
      ..build();

    try {
      // 发送GET请求
      final response = await http.get('/posts/1');
      if (response.data != null) {
        setState(() {
          responseData = response.data.toString();
        });
      } else {
        setState(() {
          responseData = 'Error: No data received';
        });
      }
    } catch (e) {
      setState(() {
        responseData = 'Error: $e';
      });
    }
  }
}

在这个示例中,我们做了以下几件事:

  1. pubspec.yaml文件中添加了enhanced_http依赖。
  2. 创建了一个简单的Flutter应用,包含一个按钮和一个文本显示区。
  3. 初始化了一个EnhancedHttp实例,并设置了基础URL、请求拦截器和响应拦截器。
  4. 在按钮点击事件中,使用EnhancedHttp实例发送了一个GET请求到https://jsonplaceholder.typicode.com/posts/1,并将响应数据显示在文本区域中。

你可以根据需要自定义拦截器中的逻辑,比如添加认证token、处理错误响应等。希望这个示例对你有所帮助!

回到顶部