Flutter网络调试插件network_inspector的使用
Flutter网络调试插件network_inspector的使用
1. 整理后的内容中尽量给我提供关于“Flutter网络调试插件network_inspector的使用”的完整示例demo
import 'package:flutter/material.dart';
import 'package:network_inspector/network_inspector.dart';
import 'package:provider/provider.dart';
import 'common/navigation_service.dart';
import 'common/notification_helper.dart';
import 'presentation/controllers/main_provider.dart';
import 'presentation/pages/main_page.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
NetworkInspector.initialize();
NotificationHelper.initialize();
runApp(const ExampleApp());
}
class ExampleApp extends StatelessWidget {
const ExampleApp({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<MainProvider>(
create: (context) => MainProvider(context: context),
builder: (context, child) => MaterialApp(
title: 'Network inspector',
theme: ThemeData(
brightness: Brightness.light,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.deepPurple),
),
),
),
darkTheme: ThemeData(
brightness: Brightness.dark,
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Colors.black.withAlpha((0.3 * 2).round()),
),
),
),
),
themeMode: ThemeMode.dark,
navigatorKey: NavigationService.navigatorKey,
initialRoute: MainPage.routeName,
routes: NavigationService.routes,
),
);
}
}
2. 参考我提供的内容和示例代回答“Flutter网络调试插件network_inspector的使用”对应的内容
Easy to use, http client class debugger & logger for multiple http client.
这个包包含了一组高级函数和类,使您能够轻松地在运行时日志/调试HTTP活动。它还依赖于Dio
和Http
包。
Material 3 & Dark mode support 🆕
现在您可以使用您最喜欢的Material 3主题和暗模式,从版本1.0.4
开始。
Get Started
添加依赖项:
dependencies:
network_inspector: ^1.0.0
Initialize
初始化网络检查器,调用initialize
方法来初始化本地数据库sqlite
。确保在初始化网络检查器之前WidgetsFlutterBinding.ensureInitialized()
已经初始化了flutter binding
。
void main() {
WidgetsFlutterBinding.ensureInitialized();
NetworkInspector.initialize();
runApp(const ExampleApp());
}
Dio Users
- 添加拦截器类
DioInterceptor
用于dio客户端。 - 创建另一个网络检查器类用于
DioInterceptor
构造函数。 - 使用
onHttpFinish
作为回调当http活动完成(可以是成功或错误)。
/// Client Declaration
Dio get dioClient {
final networkInspector = NewtworkInspector();
final client = Dio()..interceptors.add(
DioInterceptor(
logIsAllowed: true, //启用/禁用整体日志记录
isConsoleLogAllowed: true, //启用/禁用仅控制台日志记录
networkInspector: networkInspector,
onHttpFinish: (hashCode, title, message) {
notifyActivity(
title: title,
message: message,
);
},
),
);
return client;
}
/// Use dio regularly
/// Every request, response & error will automatically fetched & stored by the network inspector.
/// And also if the properties of declared `DioInterceptor` is not empty, it will set every properties as default.
await dioClient.post('/test', data: {'id': 1, 'name': 'jhon folks'});
Http Users
- 添加拦截器类
HttpInterceptor
用于dio客户端。 - 初始化
Client
到客户端类,然后在HttpInterceptor
构造函数中使用client
。 - 创建另一个网络检查器类用于
DioInterceptor
构造函数。 - 使用
onHttpFinish
作为回调当http活动完成(可以是成功或错误)。
HttpInterceptor get httpClient {
final networkInspector = NewtworkInspector();
final client = Client();
final interceptor = HttpInterceptor(
logIsAllowed: true, //启用/禁用整体日志记录
isConsoleLogAllowed: true, //启用/禁用仅控制台日志记录
client: client,
baseUrl: Uri.parse('http://192.168.1.3:8000/'),
networkInspector: networkInspector,
onHttpFinish: ( hashCode, title, message {
notifyActivity(
title: title,
message: message,
);
},
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer WEKLSSS'
},
);
return interceptor;
}
/// Use http client regularly
/// Every request, response & error will automatically fetched & stored by the network inspector.
/// And also if the properties of declared `HttpInterceptor` is not empty, it will set every properties as default.
await httpClient.post(url, body: {'name': 'doodle', 'color': 'blue'});
Acessing the UI
我们可以使用常规的Navigator.push
,我们决定使用MaterialPageRoute
而不是命名路由以避免紧密耦合。
/// Use this on floating button / notification handler.
void goToActivityPage(BuildContext context) async {
await Navigator.push(
context,
MaterialPageRoute<void>(
builder: (context) => ActivityPage(),
),
);
}
Entry point from notification tap action
如果希望从通知点击动作进入http活动页面,则创建一个存储GlobalKey<NavigatorState>
的类,将全局键放入MaterialApp
中的navigatorKey
构造函数上。
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Network inspector',
theme: ThemeData(
primarySwatch: Colors.blue,
),
/// Put your navigation key into a class
/// In this case we put navigator key on
/// ```dart
/// class NavigationService{
/// static var navigatorKey = GlobalKey<NavigatorState>();
/// }
/// ```
navigatorKey: NavigationService.navigatorKey,
initialRoute: MainPage.routeName,
routes: NavigationService.routes,
);
}
然后您可以使用全局键获取上下文并调用goToActivityPage
方法并传递上下文。
/// Get the current context
var context = NavigationService.navigatorKey.currentContext;
/// Call the `goToActivityPage` method and Supply the context
goToActivityPage(context);
更多关于Flutter网络调试插件network_inspector的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络调试插件network_inspector的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter开发中,network_inspector
是一个非常有用的插件,用于调试和分析网络请求。下面是如何在Flutter项目中使用 network_inspector
的详细步骤,包括一些相关代码示例。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 network_inspector
依赖:
dependencies:
flutter:
sdk: flutter
network_inspector: ^0.x.x # 请替换为最新版本号
然后运行 flutter pub get
来获取依赖。
2. 配置应用
在你的 main.dart
文件中,你需要初始化 NetworkInspector
并将其与你的应用结合。以下是一个基本的配置示例:
import 'package:flutter/material.dart';
import 'package:network_inspector/network_inspector.dart';
import 'package:http/http.dart' as http;
void main() {
WidgetsFlutterBinding.ensureInitialized();
// 初始化 NetworkInspector
final networkInspector = NetworkInspector();
networkInspector.startServer();
// 替换默认的 http 客户端
http.Client httpClient = NetworkInspectorHttpClient(networkInspector);
runApp(MyApp(httpClient: httpClient));
}
class MyApp extends StatelessWidget {
final http.Client httpClient;
MyApp({required this.httpClient});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(httpClient: httpClient),
);
}
}
class MyHomePage extends StatefulWidget {
final http.Client httpClient;
MyHomePage({required this.httpClient});
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Network Inspector Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
try {
final response = await widget.httpClient.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
print(response.body);
} catch (e) {
print(e);
}
},
child: Text('Fetch Data'),
),
),
);
}
}
3. 启动网络调试界面
在你的应用中,你可以通过访问 http://localhost:8888
来查看网络请求的详细信息。确保你的设备或模拟器能够访问这个地址。如果你在使用真实设备调试,可能需要将设备的IP地址替换为本地主机的IP地址(例如 10.0.2.2
,具体取决于你的开发环境)。
4. 使用 NetworkInspector
提供的API(可选)
network_inspector
插件还提供了一些API,用于更细粒度地控制网络请求的捕获和过滤。例如,你可以动态地启用或禁用捕获:
// 启用捕获
networkInspector.enableCapture();
// 禁用捕获
networkInspector.disableCapture();
5. 清理资源
在应用的适当位置(例如在 dispose
方法中),你可以停止 NetworkInspector
服务器以释放资源:
@override
void dispose() {
networkInspector.stopServer();
super.dispose();
}
总结
通过上述步骤,你可以在Flutter项目中集成并使用 network_inspector
插件来调试和分析网络请求。这个插件提供了直观的网络请求界面,使得开发者能够更容易地识别和解决网络相关的问题。