Flutter动态调试与检查插件inspectable的使用

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

Flutter动态调试与检查插件inspectable的使用

Inspectable 是一个用于检查其子树中所有小部件的组件。

特性

  • 检查属于其子树的小部件。
  • 为需要检查的小部件着色。

目标

Inspectable 的目标是在不使用 IDE 的情况下,帮助 Flutter 应用程序开发者明确构建当前显示 UI 的具体小部件。

在没有 IDE 的情况下使用它可能非常有用,例如在使用 “release” 模式构建应用或在没有连接到 PC 的真实设备上进行调试时。

使用方法

1. 在 MaterialApp 下放置 Inspectable

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Inspectable(
        child: MyHomePage(),
        colors: {
          Text: Colors.blue,
          Stack: Colors.teal,
          TextButton: Colors.brown,
          Material: Colors.red,
        },
        verbose: true,
      ),
    );
  }
}

可选地,你可以通过 colors 属性为需要检查的小部件着色。

verbose 是一个标志,用于切换是否显示以 _ 开头的私有小部件。

2. 调用 Inspectable.of(context).inspect() 显示小部件树

TextButton(
  onPressed: () {
    Inspectable.of(context).inspect();
  },
  child: Text(
    'INSPECT',
  ),
)

3. 如果只想检查特定小部件下的子树,可以在此处放置另一个 Inspectable

Inspectable(
  child: AnyWidgetForInspect()
)

注意,在这种情况下,你必须使用 AnyWidgetForInspect 下的 context,因为该上下文会查找最近的祖先 Inspectable

4. 如果想检查 State 的状态(如 StatefulWidget),需要重写 debugFillProperties() 方法。以下示例尝试显示其私有字段 _someIntState_someBoolState

[@override](/user/override)
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
  super.debugFillProperties(properties);
  properties.add(IntProperty('someIntState', _someIntState, defaultValue: null));
  properties.add(FlagProperty(
    'someBoolState',
    value: _someBoolState,
    defaultValue: null,
    ifTrue: 'flag is true',
    ifFalse: 'flag is false',
  ));
}

debugFillProperties 在 Flutter 框架中经常使用,你可以参考 Text 等小部件的代码来了解更多的用法细节。

完整示例代码

以下是完整的示例代码:

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

import 'package:inspectable/inspectable.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Inspectable Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Inspectable(
        child: MyHomePage(),
        colors: {
          Text: Colors.blue,
          Stack: Colors.teal,
          TextButton: Colors.brown,
          Material: Colors.red,
        },
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Inspectable Sample'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            const SizedBox(height: 60),
            InspectButton(
              key: ValueKey('InspectTestKey'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  [@override](/user/override)
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty('count', _counter, defaultValue: null));
  }
}

class InspectButton extends StatefulWidget {
  const InspectButton({
    Key? key,
  }) : super(key: key);

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

class _InspectButtonState extends State<InspectButton> {
  var _someBoolState = false;
  var _someIntState = 10;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: () {
        Inspectable.of(context).inspect();
      },
      child: Text(
        'INSPECT',
        style: TextStyle(fontSize: 24),
      ),
    );
  }

  [@override](/user/override)
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties
        .add(IntProperty('someIntState', _someIntState, defaultValue: null));
    properties.add(FlagProperty(
      'someBoolState',
      value: _someBoolState,
      defaultValue: null,
      ifTrue: 'flag is true',
      ifFalse: 'flag is false',
    ));
  }
}

更多关于Flutter动态调试与检查插件inspectable的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter动态调试与检查插件inspectable的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter开发中,inspectable 是一个非常有用的插件,它允许你在开发过程中动态地检查和调试应用程序的状态。以下是如何在Flutter项目中使用 inspectable 插件的详细步骤,包括相关代码示例。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  inspectable: ^0.0.x  # 请替换为最新版本号

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

2. 初始化 Inspectable

在你的 Flutter 应用的入口文件(通常是 main.dart)中,初始化 Inspectable

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

void main() {
  // 初始化 Inspectable
  Inspectable.install();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 使用 InspectableWidget 包装你的 Widget

为了使用 inspectable 的功能,你需要用 InspectableWidget 包装你想要检查的 Widget。

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

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

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

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

  @override
  Widget build(BuildContext context) {
    return InspectableWidget(
      label: 'MyHomePage',  // 你可以为这个 Widget 设置一个标签
      child: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Demo Home Page'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

4. 使用 DevTools 进行调试

现在,当你运行你的 Flutter 应用时,你可以打开 Flutter DevTools(在 Android Studio 或 VS Code 中都有集成),然后在 DevTools 的“Inspect”面板中查看和调试你的 Widget。

  • 打开 DevTools:在 Android Studio 中,你可以通过菜单栏的 View > Tool Windows > Flutter DevTools 打开;在 VS Code 中,你可以通过命令面板(Ctrl+Shift+PCmd+Shift+P)搜索并运行 Flutter: Open DevTools
  • 切换到 Inspect 面板:在 DevTools 中,选择 Inspect 面板,你应该能看到应用中的 Widget 树。
  • 选择和检查 Widget:你可以点击并展开 Widget 树中的节点,查看它们的属性和状态。

5. 动态检查变量和状态

inspectable 还允许你动态地检查和监听变量的变化。你可以使用 InspectableValue 来包装你的变量。

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

class _MyHomePageState extends State<MyHomePage> {
  final inspectableCounter = InspectableValue<int>(0);  // 包装变量

  void _incrementCounter() {
    inspectableCounter.value = inspectableCounter.value! + 1;  // 更新变量值
    setState(() {});  // 通知 Flutter UI 更新
  }

  @override
  Widget build(BuildContext context) {
    return InspectableWidget(
      label: 'MyHomePage',
      child: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Demo Home Page'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '${inspectableCounter.value}',  // 使用包装后的变量
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

现在,当你在 DevTools 中查看这个 Widget 时,你可以看到 inspectableCounter 的值,并且它会在你点击按钮时实时更新。

通过这些步骤,你就可以在 Flutter 应用中使用 inspectable 插件来进行动态调试和检查了。希望这些代码示例能帮助你更好地理解和使用这个插件。

回到顶部