debugCheckHasDirectionality function

bool debugCheckHasDirectionality(
  1. BuildContext context,
  2. {String? why,
  3. String? hint,
  4. String? alternative}
)

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:

assert(debugCheckHasDirectionality(context));

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 value of the 'alignment' argument of the $runtimeType widget is an 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' argument.". Should be a fully punctuated sentence.

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.

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.

Does nothing if asserts are disabled. Always returns true.

Implementation

bool debugCheckHasDirectionality(BuildContext context, { String? why, String? hint, String? alternative }) {
  assert(() {
    if (context.widget is! Directionality && context.getElementForInheritedWidgetOfExactType<Directionality>() == null) {
      why = why == null ? '' : ' $why';
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No Directionality widget found.'),
        ErrorDescription('${context.widget.runtimeType} widgets require a Directionality widget ancestor$why.\n'),
        if (hint != null)
          ErrorHint(hint),
        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.',
        ),
        if (alternative != null)
          ErrorHint(alternative),
      ]);
    }
    return true;
  }());
  return true;
}