debug.dart 20.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:collection';
6
import 'dart:developer' show Timeline; // to disambiguate reference in dartdocs below
7

8 9
import 'package:flutter/foundation.dart';

10
import 'basic.dart';
11
import 'framework.dart';
12
import 'localizations.dart';
13
import 'lookup_boundary.dart';
14
import 'media_query.dart';
15
import 'overlay.dart';
16
import 'table.dart';
17

18 19 20 21 22
// Examples can assume:
// late BuildContext context;
// List<Widget> children = <Widget>[];
// List<Widget> items = <Widget>[];

23 24 25
// Any changes to this file should be reflected in the debugAssertAllWidgetVarsUnset()
// function below.

26
/// Log the dirty widgets that are built each frame.
27 28 29 30
///
/// Combined with [debugPrintBuildScope] or [debugPrintBeginFrameBanner], this
/// allows you to distinguish builds triggered by the initial mounting of a
/// widget tree (e.g. in a call to [runApp]) from the regular builds triggered
31
/// by the pipeline.
32 33 34
///
/// Combined with [debugPrintScheduleBuildForStacks], this lets you watch a
/// widget's dirty/clean lifecycle.
35
///
36 37
/// To get similar information but showing it on the timeline available from
/// Flutter DevTools rather than getting it in the console (where it can be
38 39
/// overwhelming), consider [debugProfileBuildsEnabled].
///
40 41 42 43
/// See also:
///
///  * [WidgetsBinding.drawFrame], which pumps the build and rendering pipeline
///    to generate a frame.
44 45
bool debugPrintRebuildDirtyWidgets = false;

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/// Signature for [debugOnRebuildDirtyWidget] implementations.
typedef RebuildDirtyWidgetCallback = void Function(Element e, bool builtOnce);

/// Callback invoked for every dirty widget built each frame.
///
/// This callback is only invoked in debug builds.
///
/// See also:
///
///  * [debugPrintRebuildDirtyWidgets], which does something similar but logs
///    to the console instead of invoking a callback.
///  * [debugOnProfilePaint], which does something similar for [RenderObject]
///    painting.
///  * [WidgetInspectorService], which uses the [debugOnRebuildDirtyWidget]
///    callback to generate aggregate profile statistics describing which widget
///    rebuilds occurred when the
///    `ext.flutter.inspector.trackRebuildDirtyWidgets` service extension is
///    enabled.
64
RebuildDirtyWidgetCallback? debugOnRebuildDirtyWidget;
65

66 67 68 69 70 71 72 73
/// Log all calls to [BuildOwner.buildScope].
///
/// Combined with [debugPrintScheduleBuildForStacks], this allows you to track
/// when a [State.setState] call gets serviced.
///
/// Combined with [debugPrintRebuildDirtyWidgets] or
/// [debugPrintBeginFrameBanner], this allows you to distinguish builds
/// triggered by the initial mounting of a widget tree (e.g. in a call to
74 75
/// [runApp]) from the regular builds triggered by the pipeline.
///
76 77 78 79
/// See also:
///
///  * [WidgetsBinding.drawFrame], which pumps the build and rendering pipeline
///    to generate a frame.
80 81 82 83 84 85 86 87 88 89
bool debugPrintBuildScope = false;

/// Log the call stacks that mark widgets as needing to be rebuilt.
///
/// This is called whenever [BuildOwner.scheduleBuildFor] adds an element to the
/// dirty list. Typically this is as a result of [Element.markNeedsBuild] being
/// called, which itself is usually a result of [State.setState] being called.
///
/// To see when a widget is rebuilt, see [debugPrintRebuildDirtyWidgets].
///
90
/// To see when the dirty list is flushed, see [debugPrintBuildScope].
91 92
///
/// To see when a frame is scheduled, see [debugPrintScheduleFrameStacks].
93 94
bool debugPrintScheduleBuildForStacks = false;

95 96 97 98 99 100
/// Log when widgets with global keys are deactivated and log when they are
/// reactivated (retaken).
///
/// This can help track down framework bugs relating to the [GlobalKey] logic.
bool debugPrintGlobalKeyedWidgetLifecycle = false;

