debug.dart 14.8 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 'media_query.dart';
14
import 'table.dart';
15

16 17 18
// Any changes to this file should be reflected in the debugAssertAllWidgetVarsUnset()
// function below.

19
/// Log the dirty widgets that are built each frame.
20 21 22 23
///
/// 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
24
/// by the pipeline.
25 26 27
///
/// Combined with [debugPrintScheduleBuildForStacks], this lets you watch a
/// widget's dirty/clean lifecycle.
28
///
29 30 31 32
/// To get similar information but showing it on the timeline available from the
/// Observatory rather than getting it in the console (where it can be
/// overwhelming), consider [debugProfileBuildsEnabled].
///
33 34 35 36
/// See also:
///
///  * [WidgetsBinding.drawFrame], which pumps the build and rendering pipeline
///    to generate a frame.
37 38
bool debugPrintRebuildDirtyWidgets = false;

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/// 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.
57
RebuildDirtyWidgetCallback? debugOnRebuildDirtyWidget;
58

59 60 61 62 63 64 65 66
/// 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
67 68
/// [runApp]) from the regular builds triggered by the pipeline.
///
69 70 71 72
/// See also:
///
///  * [WidgetsBinding.drawFrame], which pumps the build and rendering pipeline
///    to generate a frame.
73 74 75 76 77 78 79 80 81 82
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].
///
83
/// To see when the dirty list is flushed, see [debugPrintBuildScope].
84 85
///
/// To see when a frame is scheduled, see [debugPrintScheduleFrameStacks].
86 87
bool debugPrintScheduleBuildForStacks = false;

88 89 90 91 92 93
/// 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;

94 95 96
/// Adds [Timeline] events for every Widget built.
///
/// For details on how to use [Timeline] events in the Dart Observatory to
97
/// optimize your app, see https://flutter.dev/docs/testing/debugging#tracing-any-dart-code-performance
98
/// and https://fuchsia.googlesource.com/topaz/+/master/shell/docs/performance.md
99
///
100 101
/// See also:
///
102 103 104 105 106
///  * [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.
107 108
bool debugProfileBuildsEnabled = false;

109 110 111
/// Show banners for deprecated widgets.
bool debugHighlightDeprecatedWidgets = false;

112
Key? _firstNonUniqueKey(Iterable<Widget> widgets) {
113
  final Set<Key> keySet = HashSet<Key>();
114
  for (final Widget widget in widgets) {
115 116 117
    assert(widget != null);
    if (widget.key == null)
      continue;
118
    if (!keySet.add(widget.key!))
119 120 121 122 123
      return widget.key;
  }
  return null;
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137
/// Asserts if the given child list contains any duplicate non-null keys.
///
/// To invoke this function, use the following pattern, typically in the
/// relevant Widget's constructor:
///
/// ```dart
/// assert(!debugChildrenHaveDuplicateKeys(this, children));
/// ```
///
/// 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].
///
/// Does nothing if asserts are disabled. Always returns true.
138
bool debugChildrenHaveDuplicateKeys(Widget parent, Iterable<Widget> children) {
139
  assert(() {
140
    final Key? nonUniqueKey = _firstNonUniqueKey(children);
141
    if (nonUniqueKey != null) {
142 143 144 145 146
      throw FlutterError(
        'Duplicate keys found.\n'
        'If multiple keyed nodes exist as children of another node, they must have unique keys.\n'
        '$parent has multiple children with key $nonUniqueKey.'
      );
147 148
    }
    return true;
149
  }());
150 151
  return false;
}
152

153 154 155 156 157 158 159 160 161 162 163 164
/// 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].
///
/// Does nothing if asserts are disabled. Always returns true.
165 166
bool debugItemsHaveDuplicateKeys(Iterable<Widget> items) {
  assert(() {
167
    final Key? nonUniqueKey = _firstNonUniqueKey(items);
168
    if (nonUniqueKey != null)
169
      throw FlutterError('Duplicate key found: $nonUniqueKey.');
170
    return true;
171
  }());
172 173
  return false;
}
174 175 176

/// Asserts that the given context has a [Table] ancestor.
///
177
/// Used by [TableRowInkWell] to make sure that it is only used in an appropriate context.
178 179
///
/// To invoke this function, use the following pattern, typically in the
180
/// relevant Widget's build method:
181 182 183 184 185 186 187 188
///
/// ```dart
/// assert(debugCheckHasTable(context));
/// ```
///
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasTable(BuildContext context) {
  assert(() {
189
    if (context.widget is! Table && context.findAncestorWidgetOfExactType<Table>() == null) {
190 191 192 193 194 195
      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'),
      ]);
196 197
    }
    return true;
198
  }());
