Flutter调试工具插件flutter_debug_tools的使用

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

Flutter调试工具插件flutter_debug_tools的使用

简介

一套用于诊断Flutter应用UI和性能问题的交互式内置工具——无需外部工具。

Platform Pub Package License: MIT Donate

目录


特性

  • 性能叠加层: 可视化帧率(FPS)、帧渲染时间以及光栅化指标在你的应用UI上。

  • 设备详细信息叠加层: 即时查看设备特定信息(如型号、操作系统版本、屏幕大小等)直接在你的应用中。

  • 调试绘制/布局指南: 通过单个切换即可揭示小部件边界、填充、对齐方式和布局约束。

  • 图层边界显示: 实时查看图层边界以理解Flutter如何组成图层。

  • 调试日志叠加层: 不用附加到外部控制台即可跟踪日志——日志会出现在正在运行的应用顶部。

  • 重绘彩虹: 轻松检测频繁的小部件重绘。每次重绘时覆盖不同的颜色,有助于识别成本高昂的构建。

  • 拾色器: 点击任何像素以获取其颜色值——非常适合UI微调和设计验证。

  • 屏幕名称叠加层: 总是知道当前显示的是哪个路由或屏幕,对于调试导航流非常有用。

无需特殊的IDE或单独的调试模式——只需集成并根据需要切换叠加层即可。


安装

在你的pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter_debug_tools: ^1.0.0

然后运行:

flutter pub get

使用

以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:flutter_debug_tools/flutter_debug_tools.dart';
import 'package:loggy/loggy.dart';

void main() {
  // 初始化Loggy以在调试日志中显示日志
  Loggy.initLoggy(logPrinter: DebugLoggyPrinter());

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    // 添加`DebugNavigatorObserver`来观察屏幕详情
    final DebugNavigatorObserver navigatorObserver = DebugNavigatorObserver();

    // 将`FlutterDebugTools`包裹在`MaterialApp`之上以启用调试工具
    return FlutterDebugTools(
      builder: (context, showPerformanceOverlay, child) {
        return MaterialApp(
          // 控制是否显示性能叠加层
          showPerformanceOverlay: showPerformanceOverlay,
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
          // 添加`navigatorObservers`来观察屏幕详情
          navigatorObservers: [navigatorObserver],
        );
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

许可证

MIT License

Copyright (c) 2024 Abhay Maurya

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

更多关于Flutter调试工具插件flutter_debug_tools的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter调试工具插件flutter_debug_tools的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用 flutter_debug_tools 插件的示例代码和说明。flutter_debug_tools 是一个帮助 Flutter 开发者在开发过程中进行调试的插件。虽然这不是一个官方的 Flutter 插件,但假设它提供了一些常见的调试功能,比如日志记录、性能监控等。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_debug_tools: ^x.y.z  # 请替换为实际的版本号

然后运行 flutter pub get 来获取依赖。

2. 导入并使用插件

在你的 Dart 文件中导入插件,并开始使用它提供的调试功能。以下是一个简单的示例,展示如何使用日志记录和性能监控功能。

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

void main() {
  // 初始化调试工具(假设插件提供了初始化方法)
  FlutterDebugTools.instance.init();

  runApp(MyApp());
}

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();

    // 记录一条调试信息
    FlutterDebugTools.instance.log('App started');

    // 开始性能监控
    final performanceMonitor = FlutterDebugTools.instance.startPerformanceMonitor('Home Page Load');

    // 模拟一些工作
    Future.delayed(Duration(seconds: 2), () {
      // 停止性能监控并记录结果
      performanceMonitor.stop();
      FlutterDebugTools.instance.log('Home Page Loaded in ${performanceMonitor.duration.inMilliseconds}ms');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: () {
            // 记录按钮点击事件
            FlutterDebugTools.instance.log('Button clicked');

            // 模拟一些异步操作
            Future.delayed(Duration(seconds: 1), () {
              // 记录异步操作完成
              FlutterDebugTools.instance.log('Async operation completed');
            });
          },
          child: Text('Click Me'),
        ),
      ],
    );
  }
}

3. 插件假设功能

请注意,上述代码假设 flutter_debug_tools 插件提供了以下功能:

  • FlutterDebugTools.instance.init(): 初始化调试工具。
  • FlutterDebugTools.instance.log(String message): 记录调试信息。
  • FlutterDebugTools.instance.startPerformanceMonitor(String description): 开始性能监控并返回一个 PerformanceMonitor 对象。
  • performanceMonitor.stop(): 停止性能监控。
  • performanceMonitor.duration: 获取性能监控的持续时间。

4. 运行和调试

运行你的 Flutter 应用,并在控制台中查看调试信息和性能监控结果。这些工具将帮助你更好地理解和调试你的应用。

注意事项

  • 确保你使用的 flutter_debug_tools 版本与你的 Flutter SDK 版本兼容。
  • 查阅插件的官方文档以获取更多功能和详细信息。
  • 如果插件提供了更多的调试功能(如内存监控、UI 检查器等),你可以按照文档进一步集成和使用这些功能。

希望这个示例能帮助你开始使用 flutter_debug_tools 插件进行 Flutter 开发调试。

回到顶部