101 102
/// Adds [Timeline] events for every Widget built.
///
Ian Hickson's avatar
Ian Hickson committed
103 104 105 106 107 108 109 110 111 112 113 114
/// The timing information this flag exposes is not representative of the actual
/// cost of building, because the overhead of adding timeline events is
/// significant relative to the time each object takes to build. However, it can
/// expose unexpected widget behavior in the timeline.
///
/// In debug builds, additional information is included in the trace (such as
/// the properties of widgets being built). Collecting this data is
/// expensive and further makes these traces non-representative of actual
/// performance. This data is omitted in profile builds.
///
/// For more information about performance debugging in Flutter, see
/// <https://flutter.dev/docs/perf/rendering>.
115
///
116 117
/// See also:
///
118 119 120 121 122
///  * [debugPrintRebuildDirtyWidgets], which does something similar but
///    reporting the builds to the console.
///  * [debugProfileLayoutsEnabled], which does something similar for layout,
///    and [debugPrintLayouts], its console equivalent.
///  * [debugProfilePaintsEnabled], which does something similar for painting.
123 124
///  * [debugProfileBuildsEnabledUserWidgets], which adds events for user-created
///    [Widget] build times and incurs less overhead.
125 126
///  * [debugEnhanceBuildTimelineArguments], which enhances the trace with
///    debugging information related to [Widget] builds.
127 128
bool debugProfileBuildsEnabled = false;

129 130 131 132 133 134 135 136 137 138 139 140
/// Adds [Timeline] events for every user-created [Widget] built.
///
/// A user-created [Widget] is any [Widget] that is constructed in the root
/// library. Often [Widget]s contain child [Widget]s that are constructed in
/// libraries (for example, a [TextButton] having a [RichText] child). Timeline
/// events for those children will be omitted with this flag. This works for any
/// [Widget] not just ones declared in the root library.
///
/// See also:
///
///  * [debugProfileBuildsEnabled], which functions similarly but shows events
///    for every widget and has a higher overhead cost.
141 142
///  * [debugEnhanceBuildTimelineArguments], which enhances the trace with
///    debugging information related to [Widget] builds.
143 144
bool debugProfileBuildsEnabledUserWidgets = false;

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
/// Adds debugging information to [Timeline] events related to [Widget] builds.
///
/// This flag will only add [Timeline] event arguments for debug builds.
/// Additional arguments will be added for the "BUILD" [Timeline] event and for
/// all [Widget] build [Timeline] events, which are the [Timeline] events that
/// are added when either of [debugProfileBuildsEnabled] and
/// [debugProfileBuildsEnabledUserWidgets] are true. The debugging information
/// that will be added in trace arguments includes stats around [Widget] dirty
/// states and [Widget] diagnostic information (i.e. [Widget] properties).
///
/// See also:
///
///  * [debugProfileBuildsEnabled], which adds [Timeline] events for every
///    [Widget] built.
///  * [debugProfileBuildsEnabledUserWidgets], which adds [Timeline] events for
///    every user-created [Widget] built.
///  * [debugEnhanceLayoutTimelineArguments], which does something similar for
///    events related to [RenderObject] layouts.
///  * [debugEnhancePaintTimelineArguments], which does something similar for
///    events related to [RenderObject] paints.
bool debugEnhanceBuildTimelineArguments = false;

167 168 169
/// Show banners for deprecated widgets.
bool debugHighlightDeprecatedWidgets = false;

170
Key? _firstNonUniqueKey(Iterable<Widget> widgets) {
171
  final Set<Key> keySet = HashSet<Key>();
172
  for (final Widget widget in widgets) {
173
    if (widget.key == null) {
174
      continue;
175 176
    }
    if (!keySet.add(widget.key!)) {
177
      return widget.key;
178
    }
179 180 181 182
  }
  return null;
}