199 200
  return true;
}
201

202 203 204 205 206 207
/// 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
208
/// relevant Widget's build method:
209 210 211 212 213 214 215 216
///
/// ```dart
/// assert(debugCheckHasMediaQuery(context));
/// ```
///
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasMediaQuery(BuildContext context) {
  assert(() {
217
    if (context.widget is! MediaQuery && context.findAncestorWidgetOfExactType<MediaQuery>() == null) {
218
      throw FlutterError.fromParts(<DiagnosticsNode>[
219
        ErrorSummary('No MediaQuery widget ancestor found.'),
220 221 222 223
        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(
224 225 226 227 228
          'No MediaQuery ancestor could be found starting from the context '
          'that was passed to MediaQuery.of(). This can happen because you '
          'have not added a WidgetsApp, CupertinoApp, or MaterialApp widget '
          '(those widgets introduce a MediaQuery), or it can happen if the '
          'context you use comes from a widget above those widgets.'
229 230
        ),
      ]);
231 232
    }
    return true;
233
  }());
234 235 236
  return true;
}

237 238 239 240 241 242 243 244 245 246 247 248
/// 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));
/// ```
///
249 250 251 252 253 254
/// 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
255
///    value of the 'alignment' argument of the $runtimeType widget is an
256 257 258 259
///    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'
260
///    argument.". Should be a fully punctuated sentence.
261 262 263 264 265
///
/// 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].
///
266
/// Does nothing if asserts are disabled. Always returns true.
267
bool debugCheckHasDirectionality(BuildContext context, { String? why, String? hint, String? alternative }) {
268
  assert(() {
269
    if (context.widget is! Directionality && context.findAncestorWidgetOfExactType<Directionality>() == null) {
270
      why = why == null ? '' : ' $why';
271 272
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No Directionality widget found.'),
273 274 275
        ErrorDescription('${context.widget.runtimeType} widgets require a Directionality widget ancestor$why.\n'),
        if (hint != null)
          ErrorHint(hint),
276 277 278 279 280 281 282 283 284 285
        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, '
          'AlignmentDirectional, and other *Directional objects.'
        ),
286 287
        if (alternative != null)
          ErrorHint(alternative),
288
      ]);
289 290 291 292 293 294
    }
    return true;
  }());
  return true;
}

295 296 297 298 299 300
/// 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.
301
void debugWidgetBuilderValue(Widget widget, Widget? built) {
302 303
  assert(() {
    if (built == null) {
304 305 306 307 308 309 310 311 312
      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()". '
          'To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".'
        ),
      ]);
313
    }
314
    if (widget == built) {
315 316 317 318 319 320 321 322
      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". '
          'Doing so introduces a loop in the widget tree that can cause the app to crash.'
        ),
      ]);
323
    }
324
    return true;
325
  }());
326
}
327

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
/// 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));
/// ```
///
/// 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 '
          'to be provided by a Localizations widget ancestor.'
        ),
        ErrorDescription(
          'The widgets library uses Localizations to generate messages, '
          'labels, and abbreviations.'
        ),
        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 '
          'WidgetsLocalizations delegate.'
        ),
        ...context.describeMissingAncestor(expectedAncestorType: WidgetsLocalizations)
      ]);
    }
    return true;
  }());
  return true;
}

366 367 368 369 370
/// 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.
///
371
/// See [the widgets library](widgets/widgets-library.html) for a complete list.
372 373 374 375 376 377
bool debugAssertAllWidgetVarsUnset(String reason) {
  assert(() {
    if (debugPrintRebuildDirtyWidgets ||
        debugPrintBuildScope ||
        debugPrintScheduleBuildForStacks ||
        debugPrintGlobalKeyedWidgetLifecycle ||
378 379
        debugProfileBuildsEnabled ||
        debugHighlightDeprecatedWidgets) {
380
      throw FlutterError(reason);
381 382
    }
    return true;
383
  }());
384 385
  return true;
}