[ Web Proxy ]
URL:
Viewing: https://docs.flutter.dev/testing/code-debugging.md [Back]  [Original]

# Debug Flutter apps from code

> How to enable various debugging tools from your code and at the command line.


This guide describes which debugging features you can enable in your code.
For a full list of debugging and profiling tools, check out the
[Debugging][] page.

## Add logging to your application

The following list contains a few statements that you can use to log the
behavior of your application. You can view your logs in DevTools'
[Logging view][] or in your system console.

*   [`print()`][]: Prints a `stdout` (standard output) message. Part of the
    `dart:io` library.

*   [`stderr.method_to_invoke()`][]: Prints a `stderr` (standard error) message.
    Replace `method_to_invoke()` with a method supported by the `stderr`
    property, such as `writeln()` or `write()`. Often used in a `try...catch`
    block. Part of the `dart:io` library.

    
    ```dart
    stderr.writeln('print me');
    ```

*   [`log()`][]: Includes greater granularity and more information in the
    logging output. Part of the `dart:developer` library.

*   [`debugPrint()`][]: If too much output results in discarded log lines, use
    this to keep those lines. Will print messages in release mode unless part
    of a debug mode check or an assert. Part of the `foundations` library.

### Example 1 {:.no_toc}


```dart
import 'dart:developer' as developer;

void main() {
  developer.log('log me', name: 'my.app.category');

  developer.log('log me 1', name: 'my.other.category');
  developer.log('log me 2', name: 'my.other.category');
}
```

You can also pass app data to the log call.
The convention for this is to use the `error:` named
parameter on the `log()` call, JSON encode the object
you want to send, and pass the encoded string to the
error parameter.

### Example 2 {:.no_toc}


```dart
import 'dart:convert';
import 'dart:developer' as developer;

void main() {
  var myCustomObject = MyCustomObject();

  developer.log(
    'log me',
    name: 'my.app.category',
    error: jsonEncode(myCustomObject),
  );
}
```

DevTool's logging view interprets the JSON encoded error parameter
as a data object.
DevTool renders in the details view for that log entry.

## Set breakpoints

You can set breakpoints in DevTools' [Debugger][] or
in the built-in debugger of your IDE.

To set programmatic breakpoints:

1. Import the `dart:developer` package into the relevant file.
1. Insert programmatic breakpoints using the `debugger()` statement.
   This statement takes an optional `when` argument.
   This boolean argument sets a break when the given condition resolves to true.

   **Example 3** illustrates this.

### Example 3 {:.no_toc}


```dart
import 'dart:developer';

void someFunction(double offset) {
  debugger(when: offset > 30);
  // ...
}
```

## Debug app layers using flags

Each layer of the Flutter framework provides a function to dump its
current state or events to the console using the `debugPrint` property.

:::note
All of the following examples were run as macOS native apps on
a MacBook Pro M1. These will differ from any dumps your
development machine prints.
:::

:::tip
Each render object in any tree includes the first five
hexadecimal digits of its [`hashCode`][].
This hash serves as a unique identifier for that render object.
:::

[`hashCode`]: https://api.flutter.dev/flutter/rendering/TextSelectionPoint/hashCode.html

### Print the widget tree

To dump the state of the Widgets library,
call the [`debugDumpApp()`][] function.

1. Open your source file.
1. Import `package:flutter/rendering.dart`.
1. Call the [`debugDumpApp()`][] function from within the `runApp()` function.
   You need your app in debug mode.
   You cannot call this function inside a `build()` method
   when the app is building.
1. If you haven't started your app, debug it using your IDE.
1. If you have started your app, save your source file.
   Hot reload re-renders your app.

#### Example 4: Call `debugDumpApp()`


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