183 184
/// Asserts if the given child list contains any duplicate non-null keys.
///
185
/// To invoke this function, use the following pattern:
186 187
///
/// ```dart
188 189 190 191 192 193 194 195 196
/// class MyWidget extends StatelessWidget {
///   MyWidget({ super.key, required this.children }) {
///     assert(!debugChildrenHaveDuplicateKeys(this, children));
///   }
///
///   final List<Widget> children;
///
///   // ...
/// }
197 198
/// ```
///
199 200
/// If specified, the `message` overrides the default message.
///
201 202 203 204
/// For a version of this function that can be used in contexts where
/// the list of items does not have a particular parent, see
/// [debugItemsHaveDuplicateKeys].
///
205 206
/// Does nothing if asserts are disabled. Always returns false.
bool debugChildrenHaveDuplicateKeys(Widget parent, Iterable<Widget> children, { String? message }) {
207
  assert(() {
208
    final Key? nonUniqueKey = _firstNonUniqueKey(children);
209
    if (nonUniqueKey != null) {
210
      throw FlutterError(
211 212 213
        "${message ?? 'Duplicate keys found.\n'
                      'If multiple keyed widgets exist as children of another widget, they must have unique keys.'}"
        '\n$parent has multiple children with key $nonUniqueKey.',
214
      );
215 216
    }
    return true;
217
  }());
218 219
  return false;
}
220

221 222 223 224 225 226 227 228 229 230 231
/// Asserts if the given list of items contains any duplicate non-null keys.
///
/// To invoke this function, use the following pattern:
///
/// ```dart
/// assert(!debugItemsHaveDuplicateKeys(items));
/// ```
///
/// For a version of this function specifically intended for parents
/// checking their children lists, see [debugChildrenHaveDuplicateKeys].
///
232
/// Does nothing if asserts are disabled. Always returns false.
233 234
bool debugItemsHaveDuplicateKeys(Iterable<Widget> items) {
  assert(() {
235
    final Key? nonUniqueKey = _firstNonUniqueKey(items);
236
    if (nonUniqueKey != null) {
237
      throw FlutterError('Duplicate key found: $nonUniqueKey.');
238
    }
239
    return true;
240
  }());
241 242
  return false;
}
243 244 245

/// Asserts that the given context has a [Table] ancestor.
///
246
/// Used by [TableRowInkWell] to make sure that it is only used in an appropriate context.
247 248
///
/// To invoke this function, use the following pattern, typically in the
249
/// relevant Widget's build method:
250 251 252 253 254
///
/// ```dart
/// assert(debugCheckHasTable(context));
/// ```
///
255 256 257 258
/// Always place this before any early returns, so that the invariant is checked
/// in all cases. This prevents bugs from hiding until a particular codepath is
/// hit.
///
259 260
/// This method can be expensive (it walks the element tree).
///
261 262 263
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasTable(BuildContext context) {
  assert(() {
264
    if (context.widget is! Table && context.findAncestorWidgetOfExactType<Table>() == null) {
265 266 267 268 269 270
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No Table widget found.'),
        ErrorDescription('${context.widget.runtimeType} widgets require a Table widget ancestor.'),
        context.describeWidget('The specific widget that could not find a Table ancestor was'),
        context.describeOwnershipChain('The ownership chain for the affected widget is'),
      ]);
271 272
    }
    return true;
273
  }());
274 275
  return true;
}
276

277 278 279 280 281 282
/// Asserts that the given context has a [MediaQuery] ancestor.
///
/// Used by various widgets to make sure that they are only used in an
/// appropriate context.
///
/// To invoke this function, use the following pattern, typically in the
283
/// relevant Widget's build method:
284 285 286 287 288
///
/// ```dart
/// assert(debugCheckHasMediaQuery(context));
/// ```
///
289 290 291 292
/// Always place this before any early returns, so that the invariant is checked
/// in all cases. This prevents bugs from hiding until a particular codepath is
/// hit.
///
293 294 295
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasMediaQuery(BuildContext context) {
  assert(() {
296
    if (context.widget is! MediaQuery && context.getElementForInheritedWidgetOfExactType<MediaQuery>() == null) {
297
      throw FlutterError.fromParts(<DiagnosticsNode>[
298
        ErrorSummary('No MediaQuery widget ancestor found.'),
299 300 301 302
        ErrorDescription('${context.widget.runtimeType} widgets require a MediaQuery widget ancestor.'),
        context.describeWidget('The specific widget that could not find a MediaQuery ancestor was'),
        context.describeOwnershipChain('The ownership chain for the affected widget is'),
        ErrorHint(
303
          'No MediaQuery ancestor could be found starting from the context '
304 305 306
          'that was passed to MediaQuery.of(). This can happen because the '
          'context used is not a descendant of a View widget, which introduces '
          'a MediaQuery.'
307 308
        ),
      ]);
309 310
    }
    return true;
311
  }());
312 313 314
  return true;
}

