├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── README_zh.md ├── android └── app │ └── src │ └── main │ └── java │ └── io │ └── flutter │ └── plugins │ └── GeneratedPluginRegistrant.java ├── example ├── .gitignore ├── .metadata ├── README.md ├── example.iml ├── example_android.iml ├── lib │ ├── home_page.dart │ ├── http_utils.dart │ └── main.dart └── pubspec.yaml ├── images ├── dio_log_example.gif ├── log_filter.jpg ├── log_list.jpg ├── log_request.jpg ├── log_response.jpg └── wechat.png ├── ios ├── Flutter │ ├── Generated.xcconfig │ └── flutter_export_environment.sh └── Runner │ ├── GeneratedPluginRegistrant.h │ └── GeneratedPluginRegistrant.m ├── lib ├── bean │ ├── err_options.dart │ ├── net_options.dart │ ├── req_options.dart │ └── res_options.dart ├── dio_log.dart ├── http_log_list_widget.dart ├── interceptor │ └── dio_log_interceptor.dart ├── overlay_draggable_button.dart ├── page │ ├── log_error_widget.dart │ ├── log_request_widget.dart │ ├── log_response_widget.dart │ └── log_widget.dart ├── theme │ └── style.dart ├── utils │ ├── copy_clipboard.dart │ ├── json_utils.dart │ ├── log_pool_manager.dart │ ├── time_utils.dart │ └── url_utils.dart └── widget │ ├── input_dialog.dart │ └── json_view.dart └── pubspec.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | dio_log.iml 2 | workspace.xml 3 | .idea 4 | .packages 5 | *.lock 6 | .dart_tool 7 | .fvm 8 | .vscode 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [v5.3.0+1] - 2025/01/20 2 | * add logs filter function. 3 | * LogPoolManager.maxCount from 50 to 200. 4 | ## [v5.3.0] - 2024/05/22 5 | * Dio 5.3.0 support. 6 | * Synchronize the tag of the project with the tag of the Dio library. 7 | ## [v2.0.5] - 2023/08/22 8 | * Dio 5.0.0 support. 9 | ## [v2.0.4] - 2022/07/11 10 | * remove WidgetsBinding.instance.addPostFrameCallback was replaced by await Future.delayed(Duration(milliseconds: 500)); 11 | ## [v2.0.3] - 2022/06/13 12 | * fix flutter 3.0 warning of WidgetsBinding 13 | * Add the isError method implementation to LogPoolManager so that request messages defined as errors are displayed in red font 14 | ## [v2.0.2] - 2022/03/22 15 | * fix copy Clipboard error 16 | * Response header values can be copied 17 | ## [v2.0.1] - 2021/10/15 18 | * response add headers 19 | * overlay_draggable_button can set the color 20 | ## [v2.0.0] - 2021/04/01 21 | * stable version 22 | * Happy April Fools' Day 23 | ## [v2.0.0-nullsafety.0] - 2021/03/30 24 | * Dio 4.0.0 support. 25 | * Migrated to Flutter 2 and Better Theme support. 26 | * Migrated to null safety. 27 | * to public API add doc comments 28 | * use ElevatedButton instead of RaisedButton 29 | ## [v1.3.5] - 2020/09/04 30 | * ShowDebugBtn on WidgetsBinding.Instance.AddPostFrameCallback callback 31 | * Adds a body of type FormData According to 32 | * Adds a body of type string According to 33 | ## [v1.3.4] - 2020/2/03 34 | * add replication request information 35 | ## [v1.3.3] - 2019/9/18 36 | * Support dio > 3.0.0 37 | ## [v1.3.2] - 2019/9/18 38 | * Support Flutter Web 39 | * Support dio >2.2.1 40 | * if you dio version < 2.2.1, please use dio_log:1.3.1 41 | ## [v1.3.1] - 2019/9/05 42 | * fix shrink and expand bug 43 | ## [v1.3.0] - 2019/8/21 44 | * Optimize the request display UI 45 | * HttpLogInterceptor Deprecated and change it to DioLogInterceptor 46 | ## [v1.2.1] - 2019/8/05 47 | * add example project 48 | * Fix the response parsing bug 49 | ## [v1.2.0] - 2019/8/01 50 | * add overlay_draggable_button(Global float window is easier to open HttpLogListWidget) 51 | * add clear log function at requestList 52 | * add display requestTime at requestList 53 | ## [v1.1.1] - 2019/7/22 54 | * add Screenshot 55 | ## [v1.1.0] - 2019/7/22 56 | * support jsonView look at json 57 | ## [v1.0.3] - 2019/7/16 58 | * fix some code 59 | * Lower the version needed by dio 60 | ## [v1.0.2] - 2019/7/16 61 | * Add description information and example 62 | ## [v1.0.1] - 2019/6/6 63 | * Add a display of the body content to the request 64 | * Logs with failed requests are shown in red in the list 65 | ## [v1.0.0] - 2018/09/04 66 | 67 | * initial version 68 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 rich 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: format check pub 2 | format: 3 | @echo '格式化dart代码---执行|dart format .|命令' 4 | @fvm dart format . 5 | check: 6 | @echo '检查代码---执行|dart analyze .|命令' 7 | @fvm dart analyze . 8 | pub: 9 | @echo '发布插件到pub---执行|packages pub publish --server=https://pub.dev|命令' 10 | @fvm flutter packages pub publish --server=https://pub.dev 11 | 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dio_log 2 | [![pub package](https://img.shields.io/pub/v/dio_log.svg)](https://pub.dev/packages/dio_log) 3 | 4 | [English](./README.md) | [中文](./README_zh.md) 5 | 6 | ## Description 7 | HTTP Inspector tool for Dart which can debugging http requests. Currently, DIO based HTTP capture is implemented. 8 | Of course, you can implement an Interceptor instead of a DiologInterceptor to adapt to other HTTP clients. 9 | ## Installation 10 | Add this to your package's `pubspec.yaml` file: 11 | ```yaml 12 | dependencies: 13 | dio_log: 5.3.0+1 14 | ``` 15 | 16 | ## Usage 17 | 1. Set interceptor of dio: 18 | ```dart 19 | dio.interceptors.add(DioLogInterceptor()); 20 | ``` 21 | 22 | 2. Add a global hover button on your home page: 23 | ```dart 24 | // Display overlay button 25 | showDebugBtn(context, btnColor: Colors.blue); 26 | // Cancel overlay button 27 | dismissDebugBtn(); 28 | // Check overlay button state 29 | debugBtnIsShow() 30 | ``` 31 | 32 | 3. Or open log list manually: 33 | ```dart 34 | Navigator.of(context).push( 35 | MaterialPageRoute( 36 | builder: (context) => HttpLogListWidget(), 37 | ), 38 | ); 39 | ``` 40 | 41 | ## Configuration 42 | ```dart 43 | // Sets the maximum number of entries for logging 44 | LogPoolManager.getInstance().maxCount = 100; 45 | // Add custom error detection 46 | LogPoolManager.getInstance().isError = (res) => res.resOptions==null; 47 | // Disable Log Printing 48 | DioLogInterceptor.enablePrintLog = false; 49 | ``` 50 | 51 | ## Screenshots 52 | 53 | 54 | 55 | 56 | 57 | ## Demo 58 | ![gif](https://raw.githubusercontent.com/flutterplugin/dio_log/develop/images/dio_log_example.gif) -------------------------------------------------------------------------------- /README_zh.md: -------------------------------------------------------------------------------- 1 | # dio_log 2 | [![pub package](https://img.shields.io/pub/v/dio_log.svg)](https://pub.dev/packages/dio_log) 3 | 4 | [English](README.md) | [中文](README_zh.md) 5 | 6 | ## 描述 7 | 这是一个用于 Dart 的 HTTP 检查器工具,可以帮助调试 HTTP 请求。目前实现了基于 dio 的 http 捕获功能。 8 | 当然,您可以通过自己实现 Interceptor 来代替 DioLogInterceptor 以适配其他 Http client。 9 | 10 | ## 安装 11 | 在您的 `pubspec.yaml` 文件中添加: 12 | ```yaml 13 | dependencies: 14 | dio_log: 5.3.0+1 15 | ``` 16 | 17 | ## 使用方法 18 | 1. 给 dio 设置拦截器: 19 | ```dart 20 | dio.interceptors.add(DioLogInterceptor()); 21 | ``` 22 | 23 | 2. 在主页面添加全局悬浮按钮: 24 | ```dart 25 | // 显示悬浮按钮 26 | showDebugBtn(context, btnColor: Colors.blue); 27 | // 取消悬浮按钮 28 | dismissDebugBtn(); 29 | // 检查悬浮按钮显示状态 30 | debugBtnIsShow() 31 | ``` 32 | 33 | 3. 或者在需要的地方手动打开日志列表: 34 | ```dart 35 | Navigator.of(context).push( 36 | MaterialPageRoute( 37 | builder: (context) => HttpLogListWidget(), 38 | ), 39 | ); 40 | ``` 41 | 42 | ## 配置选项 43 | ```dart 44 | // 设置记录日志的最大条数 45 | LogPoolManager.getInstance().maxCount = 100; 46 | // 添加自定义错误检测 47 | LogPoolManager.getInstance().isError = (res) => res.resOptions==null; 48 | // 禁用日志打印 49 | DioLogInterceptor.enablePrintLog = false; 50 | ``` 51 | 52 | ## 截图展示 53 | 54 | 55 | 56 | 57 | 58 | ## 演示 59 | ![gif](https://raw.githubusercontent.com/flutterplugin/dio_log/develop/images/dio_log_example.gif) -------------------------------------------------------------------------------- /android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java: -------------------------------------------------------------------------------- 1 | package io.flutter.plugins; 2 | 3 | import io.flutter.plugin.common.PluginRegistry; 4 | 5 | /** 6 | * Generated file. Do not edit. 7 | */ 8 | public final class GeneratedPluginRegistrant { 9 | public static void registerWith(PluginRegistry registry) { 10 | if (alreadyRegisteredWith(registry)) { 11 | return; 12 | } 13 | } 14 | 15 | private static boolean alreadyRegisteredWith(PluginRegistry registry) { 16 | final String key = GeneratedPluginRegistrant.class.getCanonicalName(); 17 | if (registry.hasPlugin(key)) { 18 | return true; 19 | } 20 | registry.registrarFor(key); 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .dart_tool/ 3 | 4 | .packages 5 | .pub/ 6 | 7 | .idea/ 8 | .vagrant/ 9 | .sconsign.dblite 10 | .svn/ 11 | 12 | *.swp 13 | profile 14 | 15 | DerivedData/ 16 | 17 | .generated/ 18 | 19 | *.pbxuser 20 | *.mode1v3 21 | *.mode2v3 22 | *.perspectivev3 23 | 24 | !default.pbxuser 25 | !default.mode1v3 26 | !default.mode2v3 27 | !default.perspectivev3 28 | 29 | xcuserdata 30 | 31 | *.moved-aside 32 | 33 | *.pyc 34 | *sync/ 35 | Icon? 36 | .tags* 37 | 38 | build/ 39 | .android/ 40 | .ios/ 41 | .flutter-plugins 42 | -------------------------------------------------------------------------------- /example/.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: 2fefa8c7315c32191aa10ef0ef03afb565e99701 8 | channel: unknown 9 | 10 | project_type: module 11 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # example 2 | 3 | example of dio log 4 | 5 | ## Getting Started 6 | 7 | For help getting started with Flutter, view our online 8 | [documentation](https://flutter.dev/). 9 | -------------------------------------------------------------------------------- /example/example.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /example/example_android.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /example/lib/home_page.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio_log/dio_log.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | import 'http_utils.dart'; 5 | 6 | class MyHomePage extends StatefulWidget { 7 | MyHomePage({Key? key, required this.title}) : super(key: key); 8 | 9 | final String title; 10 | 11 | @override 12 | _MyHomePageState createState() => _MyHomePageState(); 13 | } 14 | 15 | class _MyHomePageState extends State { 16 | TextEditingController controller = TextEditingController(); 17 | 18 | // 添加 API 列表 19 | final Map apiEndpoints = { 20 | 'GitHub 用户列表': 'https://api.github.com/users', 21 | 'JSONPlaceholder 帖子': 'https://jsonplaceholder.typicode.com/posts', 22 | '随机用户数据': 'https://randomuser.me/api/', 23 | '天气数据(伦敦)': 'https://api.open-meteo.com/v1/forecast?latitude=51.5085&longitude=-0.1257&forecast_days=1', 24 | '狗狗图片': 'https://dog.ceo/api/breeds/image/random', 25 | '猫咪图片': 'https://api.thecatapi.com/v1/images/search', 26 | '比特币价格': 'https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT', 27 | }; 28 | 29 | String selectedApi = 'GitHub 用户列表'; // 默认选中的 API 30 | 31 | @override 32 | void initState() { 33 | super.initState(); 34 | showDebugBtn(context, btnColor: Colors.blue); 35 | controller.text = apiEndpoints[selectedApi]!; 36 | } 37 | 38 | @override 39 | void dispose() { 40 | super.dispose(); 41 | } 42 | 43 | @override 44 | Widget build(BuildContext context) { 45 | return Scaffold( 46 | appBar: AppBar( 47 | title: Text(widget.title), 48 | ), 49 | body: Center( 50 | child: Column( 51 | mainAxisAlignment: MainAxisAlignment.center, 52 | children: [ 53 | Text( 54 | '选择一个 API 接口进行测试', 55 | style: TextStyle(fontSize: 16), 56 | ), 57 | Padding( 58 | padding: const EdgeInsets.all(16.0), 59 | child: DropdownButton( 60 | value: selectedApi, 61 | isExpanded: true, 62 | items: apiEndpoints.keys.map((String key) { 63 | return DropdownMenuItem( 64 | value: key, 65 | child: Text(key), 66 | ); 67 | }).toList(), 68 | onChanged: (String? newValue) { 69 | if (newValue != null) { 70 | setState(() { 71 | selectedApi = newValue; 72 | controller.text = apiEndpoints[newValue]!; 73 | }); 74 | } 75 | }, 76 | ), 77 | ), 78 | Padding( 79 | padding: const EdgeInsets.all(16.0), 80 | child: TextField( 81 | controller: controller, 82 | decoration: InputDecoration( 83 | border: OutlineInputBorder(), 84 | labelText: 'API URL', 85 | ), 86 | maxLines: 2, 87 | ), 88 | ), 89 | ], 90 | ), 91 | ), 92 | floatingActionButton: FloatingActionButton( 93 | onPressed: _sendRequest, 94 | child: Icon(Icons.send), 95 | tooltip: '发送请求', 96 | ), 97 | ); 98 | } 99 | 100 | _sendRequest() async { 101 | httpGet(controller.text); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /example/lib/http_utils.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio/dio.dart'; 2 | import 'package:dio_log/dio_log.dart'; 3 | 4 | Dio dio = Dio(); 5 | 6 | initHttp() { 7 | DioLogInterceptor.enablePrintLog = false; 8 | dio.interceptors.add(DioLogInterceptor()); 9 | // LogPoolManager.getInstance().isError = (res) => res.resOptions==null; 10 | } 11 | 12 | httpGet(String url) { 13 | dio.get(url); 14 | } 15 | -------------------------------------------------------------------------------- /example/lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | import 'home_page.dart'; 4 | import 'http_utils.dart'; 5 | 6 | void main() { 7 | initHttp(); 8 | runApp(MyApp()); 9 | } 10 | 11 | class MyApp extends StatelessWidget { 12 | // This widget is the root of your application. 13 | @override 14 | Widget build(BuildContext context) { 15 | return MaterialApp( 16 | title: 'Demo of dio_log', 17 | theme: ThemeData( 18 | primarySwatch: Colors.blue, 19 | ), 20 | home: MyHomePage(title: 'Demo of dio_log'), 21 | ); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: example 2 | description: example of dio log 3 | 4 | # The following defines the version and build number for your application. 5 | # A version number is three numbers separated by dots, like 1.2.43 6 | # followed by an optional build number separated by a +. 7 | # Both the version and the builder number may be overridden in flutter 8 | # build by specifying --build-name and --build-number, respectively. 9 | # In Android, build-name is used as versionName while build-number used as versionCode. 10 | # Read more about Android versioning at https://developer.android.com/studio/publish/versioning 11 | # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. 12 | # Read more about iOS versioning at 13 | # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html 14 | # 15 | # This version is used _only_ for the Runner app, which is used if you just do 16 | # a `flutter run` or a `flutter make-host-app-editable`. It has no impact 17 | # on any other native host app that you embed your Flutter project into. 18 | version: 1.0.0+1 19 | 20 | environment: 21 | sdk: ">=2.18.0 <4.0.0" 22 | 23 | dependencies: 24 | flutter: 25 | sdk: flutter 26 | 27 | # The following adds the Cupertino Icons font to your application. 28 | # Use with the CupertinoIcons class for iOS style icons. 29 | cupertino_icons: ^1.0.1 30 | dio: ^5.3.0 31 | dio_log: 32 | path: ../../dio_log 33 | 34 | dev_dependencies: 35 | flutter_test: 36 | sdk: flutter 37 | 38 | # For information on the generic Dart part of this file, see the 39 | # following page: https://dart.dev/tools/pub/pubspec 40 | 41 | flutter: 42 | # The following line ensures that the Material Icons font is 43 | # included with your application, so that you can use the icons in 44 | # the material Icons class. 45 | uses-material-design: true 46 | 47 | # To add Flutter specific assets to your application, add an assets section, 48 | # like this: 49 | # assets: 50 | # - images/a_dot_burr.jpeg 51 | # - images/a_dot_ham.jpeg 52 | 53 | # An image asset can refer to one or more resolution-specific "variants", see 54 | # https://flutter.dev/assets-and-images/#resolution-aware. 55 | 56 | # For details regarding adding assets from package dependencies, see 57 | # https://flutter.dev/assets-and-images/#from-packages 58 | 59 | # To add Flutter specific custom fonts to your application, add a fonts 60 | # section here, in this "flutter" section. Each entry in this list should 61 | # have a "family" key with the font family name, and a "fonts" key with a 62 | # list giving the asset and other descriptors for the font. For 63 | # example: 64 | # fonts: 65 | # - family: Schyler 66 | # fonts: 67 | # - asset: fonts/Schyler-Regular.ttf 68 | # - asset: fonts/Schyler-Italic.ttf 69 | # style: italic 70 | # - family: Trajan Pro 71 | # fonts: 72 | # - asset: fonts/TrajanPro.ttf 73 | # - asset: fonts/TrajanPro_Bold.ttf 74 | # weight: 700 75 | # 76 | # For details regarding fonts from package dependencies, 77 | # see https://flutter.dev/custom-fonts/#from-packages 78 | 79 | # This section identifies your Flutter project as a module meant for 80 | # embedding in a native host app. These identifiers should _not_ ordinarily 81 | # be changed after generation - they are used to ensure that the tooling can 82 | # maintain consistency when adding or modifying assets and plugins. 83 | # They also do not have any bearing on your native host application's 84 | # identifiers, which may be completely independent or the same as these. 85 | module: 86 | androidX: false 87 | androidPackage: com.rich.example 88 | iosBundleIdentifier: com.rich.example 89 | -------------------------------------------------------------------------------- /images/dio_log_example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flutterplugin/dio_log/67b0555557dc6bde5302359e315e5adb49e8e41d/images/dio_log_example.gif -------------------------------------------------------------------------------- /images/log_filter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flutterplugin/dio_log/67b0555557dc6bde5302359e315e5adb49e8e41d/images/log_filter.jpg -------------------------------------------------------------------------------- /images/log_list.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flutterplugin/dio_log/67b0555557dc6bde5302359e315e5adb49e8e41d/images/log_list.jpg -------------------------------------------------------------------------------- /images/log_request.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flutterplugin/dio_log/67b0555557dc6bde5302359e315e5adb49e8e41d/images/log_request.jpg -------------------------------------------------------------------------------- /images/log_response.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flutterplugin/dio_log/67b0555557dc6bde5302359e315e5adb49e8e41d/images/log_response.jpg -------------------------------------------------------------------------------- /images/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flutterplugin/dio_log/67b0555557dc6bde5302359e315e5adb49e8e41d/images/wechat.png -------------------------------------------------------------------------------- /ios/Flutter/Generated.xcconfig: -------------------------------------------------------------------------------- 1 | // This is a generated file; do not edit or check into version control. 2 | FLUTTER_ROOT=/Users/rich/fvm/versions/3.0.1 3 | FLUTTER_APPLICATION_PATH=/Users/rich/Documents/flutterplugin/dio_log 4 | COCOAPODS_PARALLEL_CODE_SIGN=true 5 | FLUTTER_TARGET=lib/main.dart 6 | FLUTTER_BUILD_DIR=build 7 | FLUTTER_BUILD_NAME=2.0.2 8 | FLUTTER_BUILD_NUMBER=2.0.2 9 | EXCLUDED_ARCHS[sdk=iphonesimulator*]=i386 10 | DART_OBFUSCATION=false 11 | TRACK_WIDGET_CREATION=false 12 | TREE_SHAKE_ICONS=false 13 | PACKAGE_CONFIG=.dart_tool/package_config.json 14 | -------------------------------------------------------------------------------- /ios/Flutter/flutter_export_environment.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # This is a generated file; do not edit or check into version control. 3 | export "FLUTTER_ROOT=/Users/rich/fvm/versions/3.0.1" 4 | export "FLUTTER_APPLICATION_PATH=/Users/rich/Documents/flutterplugin/dio_log" 5 | export "COCOAPODS_PARALLEL_CODE_SIGN=true" 6 | export "FLUTTER_TARGET=lib/main.dart" 7 | export "FLUTTER_BUILD_DIR=build" 8 | export "FLUTTER_BUILD_NAME=2.0.2" 9 | export "FLUTTER_BUILD_NUMBER=2.0.2" 10 | export "DART_OBFUSCATION=false" 11 | export "TRACK_WIDGET_CREATION=false" 12 | export "TREE_SHAKE_ICONS=false" 13 | export "PACKAGE_CONFIG=.dart_tool/package_config.json" 14 | -------------------------------------------------------------------------------- /ios/Runner/GeneratedPluginRegistrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GeneratedPluginRegistrant_h 8 | #define GeneratedPluginRegistrant_h 9 | 10 | #import 11 | 12 | NS_ASSUME_NONNULL_BEGIN 13 | 14 | @interface GeneratedPluginRegistrant : NSObject 15 | + (void)registerWithRegistry:(NSObject*)registry; 16 | @end 17 | 18 | NS_ASSUME_NONNULL_END 19 | #endif /* GeneratedPluginRegistrant_h */ 20 | -------------------------------------------------------------------------------- /ios/Runner/GeneratedPluginRegistrant.m: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #import "GeneratedPluginRegistrant.h" 8 | 9 | @implementation GeneratedPluginRegistrant 10 | 11 | + (void)registerWithRegistry:(NSObject*)registry { 12 | } 13 | 14 | @end 15 | -------------------------------------------------------------------------------- /lib/bean/err_options.dart: -------------------------------------------------------------------------------- 1 | ///需要的请求错误数据类 2 | class ErrOptions { 3 | int? id; 4 | String? errorMsg; 5 | ErrOptions({ 6 | this.id, 7 | this.errorMsg, 8 | }); 9 | } 10 | -------------------------------------------------------------------------------- /lib/bean/net_options.dart: -------------------------------------------------------------------------------- 1 | import 'err_options.dart'; 2 | import 'req_options.dart'; 3 | import 'res_options.dart'; 4 | 5 | ///需要的网络数据类 6 | class NetOptions { 7 | ReqOptions? reqOptions; 8 | ResOptions? resOptions; 9 | ErrOptions? errOptions; 10 | NetOptions({ 11 | this.reqOptions, 12 | this.resOptions, 13 | this.errOptions, 14 | }); 15 | } 16 | 17 | ///判断返回数据是否异常 18 | typedef ResError = bool Function(NetOptions res); 19 | -------------------------------------------------------------------------------- /lib/bean/req_options.dart: -------------------------------------------------------------------------------- 1 | ///需要的请求数据类 2 | class ReqOptions { 3 | int? id; 4 | String? url; 5 | String? method; 6 | String? contentType; 7 | DateTime? requestTime; 8 | Map? params; 9 | dynamic data; 10 | Map? headers; 11 | ReqOptions({ 12 | this.id, 13 | this.url, 14 | this.method, 15 | this.contentType, 16 | this.requestTime, 17 | this.headers, 18 | this.params, 19 | this.data, 20 | }); 21 | } 22 | -------------------------------------------------------------------------------- /lib/bean/res_options.dart: -------------------------------------------------------------------------------- 1 | ///需要的返回数据类 2 | class ResOptions { 3 | int? id; 4 | dynamic data; 5 | int? statusCode; 6 | DateTime? responseTime; //ms 7 | int? duration; //ms 8 | Map>? headers; 9 | ResOptions({ 10 | this.id, 11 | this.data, 12 | this.statusCode, 13 | this.responseTime, 14 | this.duration, 15 | this.headers, 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /lib/dio_log.dart: -------------------------------------------------------------------------------- 1 | library dio_log; 2 | 3 | export 'package:dio_log/widget/json_view.dart'; 4 | 5 | export 'http_log_list_widget.dart'; 6 | export 'interceptor/dio_log_interceptor.dart'; 7 | export 'overlay_draggable_button.dart'; 8 | export 'page/log_error_widget.dart'; 9 | export 'page/log_request_widget.dart'; 10 | export 'page/log_response_widget.dart'; 11 | export 'utils/copy_clipboard.dart'; 12 | export 'utils/json_utils.dart'; 13 | export 'utils/log_pool_manager.dart'; 14 | export 'utils/time_utils.dart'; 15 | export 'utils/url_utils.dart'; 16 | -------------------------------------------------------------------------------- /lib/http_log_list_widget.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | import 'package:dio_log/widget/input_dialog.dart'; 4 | import 'package:flutter/material.dart'; 5 | 6 | import 'bean/net_options.dart'; 7 | import 'dio_log.dart'; 8 | import 'page/log_widget.dart'; 9 | 10 | ///网络请求日志列表 11 | class HttpLogListWidget extends StatefulWidget { 12 | @override 13 | _HttpLogListWidgetState createState() => _HttpLogListWidgetState(); 14 | } 15 | 16 | class _HttpLogListWidgetState extends State { 17 | LinkedHashMap? logMap; 18 | List? keys; 19 | SearchModel? searchModel; 20 | @override 21 | Widget build(BuildContext context) { 22 | logMap = LogPoolManager.getInstance().logMap; 23 | if (searchModel != null) { 24 | keys = LogPoolManager.getInstance().keys.where((element) { 25 | var model = logMap![element]!; 26 | var req = model.reqOptions; 27 | var urlValid = req!.url!.contains(searchModel!.url); 28 | var res = model.resOptions; 29 | var statusValid; 30 | if (searchModel?.status == 0) { 31 | statusValid = true; 32 | } else { 33 | statusValid = res?.statusCode == searchModel?.status; 34 | } 35 | var isError = LogPoolManager.getInstance().isError(model); 36 | var duration = searchModel?.duration ?? 0; 37 | var durationType = searchModel?.durationType ?? 0; 38 | var isDuration = true; 39 | if (durationType == 0) { 40 | isDuration = (model.resOptions?.duration ?? 0) > duration; 41 | } 42 | if (durationType == 1) { 43 | isDuration = (model.resOptions?.duration ?? 0) < duration; 44 | } 45 | return urlValid && statusValid && isError == searchModel?.isError && isDuration; 46 | }).toList(); 47 | } else { 48 | keys = LogPoolManager.getInstance().keys; 49 | } 50 | 51 | final theme = Theme.of(context); 52 | return Scaffold( 53 | appBar: AppBar( 54 | title: Text( 55 | 'Logs', 56 | style: theme.textTheme.bodySmall!.copyWith(fontWeight: FontWeight.bold), 57 | ), 58 | backgroundColor: theme.scaffoldBackgroundColor, 59 | elevation: 1.0, 60 | iconTheme: theme.iconTheme, 61 | actions: [ 62 | InkWell( 63 | onTap: () async { 64 | searchModel = SearchModel.noCondition(); 65 | setState(() {}); 66 | snackBar(context, 'show All Logs'); 67 | }, 68 | child: Align( 69 | child: Padding( 70 | padding: const EdgeInsets.all(8.0), 71 | child: Text( 72 | 'show All', 73 | style: theme.textTheme.bodySmall!.copyWith(fontWeight: FontWeight.bold), 74 | ), 75 | ), 76 | ), 77 | ), 78 | InkWell( 79 | onTap: () async { 80 | searchModel = await showInputDialog(context); 81 | setState(() {}); 82 | snackBar(context, 'Filtered by condition'); 83 | }, 84 | child: Icon(Icons.search), 85 | ), 86 | InkWell( 87 | onTap: () { 88 | if (debugBtnIsShow()) { 89 | dismissDebugBtn(); 90 | } else { 91 | showDebugBtn(context); 92 | } 93 | setState(() {}); 94 | }, 95 | child: Container( 96 | padding: EdgeInsets.symmetric(horizontal: 8), 97 | child: Align( 98 | child: Text( 99 | debugBtnIsShow() ? 'close overlay' : 'open overlay', 100 | style: theme.textTheme.bodySmall!.copyWith(fontWeight: FontWeight.bold), 101 | ), 102 | ), 103 | ), 104 | ), 105 | InkWell( 106 | onTap: () { 107 | LogPoolManager.getInstance().clear(); 108 | setState(() {}); 109 | snackBar(context, 'clear Logs'); 110 | }, 111 | child: Container( 112 | padding: EdgeInsets.symmetric(horizontal: 8), 113 | child: Align( 114 | child: Text( 115 | 'clear', 116 | style: theme.textTheme.bodySmall!.copyWith(fontWeight: FontWeight.bold), 117 | ), 118 | ), 119 | ), 120 | ), 121 | ], 122 | ), 123 | body: logMap?.isEmpty ?? true 124 | ? Center( 125 | child: Text('no request log'), 126 | ) 127 | : ListView.builder( 128 | reverse: false, 129 | itemCount: keys!.length, 130 | itemBuilder: (BuildContext context, int index) { 131 | NetOptions item = logMap![keys![index]]!; 132 | return _buildItem(item); 133 | }, 134 | ), 135 | ); 136 | } 137 | 138 | ///构建请求的简易信息 139 | Widget _buildItem(NetOptions item) { 140 | var resOpt = item.resOptions; 141 | var reqOpt = item.reqOptions!; 142 | 143 | ///格式化请求时间 144 | var requestTime = getTimeStr1(reqOpt.requestTime!); 145 | 146 | Color? textColor = 147 | LogPoolManager.getInstance().isError(item) ? Colors.red : Theme.of(context).textTheme.bodyLarge!.color; 148 | return Card( 149 | margin: EdgeInsets.all(8), 150 | elevation: 6, 151 | child: InkWell( 152 | onTap: () { 153 | Navigator.push(context, MaterialPageRoute(builder: (context) { 154 | return LogWidget(item); 155 | })); 156 | }, 157 | child: Container( 158 | width: double.infinity, 159 | padding: EdgeInsets.all(8.0), 160 | child: Column( 161 | crossAxisAlignment: CrossAxisAlignment.start, 162 | children: [ 163 | Text( 164 | 'url: ${reqOpt.url}', 165 | style: TextStyle( 166 | color: textColor, 167 | ), 168 | ), 169 | Divider(height: 2), 170 | Text( 171 | 'status: ${resOpt?.statusCode}', 172 | style: TextStyle( 173 | color: textColor, 174 | ), 175 | ), 176 | Divider(height: 2), 177 | Text( 178 | 'requestTime: $requestTime duration: ${resOpt?.duration ?? 0}ms', 179 | style: TextStyle( 180 | color: textColor, 181 | ), 182 | ), 183 | ], 184 | ), 185 | ), 186 | ), 187 | ); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /lib/interceptor/dio_log_interceptor.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio/dio.dart'; 2 | import 'package:dio_log/bean/err_options.dart'; 3 | import 'package:dio_log/bean/net_options.dart'; 4 | import 'package:dio_log/bean/req_options.dart'; 5 | import 'package:dio_log/bean/res_options.dart'; 6 | import 'dart:developer'; 7 | import '../dio_log.dart'; 8 | 9 | ///log日志的处理类 10 | class DioLogInterceptor implements Interceptor { 11 | LogPoolManager? logManage; 12 | 13 | ///是否打印日志到控制台 14 | static bool enablePrintLog = false; 15 | 16 | DioLogInterceptor() { 17 | logManage = LogPoolManager.getInstance(); 18 | } 19 | 20 | ///错误数据采集 21 | @override 22 | Future onError(DioException err, ErrorInterceptorHandler handler) async { 23 | var errOptions = ErrOptions(); 24 | errOptions.id = err.requestOptions.hashCode; 25 | errOptions.errorMsg = err.toString(); 26 | //onResponse(err.response); 27 | logManage?.onError(errOptions); 28 | if (err.response != null) saveResponse(err.response!); 29 | return handler.next(err); 30 | } 31 | 32 | ///请求体数据采集 33 | @override 34 | void onRequest(RequestOptions options, RequestInterceptorHandler handler) { 35 | var reqOpt = ReqOptions(); 36 | reqOpt.id = options.hashCode; 37 | reqOpt.url = options.uri.toString(); 38 | reqOpt.method = options.method; 39 | reqOpt.contentType = options.contentType.toString(); 40 | reqOpt.requestTime = DateTime.now(); 41 | reqOpt.params = options.queryParameters; 42 | reqOpt.data = options.data; 43 | reqOpt.headers = options.headers; 44 | logManage?.onRequest(reqOpt); 45 | return handler.next(options); 46 | } 47 | 48 | ///响应体数据采集 49 | @override 50 | Future onResponse( 51 | Response response, ResponseInterceptorHandler handler) async { 52 | saveResponse(response); 53 | return handler.next(response); 54 | } 55 | 56 | void saveResponse(Response response) { 57 | var resOpt = ResOptions(); 58 | resOpt.id = response.requestOptions.hashCode; 59 | resOpt.responseTime = DateTime.now(); 60 | resOpt.statusCode = response.statusCode ?? 0; 61 | resOpt.data = response.data; 62 | resOpt.headers = response.headers.map; 63 | logManage?.onResponse(resOpt); 64 | if (enablePrintLog) { 65 | NetOptions logNp = 66 | LogPoolManager.getInstance().logMap[resOpt.id.toString()]!; 67 | log('request: url:${logNp.reqOptions?.url}'); 68 | log('request: method:${logNp.reqOptions?.method}'); 69 | log('request: params:${logNp.reqOptions?.params}'); 70 | log('request: data:${logNp.reqOptions?.data}'); 71 | log('request: duration:${getTimeStr1(logNp.reqOptions!.requestTime!)}'); 72 | log('response: ${toJson(logNp.resOptions?.data)}'); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /lib/overlay_draggable_button.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | import 'dio_log.dart'; 4 | 5 | /// 6 | /// Created by rich on 2019-07-31 7 | /// 8 | 9 | OverlayEntry? itemEntry; 10 | 11 | ///显示全局悬浮调试按钮 12 | showDebugBtn(BuildContext context, {Widget? button, Color? btnColor}) async { 13 | ///widget第一次渲染完成 14 | try { 15 | await Future.delayed(Duration(milliseconds: 500)); 16 | dismissDebugBtn(); 17 | itemEntry = OverlayEntry( 18 | builder: (BuildContext context) => 19 | button ?? DraggableButtonWidget(btnColor: btnColor)); 20 | 21 | ///显示悬浮menu 22 | Overlay.of(context).insert(itemEntry!); 23 | } catch (e) { 24 | print('$e'); 25 | } 26 | } 27 | 28 | ///关闭悬浮按钮 29 | dismissDebugBtn() { 30 | itemEntry?.remove(); 31 | itemEntry = null; 32 | } 33 | 34 | ///悬浮按钮展示状态 35 | bool debugBtnIsShow() { 36 | return !(itemEntry == null); 37 | } 38 | 39 | class DraggableButtonWidget extends StatefulWidget { 40 | final String title; 41 | final Function? onTap; 42 | final double btnSize; 43 | final Color? btnColor; 44 | 45 | DraggableButtonWidget({ 46 | this.title = 'http log', 47 | this.onTap, 48 | this.btnSize = 66, 49 | this.btnColor, 50 | }); 51 | 52 | @override 53 | _DraggableButtonWidgetState createState() => _DraggableButtonWidgetState(); 54 | } 55 | 56 | class _DraggableButtonWidgetState extends State { 57 | double left = 30; 58 | double top = 100; 59 | late double screenWidth; 60 | late double screenHeight; 61 | 62 | @override 63 | void initState() { 64 | super.initState(); 65 | } 66 | 67 | @override 68 | Widget build(BuildContext context) { 69 | screenWidth = MediaQuery.of(context).size.width; 70 | screenHeight = MediaQuery.of(context).size.height; 71 | 72 | ///默认点击事件 73 | var tap = () { 74 | Navigator.of(context).push( 75 | MaterialPageRoute( 76 | builder: (context) => HttpLogListWidget(), 77 | ), 78 | ); 79 | }; 80 | Widget w; 81 | Color primaryColor = widget.btnColor ?? Theme.of(context).primaryColor; 82 | primaryColor = primaryColor.withOpacity(0.6); 83 | w = GestureDetector( 84 | onTap: widget.onTap as void Function()? ?? tap, 85 | onPanUpdate: _dragUpdate, 86 | child: Container( 87 | width: widget.btnSize, 88 | height: widget.btnSize, 89 | color: primaryColor, 90 | child: Center( 91 | child: Text( 92 | widget.title, 93 | textAlign: TextAlign.center, 94 | style: TextStyle( 95 | fontSize: 14, 96 | color: Colors.white, 97 | fontWeight: FontWeight.normal, 98 | decoration: TextDecoration.none, 99 | ), 100 | ), 101 | ), 102 | ), 103 | ); 104 | 105 | ///圆形 106 | w = ClipRRect( 107 | borderRadius: BorderRadius.circular(widget.btnSize / 2), 108 | child: w, 109 | ); 110 | 111 | ///计算偏移量限制 112 | if (left < 1) { 113 | left = 1; 114 | } 115 | if (left > screenWidth - widget.btnSize) { 116 | left = screenWidth - widget.btnSize; 117 | } 118 | 119 | if (top < 1) { 120 | top = 1; 121 | } 122 | if (top > screenHeight - widget.btnSize) { 123 | top = screenHeight - widget.btnSize; 124 | } 125 | w = Container( 126 | alignment: Alignment.topLeft, 127 | margin: EdgeInsets.only(left: left, top: top), 128 | child: w, 129 | ); 130 | return w; 131 | } 132 | 133 | _dragUpdate(DragUpdateDetails detail) { 134 | Offset offset = detail.delta; 135 | left = left + offset.dx; 136 | top = top + offset.dy; 137 | setState(() {}); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /lib/page/log_error_widget.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio_log/bean/net_options.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | ///错误信息展示页面 5 | class LogErrorWidget extends StatefulWidget { 6 | final NetOptions netOptions; 7 | 8 | LogErrorWidget(this.netOptions); 9 | 10 | @override 11 | _LogErrorWidgetState createState() => _LogErrorWidgetState(); 12 | } 13 | 14 | class _LogErrorWidgetState extends State 15 | with AutomaticKeepAliveClientMixin { 16 | @override 17 | Widget build(BuildContext context) { 18 | super.build(context); 19 | return Container( 20 | height: double.infinity, 21 | child: Center( 22 | child: Text(widget.netOptions.errOptions?.errorMsg ?? 'no error'), 23 | ), 24 | ); 25 | } 26 | 27 | @override 28 | bool get wantKeepAlive => true; 29 | } 30 | -------------------------------------------------------------------------------- /lib/page/log_request_widget.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:dio/dio.dart'; 4 | import 'package:dio_log/bean/net_options.dart'; 5 | import 'package:flutter/material.dart'; 6 | 7 | import '../dio_log.dart'; 8 | 9 | class LogRequestWidget extends StatefulWidget { 10 | final NetOptions netOptions; 11 | 12 | LogRequestWidget(this.netOptions); 13 | 14 | @override 15 | _LogRequestWidgetState createState() => _LogRequestWidgetState(); 16 | } 17 | 18 | class _LogRequestWidgetState extends State with AutomaticKeepAliveClientMixin { 19 | late TextEditingController _urlController; 20 | late TextEditingController _cookieController; 21 | late TextEditingController _paramController; 22 | late TextEditingController _bodyController; 23 | bool reqFail = false; 24 | @override 25 | void initState() { 26 | _urlController = TextEditingController(); 27 | _cookieController = TextEditingController(); 28 | _paramController = TextEditingController(); 29 | _bodyController = TextEditingController(); 30 | super.initState(); 31 | } 32 | 33 | @override 34 | void dispose() { 35 | _bodyController.dispose(); 36 | _paramController.dispose(); 37 | _urlController.dispose(); 38 | _cookieController.dispose(); 39 | super.dispose(); 40 | } 41 | 42 | @override 43 | Widget build(BuildContext context) { 44 | super.build(context); 45 | var reqOpt = widget.netOptions.reqOptions!; 46 | var resOpt = widget.netOptions.resOptions; 47 | 48 | ///格式化请求时间 49 | var requestTime = getTimeStr(reqOpt.requestTime!); 50 | 51 | ///格式化返回时间 52 | var responseTime = getTimeStr(resOpt?.responseTime ?? reqOpt.requestTime!); 53 | return Padding( 54 | padding: const EdgeInsets.all(8.0), 55 | child: SingleChildScrollView( 56 | child: Column( 57 | crossAxisAlignment: CrossAxisAlignment.start, 58 | children: [ 59 | Text( 60 | 'Tip: long press a key to copy the value to the clipboard', 61 | style: TextStyle(fontSize: 10, color: Colors.red), 62 | ), 63 | Row( 64 | children: [ 65 | ElevatedButton( 66 | onPressed: () { 67 | copyClipboard( 68 | context, 69 | 'url:${reqOpt.url}\nmethod:${reqOpt.method}\nrequestTime:$requestTime\nresponseTime:$responseTime\n' 70 | 'duration:${resOpt?.duration ?? 0}ms\n${dataFormat(reqOpt.data)}' 71 | '\nparams:${toJson(reqOpt.params)}\nheader:${reqOpt.headers}'); 72 | }, 73 | child: Text('copy all'), 74 | ), 75 | SizedBox(width: 12), 76 | ElevatedButton( 77 | onPressed: () { 78 | copyClipboard(context, 'url:${reqOpt.url}'); 79 | }, 80 | child: Text('copy url'), 81 | ), 82 | ], 83 | ), 84 | _buildKeyValue('url', reqOpt.url), 85 | _buildKeyValue('method', reqOpt.method), 86 | _buildKeyValue('requestTime', requestTime), 87 | _buildKeyValue('responseTime', responseTime), 88 | _buildKeyValue('duration', '${resOpt?.duration ?? 0}ms'), 89 | _buildParam(reqOpt.data), 90 | _buildJsonView('params', reqOpt.params), 91 | _buildJsonView('header', reqOpt.headers), 92 | ], 93 | ), 94 | ), 95 | ); 96 | } 97 | 98 | ///构建json树的展示 99 | Widget _buildJsonView(key, json) { 100 | return Column( 101 | crossAxisAlignment: CrossAxisAlignment.start, 102 | children: [ 103 | _getDefText('$key:'), 104 | JsonView(json: json), 105 | ], 106 | ); 107 | } 108 | 109 | ///构建子节点的展示 110 | Widget _buildKeyValue(k, v) { 111 | Widget w = _getDefText('$k:${v is String ? '$v' : v?.toString() ?? null}'); 112 | if (k != null) { 113 | w = GestureDetector( 114 | behavior: HitTestBehavior.translucent, 115 | onLongPress: () { 116 | copyClipboard(context, v); 117 | }, 118 | child: Padding( 119 | padding: EdgeInsets.symmetric(vertical: 2), 120 | child: w, 121 | ), 122 | ); 123 | } 124 | return w; 125 | } 126 | 127 | ///默认的文本大小 128 | Widget _getDefText(String str) { 129 | return SelectableText(str, style: TextStyle(fontSize: 15)); 130 | } 131 | 132 | @override 133 | bool get wantKeepAlive => true; 134 | 135 | Map? formDataMap; 136 | Widget _buildParam(dynamic data) { 137 | if (data is Map) { 138 | return _buildJsonView('body', data); 139 | } else if (data is FormData) { 140 | formDataMap = Map() 141 | ..addEntries(data.fields) 142 | ..addEntries(data.files); 143 | return _getDefText('formData:${map2Json(formDataMap)}'); 144 | } else if (data is String) { 145 | try { 146 | var decodedMap = json.decode(data); 147 | return _buildJsonView('body', decodedMap); 148 | } catch (e) { 149 | return Text('body: $data'); 150 | } 151 | } else { 152 | return SizedBox(); 153 | } 154 | } 155 | 156 | String dataFormat(dynamic data) { 157 | if (data is FormData) { 158 | return 'formData:${map2Json(formDataMap)}'; 159 | } else { 160 | return 'body:${toJson(data)}'; 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /lib/page/log_response_widget.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio_log/bean/net_options.dart'; 2 | import 'package:dio_log/dio_log.dart'; 3 | import 'package:flutter/material.dart'; 4 | 5 | class LogResponseWidget extends StatefulWidget { 6 | final NetOptions netOptions; 7 | 8 | LogResponseWidget(this.netOptions); 9 | 10 | @override 11 | _LogResponseWidgetState createState() => _LogResponseWidgetState(); 12 | } 13 | 14 | class _LogResponseWidgetState extends State 15 | with AutomaticKeepAliveClientMixin { 16 | bool isShowAll = false; 17 | double fontSize = 14; 18 | @override 19 | Widget build(BuildContext context) { 20 | super.build(context); 21 | var response = widget.netOptions.resOptions; 22 | var json = response?.data ?? 'no response'; 23 | return SingleChildScrollView( 24 | child: Column( 25 | children: [ 26 | Row( 27 | children: [ 28 | SizedBox(width: 10), 29 | Text(isShowAll ? 'shrink all' : 'expand all'), 30 | Switch( 31 | value: isShowAll, 32 | onChanged: (check) { 33 | isShowAll = check; 34 | 35 | setState(() {}); 36 | }, 37 | ), 38 | Expanded( 39 | child: Slider( 40 | value: fontSize, 41 | max: 30, 42 | min: 1, 43 | onChanged: (v) { 44 | fontSize = v; 45 | setState(() {}); 46 | }, 47 | ), 48 | ), 49 | ], 50 | ), 51 | Text( 52 | 'Tip: long press a key to copy the value to the clipboard', 53 | style: TextStyle( 54 | fontSize: 10, 55 | color: Colors.red, 56 | ), 57 | ), 58 | _buildJsonView('headers:', response?.headers), 59 | _buildJsonView('response.data:', json), 60 | ], 61 | )); 62 | } 63 | 64 | ///构建json树的展示 65 | Widget _buildJsonView(key, json) { 66 | return Column( 67 | crossAxisAlignment: CrossAxisAlignment.start, 68 | children: [ 69 | ElevatedButton( 70 | onPressed: () { 71 | copyClipboard(context, toJson(json)); 72 | }, 73 | child: Text('copy json'), 74 | ), 75 | Text( 76 | '$key', 77 | style: TextStyle( 78 | fontSize: fontSize, 79 | ), 80 | ), 81 | JsonView( 82 | json: json, 83 | isShowAll: isShowAll, 84 | fontSize: fontSize, 85 | ), 86 | ], 87 | ); 88 | } 89 | 90 | @override 91 | bool get wantKeepAlive => true; 92 | } 93 | -------------------------------------------------------------------------------- /lib/page/log_widget.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio_log/bean/net_options.dart'; 2 | import 'package:dio_log/dio_log.dart'; 3 | import 'package:flutter/material.dart'; 4 | 5 | ///网络请求详情 6 | class LogWidget extends StatefulWidget { 7 | final NetOptions netOptions; 8 | 9 | LogWidget(this.netOptions); 10 | 11 | @override 12 | _LogWidgetState createState() => _LogWidgetState(); 13 | } 14 | 15 | class _LogWidgetState extends State 16 | with SingleTickerProviderStateMixin { 17 | final List tabs = [ 18 | new Tab(text: "request"), 19 | new Tab(text: "response"), 20 | ]; 21 | 22 | PageController? _pageController; 23 | 24 | int currentIndex = 0; 25 | 26 | @override 27 | void initState() { 28 | _pageController = PageController(initialPage: 0); 29 | super.initState(); 30 | } 31 | 32 | @override 33 | void dispose() { 34 | _pageController!.dispose(); 35 | super.dispose(); 36 | } 37 | 38 | @override 39 | Widget build(BuildContext context) { 40 | final theme = Theme.of(context); 41 | return Scaffold( 42 | appBar: AppBar( 43 | title: Text( 44 | widget.netOptions.reqOptions!.url!, 45 | style: TextStyle(fontSize: 11), 46 | ), 47 | backgroundColor: theme.scaffoldBackgroundColor, 48 | elevation: 1.0, 49 | iconTheme: theme.iconTheme, 50 | ), 51 | body: PageView.builder( 52 | controller: _pageController, 53 | onPageChanged: _onPageChanged, 54 | itemCount: 3, 55 | itemBuilder: (BuildContext context, int index) { 56 | if (index == 0) { 57 | return LogRequestWidget(widget.netOptions); 58 | } else if (index == 1) { 59 | return LogResponseWidget(widget.netOptions); 60 | } else { 61 | return LogErrorWidget(widget.netOptions); 62 | } 63 | }, 64 | ), 65 | bottomNavigationBar: BottomNavigationBar( 66 | currentIndex: currentIndex, 67 | onTap: _bottomTap, 68 | items: [ 69 | BottomNavigationBarItem( 70 | icon: Icon(Icons.cloud_upload_outlined), label: 'Request'), 71 | BottomNavigationBarItem( 72 | icon: Icon(Icons.cloud_download_outlined), label: 'Response'), 73 | BottomNavigationBarItem( 74 | icon: Icon(Icons.error_outline), label: 'Error'), 75 | ], 76 | ), 77 | ); 78 | } 79 | 80 | void _onPageChanged(int value) { 81 | if (mounted) { 82 | setState(() { 83 | currentIndex = value; 84 | }); 85 | } 86 | } 87 | 88 | void _bottomTap(int value) { 89 | _pageController!.animateToPage(value, 90 | duration: Duration(milliseconds: 300), curve: Curves.ease); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /lib/theme/style.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | class Style { 4 | static TextStyle defText = TextStyle( 5 | fontSize: 14, 6 | color: Colors.black, 7 | ); 8 | static TextStyle defTextBold = TextStyle( 9 | fontSize: 14, 10 | color: Colors.black, 11 | fontWeight: FontWeight.bold, 12 | ); 13 | static Color textColor = Colors.black; 14 | static Color errorTextColor = Colors.black; 15 | static Color btnColor = Colors.blue; 16 | } 17 | -------------------------------------------------------------------------------- /lib/utils/copy_clipboard.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:flutter/services.dart'; 3 | 4 | ///复制到粘贴板 5 | copyClipboard(BuildContext context, String? value) { 6 | snackBar(context,'$value\n\n copy success to clipboard'); 7 | Clipboard.setData(ClipboardData(text: value ?? 'null')); 8 | } 9 | 10 | snackBar(BuildContext context, String? value){ 11 | var snackBar = 12 | SnackBar(content: Text('$value')); 13 | ScaffoldMessenger.of(context).showSnackBar(snackBar); 14 | } -------------------------------------------------------------------------------- /lib/utils/json_utils.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | ///返回json格式的String 4 | toJson(dynamic data) { 5 | var je = JsonEncoder.withIndent(' '); 6 | var json = je.convert(data); 7 | return json; 8 | } 9 | 10 | ///返回json格式的String 11 | String map2Json(Map? map) { 12 | if (map == null) { 13 | return ''; 14 | } 15 | StringBuffer sb = StringBuffer(); 16 | sb.writeln('{'); 17 | map.forEach((key, value) => sb.writeln('$key:$value')); 18 | sb.write('}'); 19 | return sb.toString(); 20 | } 21 | -------------------------------------------------------------------------------- /lib/utils/log_pool_manager.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | import 'package:dio_log/bean/err_options.dart'; 4 | import 'package:dio_log/bean/net_options.dart'; 5 | import 'package:dio_log/bean/req_options.dart'; 6 | import 'package:dio_log/bean/res_options.dart'; 7 | 8 | ///log管理 9 | class LogPoolManager { 10 | ///请求日志存储 11 | late LinkedHashMap logMap; 12 | 13 | late List keys; 14 | 15 | ///存储请求最大数 16 | int maxCount = 200; 17 | 18 | ResError isError = 19 | (res) => res.errOptions != null || res.resOptions?.statusCode == null; 20 | 21 | static LogPoolManager? _instance; 22 | 23 | LogPoolManager._singleton() { 24 | logMap = LinkedHashMap(); 25 | keys = []; 26 | } 27 | 28 | static LogPoolManager getInstance() { 29 | if (_instance == null) { 30 | _instance = LogPoolManager._singleton(); 31 | } 32 | return _instance!; 33 | } 34 | 35 | void onError(ErrOptions err) { 36 | var key = err.id.toString(); 37 | if (logMap.containsKey(key)) { 38 | logMap.update(key, (value) { 39 | value.errOptions = err; 40 | return value; 41 | }); 42 | } 43 | } 44 | 45 | void onRequest(ReqOptions options) { 46 | if (logMap.length >= maxCount) { 47 | logMap.remove(keys.last); 48 | keys.removeLast(); 49 | } 50 | var key = options.id.toString(); 51 | keys.insert(0, key); 52 | logMap.putIfAbsent(key, () => NetOptions(reqOptions: options)); 53 | } 54 | 55 | void onResponse(ResOptions response) { 56 | var key = response.id.toString(); 57 | if (logMap.containsKey(key)) { 58 | logMap.update(key, (value) { 59 | response.duration = response.responseTime!.millisecondsSinceEpoch - 60 | value.reqOptions!.requestTime!.millisecondsSinceEpoch; 61 | value.resOptions = response; 62 | return value; 63 | }); 64 | } 65 | } 66 | 67 | ///日志清除 68 | void clear() { 69 | logMap.clear(); 70 | keys.clear(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /lib/utils/time_utils.dart: -------------------------------------------------------------------------------- 1 | ///format(2018.09.08 11:22:333) 2 | String getTimeStr(DateTime dateTime) { 3 | return "${twoNum(dateTime.year)}.${twoNum(dateTime.month)}.${twoNum(dateTime.day)}-" 4 | "${twoNum(dateTime.hour)}:${twoNum(dateTime.minute)}:${twoNum(dateTime.second)}:${dateTime.millisecond}"; 5 | } 6 | 7 | ///format(11:22:333) 8 | String getTimeStr1(DateTime dateTime) { 9 | return "${twoNum(dateTime.hour)}:${twoNum(dateTime.minute)}:${twoNum(dateTime.second)}"; 10 | } 11 | 12 | ///转成两位数 13 | String twoNum(int num) { 14 | return num > 9 ? num.toString() : "0$num"; 15 | } 16 | -------------------------------------------------------------------------------- /lib/utils/url_utils.dart: -------------------------------------------------------------------------------- 1 | ///拼接实际请求链接 2 | String getRealUrl(String url, Map params) { 3 | StringBuffer str = StringBuffer(url); 4 | if (params.length as bool? ?? 0 > 0) { 5 | str.write('?'); 6 | var hasAnd = false; 7 | params.forEach((key, value) { 8 | if (hasAnd) { 9 | hasAnd = true; 10 | str.write('&'); 11 | } 12 | str.write('$key=$value'); 13 | }); 14 | } 15 | return str.toString(); 16 | } 17 | -------------------------------------------------------------------------------- /lib/widget/input_dialog.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio_log/utils/copy_clipboard.dart'; 2 | import 'package:flutter/material.dart'; 3 | 4 | class SearchModel { 5 | String url; 6 | int status; 7 | // String time; 8 | // int timeType; //0>,1< 9 | int duration; 10 | int durationType; //0>,1< 11 | bool isError; 12 | 13 | SearchModel( 14 | this.url, 15 | this.status, 16 | // this.time, 17 | // this.timeType, 18 | this.duration, 19 | this.durationType, 20 | this.isError, 21 | ); 22 | 23 | SearchModel.noCondition({ 24 | this.url = '', 25 | this.status = 0, 26 | // this.time, 27 | // this.timeType, 28 | this.duration = 0, 29 | this.durationType = 0, 30 | this.isError = false, 31 | }); 32 | } 33 | 34 | Future showInputDialog(BuildContext context) async { 35 | TextEditingController _urlTextFieldController = TextEditingController(); 36 | TextEditingController _statusTextFieldController = TextEditingController(); 37 | TextEditingController _duration1TextFieldController = TextEditingController(); 38 | TextEditingController _durationTextFieldController = TextEditingController(); 39 | ValueNotifier valueListenable = ValueNotifier(false); 40 | return await showDialog( 41 | context: context, 42 | builder: (context1) { 43 | return AlertDialog( 44 | title: Text('Search Key'), 45 | content: Column( 46 | mainAxisSize: MainAxisSize.min, 47 | children: [ 48 | TextField( 49 | controller: _urlTextFieldController, 50 | decoration: InputDecoration(hintText: "url:"), 51 | ), 52 | TextField( 53 | controller: _statusTextFieldController, 54 | decoration: InputDecoration(hintText: "status:"), 55 | ), 56 | TextField( 57 | controller: _duration1TextFieldController, 58 | decoration: InputDecoration(hintText: ">duration(ms):"), 59 | ), 60 | Row( 61 | children: [ 62 | Expanded( 63 | child: TextField( 64 | controller: _durationTextFieldController, 65 | decoration: InputDecoration(hintText: "[ 89 | TextButton( 90 | child: Text('CANCEL'), 91 | onPressed: () { 92 | Navigator.of(context).pop(null); 93 | }, 94 | ), 95 | TextButton( 96 | child: Text('OK'), 97 | onPressed: () { 98 | var duration1 = _duration1TextFieldController.text; 99 | var duration = _durationTextFieldController.text; 100 | var du = 0; 101 | var duType = 0; 102 | if (duration.isNotEmpty && duration1.isNotEmpty) { 103 | return snackBar(context, 'duration> and duration< not both exist'); 104 | } 105 | if (duration1.isNotEmpty) { 106 | du = int.tryParse(duration1) ?? 0; 107 | duType = 0; 108 | } 109 | if (duration.isNotEmpty) { 110 | du = int.parse(duration) ?? 0; 111 | duType = 1; 112 | } 113 | var sm = SearchModel( 114 | _urlTextFieldController.text, 115 | int.tryParse(_statusTextFieldController.text) ?? 0, 116 | du, 117 | duType, 118 | valueListenable.value, 119 | ); 120 | Navigator.of(context).pop(sm); 121 | }, 122 | ), 123 | ], 124 | ); 125 | }, 126 | ); 127 | } 128 | -------------------------------------------------------------------------------- /lib/widget/json_view.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:dio_log/utils/copy_clipboard.dart'; 4 | import 'package:flutter/material.dart'; 5 | 6 | /// 7 | /// Created by rich on 2019-07-17 8 | /// 9 | 10 | class JsonView extends StatefulWidget { 11 | ///要展示的json数据 12 | final dynamic json; 13 | 14 | ///是否展开全部json 15 | final bool? isShowAll; 16 | 17 | final double fontSize; 18 | JsonView({ 19 | this.json, 20 | this.isShowAll = false, 21 | this.fontSize = 14, 22 | }); 23 | 24 | @override 25 | _JsonViewState createState() => _JsonViewState(); 26 | } 27 | 28 | class _JsonViewState extends State { 29 | Map showMap = Map(); 30 | 31 | ///当前节点编号 32 | int currentIndex = 0; 33 | 34 | @override 35 | void didUpdateWidget(JsonView oldWidget) { 36 | super.didUpdateWidget(oldWidget); 37 | if (oldWidget.isShowAll != widget.isShowAll) { 38 | _flexAll(widget.isShowAll); 39 | } 40 | } 41 | 42 | @override 43 | Widget build(BuildContext context) { 44 | currentIndex = 0; 45 | Widget w; 46 | JsonType type = getType(widget.json); 47 | if (type == JsonType.object) { 48 | w = _buildObject(widget.json); 49 | } else if (type == JsonType.array) { 50 | List? list = widget.json as List?; 51 | w = _buildArray(list, ''); 52 | } else { 53 | var je = JsonEncoder.withIndent(' '); 54 | var json = je.convert(widget.json); 55 | return _getDefText(json); 56 | } 57 | return w; 58 | } 59 | 60 | ///构建object节点的展示 61 | Widget _buildObject(Map? json, {String? key}) { 62 | List listW = []; 63 | 64 | ///增加一个节点 65 | currentIndex++; 66 | 67 | ///object节点 68 | Widget keyW; 69 | if (_isShow(currentIndex)) { 70 | keyW = _getDefText('${key == null ? '{' : '$key:{'}'); 71 | } else { 72 | keyW = _getDefText('${key == null ? '{...}' : '$key:{...}'}'); 73 | } 74 | listW.add(_wrapFlex(currentIndex, keyW)); 75 | 76 | ///object展示内容 77 | if (_isShow(currentIndex)) { 78 | List listObj = []; 79 | json!.forEach((k, v) { 80 | Widget w; 81 | JsonType type = getType(v); 82 | if (type == JsonType.object) { 83 | w = _buildObject(v, key: k); 84 | } else if (type == JsonType.array) { 85 | List list = v as List; 86 | w = _buildArray(list, k); 87 | } else { 88 | w = _buildKeyValue(v, k: k); 89 | } 90 | listObj.add(w); 91 | }); 92 | 93 | listObj.add(_getDefText('},')); 94 | 95 | ///添加缩进 96 | listW.add( 97 | Padding( 98 | padding: EdgeInsets.only(left: 16), 99 | child: Column( 100 | crossAxisAlignment: CrossAxisAlignment.start, 101 | children: listObj, 102 | ), 103 | ), 104 | ); 105 | } 106 | return Column( 107 | crossAxisAlignment: CrossAxisAlignment.start, 108 | children: listW, 109 | ); 110 | } 111 | 112 | ///构建array节点的展示 113 | Widget _buildArray(List? listJ, String key) { 114 | List listW = []; 115 | 116 | ///增加一个节点 117 | currentIndex++; 118 | 119 | ///添加key的展示 120 | Widget keyW; 121 | if (key.isEmpty) { 122 | keyW = _getDefText('['); 123 | } else if (_isShow(currentIndex)) { 124 | keyW = _getDefText('$key:['); 125 | } else { 126 | keyW = _getDefText('$key:[...]'); 127 | } 128 | 129 | ///添加key的点击事件 130 | ///添加key的展示 131 | listW.add(GestureDetector( 132 | behavior: HitTestBehavior.translucent, 133 | onLongPress: () { 134 | _copy(listJ.toString()); 135 | }, 136 | child: _wrapFlex(currentIndex, keyW), 137 | )); 138 | 139 | if (_isShow(currentIndex)) { 140 | List listArr = []; 141 | listJ!.forEach((val) { 142 | var type = getType(val); 143 | Widget w; 144 | if (type == JsonType.object) { 145 | w = _buildObject(val); 146 | } else { 147 | w = _buildKeyValue(val); 148 | } 149 | listArr.add(w); 150 | }); 151 | listArr.add(_getDefText(']')); 152 | 153 | ///添加缩进 154 | listW.add( 155 | Padding( 156 | padding: EdgeInsets.only(left: 16), 157 | child: Column( 158 | crossAxisAlignment: CrossAxisAlignment.start, 159 | children: listArr, 160 | ), 161 | ), 162 | ); 163 | } 164 | return Column( 165 | crossAxisAlignment: CrossAxisAlignment.start, 166 | children: listW, 167 | ); 168 | } 169 | 170 | ///包裹展开按钮 171 | Widget _wrapFlex(int key, Widget keyW) { 172 | return GestureDetector( 173 | behavior: HitTestBehavior.translucent, 174 | onTap: () { 175 | if (key == 0) { 176 | _flexAll(!_isShow(key)); 177 | setState(() {}); 178 | } 179 | _flexSwitch(key.toString()); 180 | }, 181 | child: Row( 182 | children: [ 183 | Transform.rotate( 184 | angle: _isShow(key) ? 0 : 3.14 * 1.5, 185 | child: Icon( 186 | Icons.expand_more, 187 | size: 12, 188 | ), 189 | ), 190 | keyW, 191 | ], 192 | ), 193 | ); 194 | } 195 | 196 | ///构建子节点的展示 197 | Widget _buildKeyValue(v, {k}) { 198 | Widget w = _getDefText( 199 | '${k ?? ''}:${v is String ? '"$v"' : v?.toString() ?? null},'); 200 | if (k != null) { 201 | w = GestureDetector( 202 | behavior: HitTestBehavior.translucent, 203 | onLongPress: () { 204 | _copy(v); 205 | }, 206 | child: w, 207 | ); 208 | } 209 | return w; 210 | } 211 | 212 | ///json节点是否展示 213 | bool _isShow(int key) { 214 | ///说明是根节点 215 | if (key == 1) return true; 216 | if (widget.isShowAll!) { 217 | return showMap[key.toString()] ?? true; 218 | } else { 219 | return showMap[key.toString()] ?? false; 220 | } 221 | } 222 | 223 | ///展开合上的切换 224 | _flexSwitch(String key) { 225 | showMap.putIfAbsent(key, () => false); 226 | showMap[key] = !showMap[key]!; 227 | setState(() {}); 228 | } 229 | 230 | ///展开合上所有 231 | _flexAll(bool? flex) { 232 | showMap.forEach((k, v) { 233 | showMap[k] = flex; 234 | }); 235 | } 236 | 237 | ///判断value值的类型 238 | JsonType getType(dynamic json) { 239 | if (json is List) { 240 | return JsonType.array; 241 | } else if (json is Map) { 242 | return JsonType.object; 243 | } else { 244 | return JsonType.str; 245 | } 246 | } 247 | 248 | ///默认的文本大小 249 | Widget _getDefText(String str) { 250 | return Text( 251 | str, 252 | style: TextStyle(fontSize: widget.fontSize), 253 | ); 254 | } 255 | 256 | ///复制到手机粘贴板 257 | _copy(value) { 258 | copyClipboard(context, value); 259 | } 260 | } 261 | 262 | enum JsonType { 263 | object, 264 | array, 265 | str, 266 | } 267 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: dio_log 2 | description: A plug-in that captures requests and views them within the application, providing functions such as request replication and JSON expansion 3 | version: 5.3.0+3 4 | homepage: https://github.com/flutterplugin/dio_log 5 | 6 | environment: 7 | sdk: '>=2.18.0 <4.0.0' 8 | 9 | dependencies: 10 | flutter: 11 | sdk: flutter 12 | dio: ^5.3.0 13 | 14 | dev_dependencies: 15 | flutter_test: 16 | sdk: flutter 17 | 18 | # For information on the generic Dart part of this file, see the 19 | # following page: https://www.dartlang.org/tools/pub/pubspec 20 | 21 | # The following section is specific to Flutter. 22 | flutter: 23 | assets: 24 | - assets/ 25 | topics: 26 | - dio 27 | - dio-log 28 | screenshots: 29 | - description: Dio log filter. 30 | path: images/log_filter.jpg 31 | # To add assets to your package, add an assets section, like this: 32 | # assets: 33 | # - images/a_dot_burr.jpeg 34 | # - images/a_dot_ham.jpeg 35 | # 36 | # For details regarding assets in packages, see 37 | # https://flutter.io/assets-and-images/#from-packages 38 | # 39 | # An image asset can refer to one or more resolution-specific "variants", see 40 | # https://flutter.io/assets-and-images/#resolution-aware. 41 | 42 | # To add custom fonts to your package, add a fonts section here, 43 | # in this "flutter" section. Each entry in this list should have a 44 | # "family" key with the font family name, and a "fonts" key with a 45 | # list giving the asset and other descriptors for the font. For 46 | # example: 47 | # fonts: 48 | # - family: Schyler 49 | # fonts: 50 | # - asset: fonts/Schyler-Regular.ttf 51 | # - asset: fonts/Schyler-Italic.ttf 52 | # style: italic 53 | # - family: Trajan Pro 54 | # fonts: 55 | # - asset: fonts/TrajanPro.ttf 56 | # - asset: fonts/TrajanPro_Bold.ttf 57 | # weight: 700 58 | # 59 | # For details regarding fonts in packages, see 60 | # https://flutter.io/custom-fonts/#from-packages 61 | --------------------------------------------------------------------------------