Flutter网络请求检查插件requests_inspector的使用

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

Flutter网络请求检查插件requests_inspector的使用

标题

requests_inspector 🕵️‍♂️

内容

  • pub包版本: pub/vs/requests_inspector.svg
  • 功能介绍:
    • 记录HTTP请求、GraphQL和WebSocket请求。
    • 拦截请求和响应进行测试。
    • 将请求详情分享为JSON或cURL命令,以便在Postman或其他工具中重新运行。

使用示例

  1. 获取requests_inspector widget到屏幕上

    • 摇动手机:📱💃
    • 长按屏幕空白处:📱👈
  2. 设置

    void main() {
      runApp(const RequestsInspector(
        child: MyApp(),
      ));
    }
    
  3. RESTful API 示例

    a. 使用Dio并传递RequestsInspectorInterceptor

    final dio = Dio()..interceptors.add(RequestsInspectorInterceptor());
    Future<List<Post>> fetchPosts() async {
      final params = {'userId': 1};
      final response = await dio.get(
        'https://jsonplaceholder.typicode.com/posts',
        queryParameters: params,
      );
    
      final postsMap = response.data as List;
      final posts = postsMap.map((postMap) => Post.fromMap(postMap)).toList();
    
      InspectorController().addNewRequest(
        RequestDetails(
          requestName: 'Posts',
          requestMethod: RequestMethod.GET,
          url: 'https://jsonplaceholder.typicode.com/posts',
          queryParameters: params,
          statusCode: response.statusCode ?? 0,
          responseBody: response.data,
        ),
      );
    
      return posts;
    }
    

    b. 不使用Dio时

    Future<List<Post>> fetchPosts() async {
      final params = {'userId': 1};
      final response = await dio.get(
        'https://jsonplaceholder.typicode.com/posts',
        queryParameters: params,
      );
    
      final postsMap = response.data as List;
      final posts = postsMap.map((postMap) => Post.fromMap(postMap)).toList();
    
      return posts;
    }
    
  4. ** GraphQL 示例**

    Future<List<Post>> fetchPostsGraphQlUsingGraphQLFlutterInterceptor() async {
     final client = GraphQLClient(
       cache: GraphQLCache(),
       link: Link.split(
         (request) => request.isSubscription,
         GraphQLInspectorLink(HttpLink('https://graphqlzero.almansi.me/api')),
       ),
     );
     const query = r'''query {
       post(id: 1) {
         id
         title
         body
       }
     }''';
    
     final options = QueryOptions(document: gql(query));
     final result = await client.query(options);
     if (result.hasException) {
       log(result.exception.toString());
     } else {
       log(result.data.toString());
     }
     var post = Post.fromMap(result.data?['post']);
     return [post];
    

}


5. **停止器(Requests & Responses)**

 需要添加navigatorKey到MaterialApp,并传递给RequestsInspector以启用Stopper特性。

6. **未来计划**

 - 添加GraphQL支持
 - 增强GraphQL请求和响应显示结构
 - 改进请求页面UI并添加展开/折叠功能
 - 不支持暗模式/亮模式
 - 添加搜索功能
 - 添加Http拦截器

7. **许可证**

 项目遵循MIT License,请参阅[LICENSE文件](https://github.com/Abdelazeem777/requests_inspector/blob/main/LICENSE)了解详细信息。

#### 示例代码


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

1 回复

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


当然,以下是如何在Flutter项目中使用requests_inspector插件来进行网络请求检查的示例代码。requests_inspector是一个Flutter插件,它允许开发者在应用程序中拦截和检查HTTP请求和响应。

步骤 1: 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  requests_inspector: ^最新版本号  # 请替换为当前最新版本号

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

步骤 2: 配置应用

在你的main.dart文件中,你需要配置RequestsInspector以拦截网络请求。以下是一个基本的示例:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:requests_inspector/requests_inspector.dart';

void main() {
  // 创建RequestsInspector实例
  final requestsInspector = RequestsInspector();

  // 拦截器设置
  http.Client client = http.Client();
  requestsInspector.setHttpClient(client);

  // 启用RequestsInspector的UI(可选)
  runApp(MaterialApp(
    home: RequestsInspectorWidget(
      child: MyApp(),
      requestsInspector: requestsInspector,
    ),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Network Request Inspector'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 发起一个示例HTTP请求
            final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
            print('Response data: ${response.body}');
          },
          child: Text('Make Request'),
        ),
      ),
    );
  }
}

步骤 3: 使用RequestsInspector

在上述代码中,RequestsInspectorWidgetrequests_inspector插件提供的用于显示请求和响应信息的UI组件。你可以将其包装在你的应用程序的主组件外部,以便能够访问和查看网络请求。

完整示例

将上述步骤整合在一起,你会得到一个完整的Flutter应用程序,它能够在UI中显示HTTP请求和响应信息:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:requests_inspector/requests_inspector.dart';

void main() {
  final requestsInspector = RequestsInspector();

  http.Client client = http.Client();
  requestsInspector.setHttpClient(client);

  runApp(MaterialApp(
    home: RequestsInspectorWidget(
      child: MyApp(),
      requestsInspector: requestsInspector,
    ),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Network Request Inspector'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
            print('Response data: ${response.body}');
          },
          child: Text('Make Request'),
        ),
      ),
    );
  }
}

注意事项

  1. 拦截器设置:确保你在应用程序中尽早设置HTTP客户端的拦截器,以便捕获所有网络请求。
  2. UI显示RequestsInspectorWidget提供了一个默认的UI来显示请求和响应信息。如果你希望自定义显示方式,可以深入阅读requests_inspector的文档,了解如何手动访问和操作请求数据。
  3. 性能考虑:在生产环境中,建议禁用或移除网络请求检查功能,以避免性能开销。

希望这个示例能够帮助你在Flutter项目中使用requests_inspector插件!

回到顶部