315 316 317 318 319 320 321 322 323 324 325 326
/// Asserts that the given context has a [Directionality] ancestor.
///
/// Used by various widgets to make sure that they are only used in an
/// appropriate context.
///
/// To invoke this function, use the following pattern, typically in the
/// relevant Widget's build method:
///
/// ```dart
/// assert(debugCheckHasDirectionality(context));
/// ```
///
327 328 329 330 331 332
/// To improve the error messages you can add some extra color using the
/// named arguments.
///
///  * why: explain why the direction is needed, for example "to resolve
///    the 'alignment' argument". Should be an adverb phrase describing why.
///  * hint: explain why this might be happening, for example "The default
333
///    value of the 'alignment' argument of the $runtimeType widget is an
334 335 336 337
///    AlignmentDirectional value.". Should be a fully punctuated sentence.
///  * alternative: provide additional advice specific to the situation,
///    especially an alternative to providing a Directionality ancestor.
///    For example, "Alternatively, consider specifying the 'textDirection'
338
///    argument.". Should be a fully punctuated sentence.
339 340 341 342 343
///
/// Each one can be null, in which case it is skipped (this is the default).
/// If they are non-null, they are included in the order above, interspersed
/// with the more generic advice regarding [Directionality].
///
344 345 346 347
/// Always place this before any early returns, so that the invariant is checked
/// in all cases. This prevents bugs from hiding until a particular codepath is
/// hit.
///
348
/// Does nothing if asserts are disabled. Always returns true.
349
bool debugCheckHasDirectionality(BuildContext context, { String? why, String? hint, String? alternative }) {
350
  assert(() {
351
    if (context.widget is! Directionality && context.getElementForInheritedWidgetOfExactType<Directionality>() == null) {
352
      why = why == null ? '' : ' $why';
353 354
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No Directionality widget found.'),
355 356 357
        ErrorDescription('${context.widget.runtimeType} widgets require a Directionality widget ancestor$why.\n'),
        if (hint != null)
          ErrorHint(hint),
358 359 360 361 362 363 364 365
        context.describeWidget('The specific widget that could not find a Directionality ancestor was'),
        context.describeOwnershipChain('The ownership chain for the affected widget is'),
        ErrorHint(
          'Typically, the Directionality widget is introduced by the MaterialApp '
          'or WidgetsApp widget at the top of your application widget tree. It '
          'determines the ambient reading direction and is used, for example, to '
          'determine how to lay out text, how to interpret "start" and "end" '
          'values, and to resolve EdgeInsetsDirectional, '
366
          'AlignmentDirectional, and other *Directional objects.',
367
        ),
368 369
        if (alternative != null)
          ErrorHint(alternative),
370
      ]);
371 372 373 374 375 376
    }
    return true;
  }());
  return true;
}

377 378 379 380 381 382
/// Asserts that the `built` widget is not null.
///
/// Used when the given `widget` calls a builder function to check that the
/// function returned a non-null value, as typically required.
///
/// Does nothing when asserts are disabled.
383
void debugWidgetBuilderValue(Widget widget, Widget? built) {
384 385
  assert(() {
    if (built == null) {
386 387 388 389 390 391
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('A build function returned null.'),
        DiagnosticsProperty<Widget>('The offending widget is', widget, style: DiagnosticsTreeStyle.errorProperty),
        ErrorDescription('Build functions must never return null.'),
        ErrorHint(
          'To return an empty space that causes the building widget to fill available room, return "Container()". '
392
          'To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".',
393 394
        ),
      ]);
395
    }
396
    if (widget == built) {
397 398 399 400 401
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('A build function returned context.widget.'),
        DiagnosticsProperty<Widget>('The offending widget is', widget, style: DiagnosticsTreeStyle.errorProperty),
        ErrorDescription(
          'Build functions must never return their BuildContext parameter\'s widget or a child that contains "context.widget". '
402
          'Doing so introduces a loop in the widget tree that can cause the app to crash.',
403 404
        ),
      ]);
405
    }
406
    return true;
