debug.dart 1.85 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/widgets.dart';

import 'localizations.dart';

9 10 11
// Examples can assume:
// late BuildContext context;

12 13 14 15 16 17 18 19 20 21
/// Asserts that the given context has a [Localizations] ancestor that contains
/// a [CupertinoLocalizations] delegate.
///
/// To call this function, use the following pattern, typically in the
/// relevant Widget's build method:
///
/// ```dart
/// assert(debugCheckHasCupertinoLocalizations(context));
/// ```
///
22 23 24 25
/// 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.
///
26 27 28 29 30 31 32 33
/// Does nothing if asserts are disabled. Always returns true.
bool debugCheckHasCupertinoLocalizations(BuildContext context) {
  assert(() {
    if (Localizations.of<CupertinoLocalizations>(context, CupertinoLocalizations) == null) {
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('No CupertinoLocalizations found.'),
        ErrorDescription(
          '${context.widget.runtimeType} widgets require CupertinoLocalizations '
34
          'to be provided by a Localizations widget ancestor.',
35 36 37
        ),
        ErrorDescription(
          'The cupertino library uses Localizations to generate messages, '
38
          'labels, and abbreviations.',
39 40 41 42 43
        ),
        ErrorHint(
          'To introduce a CupertinoLocalizations, either use a '
          'CupertinoApp at the root of your application to include them '
          'automatically, or add a Localization widget with a '
44
          'CupertinoLocalizations delegate.',
45
        ),
46
        ...context.describeMissingAncestor(expectedAncestorType: CupertinoLocalizations),
47 48 49 50 51 52
      ]);
    }
    return true;
  }());
  return true;
}