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

import 'package:intl/date_symbols.dart' as intl;
import 'package:intl/date_symbol_data_custom.dart' as date_symbol_data_custom;
import '../l10n/generated_date_localizations.dart' as date_localizations;

/// Tracks if date i18n data has been loaded.
bool _dateIntlDataInitialized = false;

12
/// Loads i18n data for dates if it hasn't been loaded yet.
13
///
14 15
/// Only the first invocation of this function loads the data. Subsequent
/// invocations have no effect.
16 17 18 19
void loadDateIntlDataIfNotLoaded() {
  if (!_dateIntlDataInitialized) {
    // TODO(garyq): Add support for scriptCodes. Do not strip scriptCode from string.

20 21 22 23
    // Keeps track of initialized locales. This can only happen if a locale
    // with a stripped scriptCode has already been initialzed. The set of
    // initialized locales should be removed when scriptCode stripping is
    // removed.
24
    final Set<String> initializedLocales = <String>{};
25 26 27 28 29 30
    date_localizations.dateSymbols
      .cast<String, Map<String, dynamic>>()
      .forEach((String locale, Map<String, dynamic> data) {
        // Strip scriptCode from the locale, as we do not distinguish between scripts
        // for dates.
        final List<String> codes = locale.split('_');
31
        String? countryCode;
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
        if (codes.length == 2) {
          countryCode = codes[1].length < 4 ? codes[1] : null;
        } else if (codes.length == 3) {
          countryCode = codes[1].length < codes[2].length ? codes[1] : codes[2];
        }
        locale = codes[0] + (countryCode != null ? '_' + countryCode : '');
        if (initializedLocales.contains(locale))
          return;
        initializedLocales.add(locale);
        // Perform initialization.
        assert(date_localizations.datePatterns.containsKey(locale));
        final intl.DateSymbols symbols = intl.DateSymbols.deserializeFromMap(data);
        date_symbol_data_custom.initializeDateFormattingCustom(
          locale: locale,
          symbols: symbols,
          patterns: date_localizations.datePatterns[locale],
        );
      });
50 51
    _dateIntlDataInitialized = true;
  }
Dan Field's avatar
Dan Field committed
52
}