407
  }());
408
}
409

410 411 412 413 414 415 416 417 418 419
/// Asserts that the given context has a [Localizations] ancestor that contains
/// a [WidgetsLocalizations] delegate.
///
/// To call this function, use the following pattern, typically in the
/// relevant Widget's build method:
///
/// ```dart
/// assert(debugCheckHasWidgetsLocalizations(context));
/// ```
///
420 421 422 423
/// Always place this before any early returns, so that the invariant is checked
/// in all cases. This prevents bugs from hiding until a particular codepath is
/// hit.
///
424 425 426 427 428 429 430 431
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasWidgetsLocalizations(BuildContext context) {
  assert(() {
    if (Localizations.of<WidgetsLocalizations>(context, WidgetsLocalizations) == null) {
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No WidgetsLocalizations found.'),
        ErrorDescription(
          '${context.widget.runtimeType} widgets require WidgetsLocalizations '
432
          'to be provided by a Localizations widget ancestor.',
433 434 435
        ),
        ErrorDescription(
          'The widgets library uses Localizations to generate messages, '
436
          'labels, and abbreviations.',
437 438 439 440 441
        ),
        ErrorHint(
          'To introduce a WidgetsLocalizations, either use a '
          'WidgetsApp at the root of your application to include them '
          'automatically, or add a Localization widget with a '
442
          'WidgetsLocalizations delegate.',
443
        ),
444
        ...context.describeMissingAncestor(expectedAncestorType: WidgetsLocalizations),
445 446 447 448 449 450 451
      ]);
    }
    return true;
  }());
  return true;
}

452 453 454 455 456 457 458 459 460
/// Asserts that the given context has an [Overlay] ancestor.
///
/// To call this function, use the following pattern, typically in the
/// relevant Widget's build method:
///
/// ```dart
/// assert(debugCheckHasOverlay(context));
/// ```
///
461 462 463 464
/// Always place this before any early returns, so that the invariant is checked
/// in all cases. This prevents bugs from hiding until a particular codepath is
/// hit.
///
465 466
/// This method can be expensive (it walks the element tree).
///
467 468 469
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasOverlay(BuildContext context) {
  assert(() {
470 471
    if (LookupBoundary.findAncestorWidgetOfExactType<Overlay>(context) == null) {
      final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Overlay>(context);
472
      throw FlutterError.fromParts(<DiagnosticsNode>[
473 474 475 476 477
        ErrorSummary('No Overlay widget found${hiddenByBoundary ? ' within the closest LookupBoundary' : ''}.'),
        if (hiddenByBoundary)
          ErrorDescription(
              'There is an ancestor Overlay widget, but it is hidden by a LookupBoundary.'
          ),
478 479
        ErrorDescription(
          '${context.widget.runtimeType} widgets require an Overlay '
480
          'widget ancestor within the closest LookupBoundary.\n'
481
          'An overlay lets widgets float on top of other widget children.',
482 483 484 485 486 487
        ),
        ErrorHint(
          'To introduce an Overlay widget, you can either directly '
          'include one, or use a widget that contains an Overlay itself, '
          'such as a Navigator, WidgetApp, MaterialApp, or CupertinoApp.',
        ),
488 489
        ...context.describeMissingAncestor(expectedAncestorType: Overlay),
      ]);
490 491 492 493 494 495
    }
    return true;
  }());
  return true;
}

496 497 498 499 500
/// Returns true if none of the widget library debug variables have been changed.
///
/// This function is used by the test framework to ensure that debug variables
/// haven't been inadvertently changed.
///
501
/// See [the widgets library](widgets/widgets-library.html) for a complete list.
502 503 504 505 506 507
bool debugAssertAllWidgetVarsUnset(String reason) {
  assert(() {
    if (debugPrintRebuildDirtyWidgets ||
        debugPrintBuildScope ||
        debugPrintScheduleBuildForStacks ||
        debugPrintGlobalKeyedWidgetLifecycle ||
508
        debugProfileBuildsEnabled ||
509 510
        debugHighlightDeprecatedWidgets ||
        debugProfileBuildsEnabledUserWidgets) {
511
      throw FlutterError(reason);
512 513
    }
    return true;
514
  }());
515 516
  return true;
}