void main() {
  runApp(const MaterialApp(home: AppHome()));
}

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

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: TextButton(
          onPressed: () {
            debugDumpApp();
          },
          child: const Text('Dump Widget Tree'),
        ),
      ),
    );
  }
}
```

This function recursively calls the `toStringDeep()` method starting with
the root of the widget tree. It returns a "flattened" tree.

**Example 4** produces the following widget tree. It includes:

* All the widgets projected through their various build functions.
* Many widgets that don't appear in your app's source.
  The framework's widgets' build functions insert them during the build.

  The following tree, for example, shows [`_InkFeatures`][].
  That class implements part of the [`Material`][] widget.
  It doesn't appear anywhere in the code in **Example 4**.


Expand to view the widget tree for Example 4

```plaintext
flutter: WidgetsFlutterBinding - DEBUG MODE
flutter: [root](renderObject: RenderView#06beb)
flutter: View-[GlobalObjectKey FlutterView#7971c]
flutter:  _ViewScope
flutter:   _MediaQueryFromView(state: _MediaQueryFromViewState#d790c)
flutter:    MediaQuery(MediaQueryData(size: Size(800.0, 600.0), devicePixelRatio: 1.0, textScaleFactor: 1.0, platformBrightness: Brightness.dark, padding: EdgeInsets.zero, viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, systemGestureInsets: EdgeInsets.zero, alwaysUse24HourFormat: false, accessibleNavigation: false, highContrast: false, disableAnimations: false, invertColors: false, boldText: false, navigationMode: traditional, gestureSettings: DeviceGestureSettings(touchSlop: null), displayFeatures: []))
flutter:     MaterialApp(state: _MaterialAppState#27fa9)
flutter:      ScrollConfiguration(behavior: MaterialScrollBehavior)
flutter:       HeroControllerScope
flutter:        Focus(state: _FocusState#d7f97)
flutter:         _FocusInheritedScope
flutter:          Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#a6464)
flutter:           WidgetsApp-[GlobalObjectKey _MaterialAppState#27fa9](state: _WidgetsAppState#b5b17)
flutter:            RootRestorationScope(state: _RootRestorationScopeState#6b028)
flutter:             UnmanagedRestorationScope
flutter:              RestorationScope(dependencies: [UnmanagedRestorationScope], state: _RestorationScopeState#d1369)
flutter:               UnmanagedRestorationScope
flutter:                SharedAppData(state: _SharedAppDataState#95e82)
flutter:                 _SharedAppModel
flutter:                  Shortcuts(shortcuts: , state: _ShortcutsState#272dc)
flutter:                   Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#a3300)
flutter:                    _FocusInheritedScope
flutter:                     Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#db110)
flutter:                      DefaultTextEditingShortcuts
flutter:                       Shortcuts(shortcuts: , state: _ShortcutsState#1d796)
flutter:                        Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#0081b)
flutter:                         _FocusInheritedScope
flutter:                          Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#0d70e)
flutter:                           Shortcuts(shortcuts: , state: _ShortcutsState#56bac)
flutter:                            Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#3152e)
flutter:                             _FocusInheritedScope
flutter:                              Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#b7eaf)
flutter:                               Actions(dispatcher: null, actions: {DoNothingIntent: DoNothingAction#0fda1, DoNothingAndStopPropagationIntent: DoNothingAction#17f30, RequestFocusIntent: RequestFocusAction#10bd0, NextFocusIntent: NextFocusAction#60317, PreviousFocusIntent: PreviousFocusAction#2a933, DirectionalFocusIntent: DirectionalFocusAction#a6922, ScrollIntent: _OverridableContextAction#964fe(defaultAction: ScrollAction#ffb50), PrioritizedIntents: PrioritizedAction#be0e2, VoidCallbackIntent: VoidCallbackAction#805fa}, state: _ActionsState#bbd25)
flutter:                                _ActionsScope
flutter:                                 FocusTraversalGroup(policy: ReadingOrderTraversalPolicy#f1e76, state: _FocusTraversalGroupState#0c200)
flutter:                                  Focus(debugLabel: "FocusTraversalGroup", focusNode: _FocusTraversalGroupNode#ffcad(FocusTraversalGroup [IN FOCUS PATH]), dependencies: [_FocusInheritedScope], state: _FocusState#c7dc2)
flutter:                                   _FocusInheritedScope
flutter:                                    TapRegionSurface(renderObject: RenderTapRegionSurface#17aba)
flutter:                                     ShortcutRegistrar(state: _ShortcutRegistrarState#44954)
flutter:                                      _ShortcutRegistrarScope
flutter:                                       Shortcuts(manager: ShortcutManager#eb38c(shortcuts: {}), shortcuts: {}, state: _ShortcutsState#f85ac)
flutter:                                        Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#8c1a7)
flutter:                                         _FocusInheritedScope
flutter:                                          Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#1fc98)
flutter:                                           Localizations(locale: en_US, delegates: [DefaultMaterialLocalizations.delegate(en_US), DefaultCupertinoLocalizations.delegate(en_US), DefaultWidgetsLocalizations.delegate(en_US)], state: _LocalizationsState#ae3a0)
flutter:                                            Semantics(container: false, properties: SemanticsProperties, tooltip: null, textDirection: ltr, renderObject: RenderSemanticsAnnotations#8776e)
flutter:                                             _LocalizationsScope-[GlobalKey#61ca6]
flutter:                                              Directionality(textDirection: ltr)
flutter:                                               Title(color: Color(0xff2196f3))
flutter:                                                CheckedModeBanner("DEBUG")
flutter:                                                 Banner("DEBUG", textDirection: ltr, location: topEnd, Color(0xa0b71c1c), text inherit: true, text color: Color(0xffffffff), text size: 10.2, text weight: 900, text height: 1.0x, dependencies: [Directionality])
flutter:                                                  CustomPaint(renderObject: RenderCustomPaint#c014d)
flutter:                                                   DefaultTextStyle(debugLabel: fallback style; consider putting your text in a Material, inherit: true, color: Color(0xd0ff0000), family: monospace, size: 48.0, weight: 900, decoration: double Color(0xffffff00) TextDecoration.underline, softWrap: wrapping at box width, overflow: clip)
flutter:                                                    Builder(dependencies: [MediaQuery])
flutter:                                                     ScaffoldMessenger(dependencies: [MediaQuery], state: ScaffoldMessengerState#5b36e)
flutter:                                                      _ScaffoldMessengerScope
flutter:                                                       DefaultSelectionStyle
flutter:                                                        AnimatedTheme(duration: 200ms, state: _AnimatedThemeState#cd149(ticker inactive, ThemeDataTween(ThemeData#ef3b2  ThemeData#ef3b2)))
flutter:                                                         Theme(ThemeData#ef3b2, dependencies: [DefaultSelectionStyle])
flutter:                                                          _InheritedTheme
flutter:                                                           CupertinoTheme(brightness: light, primaryColor: MaterialColor(primary value: Color(0xff2196f3)), primaryContrastingColor: Color(0xffffffff), scaffoldBackgroundColor: Color(0xfffafafa), actionTextStyle: TextStyle(inherit: false, color: MaterialColor(primary value: Color(0xff2196f3)), family: .SF Pro Text, size: 17.0, letterSpacing: -0.4, decoration: TextDecoration.none), navActionTextStyle: TextStyle(inherit: false, color: MaterialColor(primary value: Color(0xff2196f3)), family: .SF Pro Text, size: 17.0, letterSpacing: -0.4, decoration: TextDecoration.none))
flutter:                                                            _InheritedCupertinoTheme
flutter:                                                             IconTheme(color: MaterialColor(primary value: Color(0xff2196f3)))
flutter:                                                              IconTheme(color: Color(0xdd000000))
flutter:                                                               DefaultSelectionStyle
flutter:                                                                FocusScope(debugLabel: "Navigator Scope", AUTOFOCUS, dependencies: [_FocusInheritedScope], state: _FocusScopeState#acbd8)
flutter:                                                                 Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#ab3f0)
flutter:                                                                  _FocusInheritedScope
flutter:                                                                   Navigator-[GlobalObjectKey _WidgetsAppState#b5b17](dependencies: [HeroControllerScope, UnmanagedRestorationScope], state: NavigatorState#1395a(tickers: tracking 1 ticker))
flutter:                                                                    HeroControllerScope
flutter:                                                                     Listener(listeners: [down, up, cancel], behavior: deferToChild, renderObject: RenderPointerListener#34172)
flutter:                                                                      AbsorbPointer(absorbing: false, renderObject: RenderAbsorbPointer#f8711)
flutter:                                                                       FocusTraversalGroup(policy: ReadingOrderTraversalPolicy#f1e76, state: _FocusTraversalGroupState#8d61a)
flutter:                                                                        Focus(debugLabel: "FocusTraversalGroup", focusNode: _FocusTraversalGroupNode#dd2b1(FocusTraversalGroup [IN FOCUS PATH]), dependencies: [_FocusInheritedScope], state: _FocusState#0bb03)
flutter:                                                                         _FocusInheritedScope
flutter:                                                                          Focus(debugLabel: "Navigator", AUTOFOCUS, focusNode: FocusNode#a3309(Navigator [IN FOCUS PATH]), dependencies: [_FocusInheritedScope], state: _FocusState#d3d07)
flutter:                                                                           _FocusInheritedScope
flutter:                                                                            UnmanagedRestorationScope
flutter:                                                                             Overlay-[LabeledGlobalKey#5485a](state: OverlayState#5bd52(entries: [OverlayEntry#fc947(opaque: true; maintainState: false), OverlayEntry#05a32(opaque: false; maintainState: true)]))
flutter:                                                                              _Theater(skipCount: 0, dependencies: [Directionality], renderObject: _RenderTheater#e86c3)
flutter:                                                                               _OverlayEntryWidget-[LabeledGlobalKey#1b37e](state: _OverlayEntryWidgetState#06ab0)
flutter:                                                                               TickerMode(state: _TickerModeState#0b4ac(requested mode: enabled))
flutter:                                                                                _EffectiveTickerMode(effective mode: enabled)
flutter:                                                                                 _RenderTheaterMarker
flutter:                                                                                  IgnorePointer(ignoring: false, renderObject: RenderIgnorePointer#34c66)
flutter:                                                                                   ModalBarrier
flutter:                                                                                    BlockSemantics(blocking: true, renderObject: RenderBlockSemantics#97799)
flutter:                                                                                     ExcludeSemantics(excluding: true, renderObject: RenderExcludeSemantics#8c4ce)
flutter:                                                                                      _ModalBarrierGestureDetector
flutter:                                                                                       RawGestureDetector(state: RawGestureDetectorState#556f6(gestures: [any tap], behavior: opaque))
flutter:                                                                                        _GestureSemantics(renderObject: RenderSemanticsGestureHandler#616f1)
flutter:                                                                                         Listener(listeners: [down, panZoomStart], behavior: opaque, renderObject: RenderPointerListener#c2b89)
flutter:                                                                                          Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#c3b31)
flutter:                                                                                           MouseRegion(listeners: , cursor: SystemMouseCursor(basic), renderObject: RenderMouseRegion#53cdb)
flutter:                                                                                            ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#faa51)
flutter:                                                                               _OverlayEntryWidget-[LabeledGlobalKey#bc0aa](state: _OverlayEntryWidgetState#cbf35)
flutter:                                                                                TickerMode(state: _TickerModeState#23e73(requested mode: enabled))
flutter:                                                                                 _EffectiveTickerMode(effective mode: enabled)
flutter:                                                                                  _RenderTheaterMarker
flutter:                                                                                   Semantics(container: false, properties: SemanticsProperties, tooltip: null, sortKey: OrdinalSortKey#135f4(order: 0.0), renderObject: RenderSemanticsAnnotations#5565e)
flutter:                                                                                    _ModalScope-[LabeledGlobalKey#4fe82](state: _ModalScopeState#4da7d)
flutter:                                                                                     AnimatedBuilder(listenable: ValueNotifier#d87c6(null), state: _AnimatedState#dde81)
flutter:                                                                                      RestorationScope(dependencies: [UnmanagedRestorationScope], state: _RestorationScopeState#78c51)
flutter:                                                                                       UnmanagedRestorationScope
flutter:                                                                                        _ModalScopeStatus(active)
flutter:                                                                                         Offstage(offstage: false, renderObject: RenderOffstage#5e498)
flutter:                                                                                          PageStorage
flutter:                                                                                           Builder
flutter:                                                                                            Actions(dispatcher: null, actions: {DismissIntent: _DismissModalAction#6279e}, state: _ActionsState#48019)
flutter:                                                                                             _ActionsScope
flutter:                                                                                              PrimaryScrollController(ScrollController#6a546(no clients))
flutter:                                                                                               FocusScope(debugLabel: "_ModalScopeState Focus Scope", focusNode: FocusScopeNode#0e2af(_ModalScopeState Focus Scope [PRIMARY FOCUS]), dependencies: [_FocusInheritedScope], state: _FocusScopeState#0bac4)
flutter:                                                                                                Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#44b4e)
flutter:                                                                                                 _FocusInheritedScope
flutter:                                                                                                  RepaintBoundary(renderObject: RenderRepaintBoundary#38f41)
flutter:                                                                                                   AnimatedBuilder(listenable: Listenable.merge([AnimationController#9d623( 1.000; paused; for MaterialPageRoute(/))ProxyAnimation, kAlwaysDismissedAnimationProxyAnimationProxyAnimation]), dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#61ca6]], state: _AnimatedState#47725)
flutter:                                                                                                    CupertinoPageTransition(dependencies: [Directionality])
flutter:                                                                                                     SlideTransition(listenable: kAlwaysDismissedAnimationProxyAnimationProxyAnimationCubic(0.35, 0.91, 0.33, 0.97)/Cubic(0.67, 0.03, 0.65, 0.09)Tween(Offset(0.0, 0.0)  Offset(-0.3, 0.0))Offset(0.0, 0.0), state: _AnimatedState#b6162)
flutter:                                                                                                      FractionalTranslation(renderObject: RenderFractionalTranslation#fb461)
flutter:                                                                                                       SlideTransition(listenable: AnimationController#9d623( 1.000; paused; for MaterialPageRoute(/))ProxyAnimationThreePointCubic /FlippedCurve(ThreePointCubic )Tween(Offset(1.0, 0.0)  Offset(0.0, 0.0))Offset(0.0, 0.0), state: _AnimatedState#834bf)
flutter:                                                                                                        FractionalTranslation(renderObject: RenderFractionalTranslation#73ea4)
flutter:                                                                                                         DecoratedBoxTransition(listenable: AnimationController#9d623( 1.000; paused; for MaterialPageRoute(/))ProxyAnimationCubic(0.35, 0.91, 0.33, 0.97)DecorationTween(_CupertinoEdgeShadowDecoration(colors: null)  _CupertinoEdgeShadowDecoration(colors: [Color(0x04000000), Color(0x00000000)]))_CupertinoEdgeShadowDecoration(colors: [Color(0x04000000), Color(0x00000000)]), state: _AnimatedState#a7fca)
flutter:                                                                                                          DecoratedBox(bg: _CupertinoEdgeShadowDecoration(colors: [Color(0x04000000), Color(0x00000000)]), dependencies: [Directionality, MediaQuery, _LocalizationsScope-[GlobalKey#61ca6]], renderObject: RenderDecoratedBox#9965c)
flutter:                                                                                                           _CupertinoBackGestureDetector(dependencies: [Directionality, MediaQuery], state: _CupertinoBackGestureDetectorState#ab8cd)
flutter:                                                                                                            Stack(alignment: AlignmentDirectional.topStart, fit: passthrough, dependencies: [Directionality], renderObject: RenderStack#b2b7c)
flutter:                                                                                                             AnimatedBuilder(listenable: ValueNotifier#1a88e(false), state: _AnimatedState#6e33c)
flutter:                                                                                                             IgnorePointer(ignoring: false, renderObject: RenderIgnorePointer#2b763)
flutter:                                                                                                              RepaintBoundary-[GlobalKey#628f4](renderObject: RenderRepaintBoundary#5a53b)
flutter:                                                                                                               Builder
flutter:                                                                                                                Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#f8795)
flutter:                                                                                                                 AppHome
flutter:                                                                                                                  Material(type: canvas, dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#61ca6]], state: _MaterialState#7d183)
flutter:                                                                                                                   AnimatedPhysicalModel(duration: 200ms, shape: rectangle, borderRadius: BorderRadius.zero, elevation: 0.0, color: Color(0xfffafafa), animateColor: false, shadowColor: Color(0xff000000), animateShadowColor: true, state: _AnimatedPhysicalModelState#d479e(ticker inactive))
flutter:                                                                                                                    PhysicalModel(shape: rectangle, borderRadius: BorderRadius.zero, elevation: 0.0, color: Color(0xfffafafa), shadowColor: Color(0xff000000), renderObject: RenderPhysicalModel#c60b5)
flutter:                                                                                                                     NotificationListener
flutter:                                                                                                                      _InkFeatures-[GlobalKey#e9da0 ink renderer](renderObject: _RenderInkFeatures#d8e6d)
flutter:                                                                                                                       AnimatedDefaultTextStyle(duration: 200ms, debugLabel: (englishLike bodyMedium 2014).merge(blackRedwoodCity bodyMedium), inherit: false, color: Color(0xdd000000), family: .AppleSystemUIFont, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip, state: _AnimatedDefaultTextStyleState#12f43(ticker inactive))
flutter:                                                                                                                        DefaultTextStyle(debugLabel: (englishLike bodyMedium 2014).merge(blackRedwoodCity bodyMedium), inherit: false, color: Color(0xdd000000), family: .AppleSystemUIFont, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip)
flutter:                                                                                                                         Center(alignment: Alignment.center, dependencies: [Directionality], renderObject: RenderPositionedBox#b088f)
flutter:                                                                                                                          TextButton(dirty, dependencies: [MediaQuery, _InheritedTheme, _LocalizationsScope-[GlobalKey#61ca6]], state: _ButtonStyleState#687c9)
flutter:                                                                                                                           Semantics(container: true, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#ca411 relayoutBoundary=up1)
flutter:                                                                                                                            _InputPadding(renderObject: _RenderInputPadding#60ede relayoutBoundary=up2)
flutter:                                                                                                                             ConstrainedBox(BoxConstraints(56.0
```dart
// Add import to the Flutter rendering library.
import 'package:flutter/rendering.dart';

void main() {
  debugPaintSizeEnabled = true;
  runApp(const MyApp());
}
```

When enabled, Flutter displays the following changes to your app:

* Displays all boxes in a bright teal border.
* Displays all padding as a box with a faded blue fill and blue border
  around the child widget.
* Displays all alignment positioning with yellow arrows.
* Displays all spacers in gray, when they have no child.

The [`debugPaintBaselinesEnabled`][] flag
does something similar but for objects with baselines.
The app displays the baseline for alphabetic characters in bright green
and the baseline for ideographic characters in orange.
Alphabetic characters "sit" on the alphabetic baseline,
but that baseline "cuts" through the bottom of [CJK characters][cjk].
Flutter positions the ideographic baseline at the very bottom of the text line.

The [`debugPaintPointersEnabled`][] flag turns on a special mode that
highlights any objects that you tap in teal.
This can help you determine if an object fails to hit test.
This might happen if the object falls outside the bounds of its parent
and thus not considered for hit testing in the first place.

If you're trying to debug compositor layers, consider using the following flags.

* Use the [`debugPaintLayerBordersEnabled`][] flag to find the boundaries
  of each layer. This flag results in outlining each layer's bounds in orange.

* Use the [`debugRepaintRainbowEnabled`][] flag to display a repainted layer.
  Whenever a layer repaints, it overlays with a rotating set of colors.

Any function or method in the Flutter framework that starts with
`debug...` only works in [debug mode][].

[cjk]: https://en.wikipedia.org/wiki/CJK_characters

## Debug animation issues

:::note
To debug animations with the least effort, slow them down.
To slow down the animation,
click **Slow Animations** in DevTools' [Inspector view][].
This reduces the animation to 20% speed.
If you want more control over the amount of slowness,
use the following instructions.
:::

Set the [`timeDilation`][] variable (from the `scheduler`
library) to a number greater than 1.0, for instance, 50.0.
It's best to only set this once on app startup. If you
change it on the fly, especially if you reduce it while
animations are running, it's possible that the framework
will observe time going backwards, which will probably
result in asserts and generally interfere with your efforts.

## Debug performance issues

:::note
You can achieve similar results to some of these debug
flags using [DevTools][]. Some of the debug flags provide little benefit.
If you find a flag with functionality you would like to add to [DevTools][],
[file an issue][].
:::

Flutter provides a wide variety of top-level properties and functions
to help you debug your app at various points along the
development cycle.
To use these features, compile your app in debug mode.

The following list highlights some flags and one function from the
[rendering library][] for debugging performance issues.

[`debugDumpRenderTree()`][]
: To dump the rendering tree to the console,
  call this function when not in a layout or repaint phase.

  To set these flags either:

  * Edit the framework code.
  * Import the module, set the value in your `main()` function,
    then hot restart.

[`debugPaintLayerBordersEnabled`][]
: To display the boundaries of each layer, set this property to `true`.
  When set, each layer paints a box around its boundary.

[`debugRepaintRainbowEnabled`][]
: To display a colored border around each widget, set this property to `true`.
  These borders change color as the app user scrolls in the app.
  To set this flag, add `debugRepaintRainbowEnabled = true;` as a top-level
  property in your app.
  If any static widgets rotate through colors after setting this flag,
  consider adding repaint boundaries to those areas.

[`debugPrintMarkNeedsLayoutStacks`][]
: To determine if your app creates more layouts than expected,
  set this property to `true`.
  This layout issue could happen on the timeline, on a profile,
  or from a `print` statement inside a layout method.
  When set, the framework outputs stack traces to the console
  to explain why your app marks each render object to be laid out.

[`debugPrintMarkNeedsPaintStacks`][]
: To determine if your app paints more layouts than expected,
  set this property to `true`.

You can generate stack traces on demand as well.
To print your own stack traces, add the `debugPrintStack()`
function to your app.

### Trace Dart code performance

:::note
You can use the DevTools [Timeline events tab][] to perform traces.
You can also import and export trace files into the Timeline view,
but only files generated by DevTools.
:::

To perform custom performance traces and measure wall or CPU time of arbitrary
segments of Dart code, use `dart:developer` [Timeline][] utilities.

1. Open your source code.
1. Wrap the code you want to measure in `Timeline` methods.

    
    ```dart
    import 'dart:developer';
    
    void main() {
      Timeline.startSync('interesting function');
      // iWonderHowLongThisTakes();
      Timeline.finishSync();
    }
    ```

1. While connected to your app, open DevTools' [Timeline events tab][].
1. Select the **Dart** recording option in the **Performance settings**.
1. Perform the function you want to measure.

To ensure that the runtime performance characteristics closely match that
of your final product, run your app in [profile mode][].

### Add performance overlay

:::note
You can toggle display of the performance overlay on
your app using the **Performance Overlay** button in the
[Flutter inspector][]. If you prefer to do it in code,
use the following instructions.
:::

To enable the `PerformanceOverlay` widget in your code,
set the `showPerformanceOverlay` property to `true` on the
[`MaterialApp`][], [`CupertinoApp`][], or [`WidgetsApp`][]
constructor:

#### Example 10


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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      showPerformanceOverlay: true,
      title: 'My Awesome App',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'My Awesome App'),
    );
  }
}
```

(If you're not using `MaterialApp`, `CupertinoApp`,
or `WidgetsApp`, you can get the same effect by wrapping your
application in a stack and putting a widget on your stack that was
created by calling [`PerformanceOverlay.allEnabled()`][].)

To learn how to interpret the graphs in the overlay,
check out [The performance overlay][] in
[Profiling Flutter performance][].

## Add widget alignment grid

To add an overlay to a [Material Design baseline grid][] on your app to
help verify alignments, add the `debugShowMaterialGrid` argument in the
[`MaterialApp` constructor][].

To add an overlay to non-Material applications, add a [`GridPaper`][] widget.

[`_InkFeatures`]: https://api.flutter.dev/flutter/material/InkFeature-class.html
[`BoxConstraints`]: https://api.flutter.dev/flutter/rendering/BoxConstraints-class.html
[`Center`]: https://api.flutter.dev/flutter/widgets/Center-class.html
[`CupertinoApp`]: https://api.flutter.dev/flutter/cupertino/CupertinoApp-class.html
[`debugDumpApp()`]: https://api.flutter.dev/flutter/widgets/debugDumpApp.html
[`debugDumpFocusTree()`]: https://api.flutter.dev/flutter/widgets/debugDumpFocusTree.html
[`debugDumpLayerTree()`]: https://api.flutter.dev/flutter/rendering/debugDumpLayerTree.html
[`debugDumpRenderTree()`]: https://api.flutter.dev/flutter/rendering/debugDumpRenderTree.html
[`debugDumpSemanticsTree()`]: https://api.flutter.dev/flutter/rendering/debugDumpSemanticsTree.html
[`debugFocusChanges`]: https://api.flutter.dev/flutter/widgets/debugFocusChanges.html
[`debugLabel`]: https://api.flutter.dev/flutter/widgets/Focus/debugLabel.html
[`debugPaintBaselinesEnabled`]: https://api.flutter.dev/flutter/rendering/debugPaintBaselinesEnabled.html
[`debugPaintLayerBordersEnabled`]: https://api.flutter.dev/flutter/rendering/debugPaintLayerBordersEnabled.html
[`debugPaintPointersEnabled`]: https://api.flutter.dev/flutter/rendering/debugPaintPointersEnabled.html
[`debugPaintSizeEnabled`]: https://api.flutter.dev/flutter/rendering/debugPaintSizeEnabled.html
[`debugPrint()`]: https://api.flutter.dev/flutter/widgets/debugPrint.html
[`debugPrintBeginFrameBanner`]: https://api.flutter.dev/flutter/scheduler/debugPrintBeginFrameBanner.html
[`debugPrintEndFrameBanner`]: https://api.flutter.dev/flutter/scheduler/debugPrintEndFrameBanner.html
[`debugPrintMarkNeedsLayoutStacks`]: https://api.flutter.dev/flutter/rendering/debugPrintMarkNeedsLayoutStacks.html
[`debugPrintMarkNeedsPaintStacks`]: https://api.flutter.dev/flutter/rendering/debugPrintMarkNeedsPaintStacks.html
[`debugPrintScheduleFrameStacks`]: https://api.flutter.dev/flutter/scheduler/debugPrintScheduleFrameStacks.html
[`debugRepaintRainbowEnabled`]: https://api.flutter.dev/flutter/rendering/debugRepaintRainbowEnabled.html
[`Focus`]: https://api.flutter.dev/flutter/widgets/Focus-class.html
[`GridPaper`]: https://api.flutter.dev/flutter/widgets/GridPaper-class.html
[`log()`]: https://api.flutter.dev/flutter/dart-developer/log.html
[`Material`]: https://api.flutter.dev/flutter/material/Material-class.html
[`MaterialApp` constructor]: https://api.flutter.dev/flutter/material/MaterialApp/MaterialApp.html
[`MaterialApp`]: https://api.flutter.dev/flutter/material/MaterialApp/MaterialApp.html
[`PerformanceOverlay.allEnabled()`]: https://api.flutter.dev/flutter/widgets/PerformanceOverlay/PerformanceOverlay.allEnabled.html
[`print()`]: https://api.flutter.dev/flutter/dart-core/print.html
[`RenderParagraph`]: https://api.flutter.dev/flutter/rendering/RenderParagraph-class.html
[`RenderPositionedBox`]: https://api.flutter.dev/flutter/rendering/RenderPositionedBox-class.html
[`setState()`]: https://api.flutter.dev/flutter/widgets/State/setState.html
[`stderr.method_to_invoke()`]: https://api.flutter.dev/flutter/dart-io/stderr.html
[`TextButton`]: https://api.flutter.dev/flutter/material/TextButton-class.html
[`timeDilation`]: https://api.flutter.dev/flutter/scheduler/timeDilation.html
[`WidgetsApp`]: https://api.flutter.dev/flutter/widgets/WidgetsApp-class.html
[debug mode]: /testing/build-modes#debug
[Debugger]: /tools/devtools/debugger
[Debugging]: /testing/debugging
[DevTools]: /tools/devtools
[DiagnosticsProperty]: https://api.flutter.dev/flutter/foundation/DiagnosticsProperty-class.html
[file an issue]: https://github.com/flutter/devtools/issues
[Flutter inspector]: /tools/devtools/inspector
[frame callback]: https://api.flutter.dev/flutter/scheduler/SchedulerBinding/addPersistentFrameCallback.html
[Inspector view]: /tools/devtools/inspector
[Logging view]: /tools/devtools/logging
[Material Design baseline grid]: https://m3.material.io/foundations/layout/understanding-layout/spacing
[profile mode]: /testing/build-modes#profile
[Profiling Flutter performance]: /perf/ui-performance
[render-fill]: https://api.flutter.dev/flutter/rendering/Layer/debugFillProperties.html
[rendering library]: https://api.flutter.dev/flutter/rendering/rendering-library.html
[The performance overlay]: /perf/ui-performance#the-performance-overlay
[Timeline events tab]: /tools/devtools/performance#timeline-events-tab
[Timeline]: https://api.dart.dev/dart-developer/Timeline-class.html
[widget-fill]: https://api.flutter.dev/flutter/widgets/Widget/debugFillProperties.html


Web Proxy Viewer  |  New URL  |  Original Page