flutter / flutter

Flutter makes it easy and fast to build beautiful apps for mobile and beyond
https://flutter.dev
BSD 3-Clause "New" or "Revised" License
165.62k stars 27.34k forks source link

A AppLocalizations delegate that supports the tzm locale was not found. #33250

Closed boukmi closed 4 years ago

boukmi commented 5 years ago

Hello everybody,

I'm trying to add support for a new language in my Flutter application by following this tutorial but unfortunately that does not seem to work.

I've added a new localisations delegate:

import 'dart:async';

import 'package:intl/intl.dart' as intl;
import 'package:intl/date_symbol_data_local.dart' as intl;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

class _TzmMaterialLocalizationsDelegate
    extends LocalizationsDelegate<MaterialLocalizations> {
  const _TzmMaterialLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => locale.languageCode == 'tzm';

  @override
  Future<MaterialLocalizations> load(Locale locale) async {
    final String localeName = intl.Intl.canonicalizedLocale(locale.toString());
    print(locale);
    print(locale.languageCode == 'tzm');

    await intl.initializeDateFormatting(localeName);
    return TzmMaterialLocalizations(
      localeName: localeName,
      fullYearFormat: intl.DateFormat('y', localeName),
      mediumDateFormat: intl.DateFormat('EEE, MMM d', localeName),
      longDateFormat: intl.DateFormat('EEEE, MMMM d, y', localeName),
      yearMonthFormat: intl.DateFormat('MMMM y', localeName),
      decimalFormat: intl.NumberFormat('#,##0.###', localeName),
      twoDigitZeroPaddedFormat: intl.NumberFormat('00', localeName),
    );
  }

  @override
  bool shouldReload(LocalizationsDelegate<MaterialLocalizations> old) => false;
}

class TzmMaterialLocalizations extends GlobalMaterialLocalizations {
  const TzmMaterialLocalizations({
    String localeName = 'tzm',
    @required intl.DateFormat fullYearFormat,
    @required intl.DateFormat mediumDateFormat,
    @required intl.DateFormat longDateFormat,
    @required intl.DateFormat yearMonthFormat,
    @required intl.NumberFormat decimalFormat,
    @required intl.NumberFormat twoDigitZeroPaddedFormat,
  }) : super(
          localeName: localeName,
          fullYearFormat: fullYearFormat,
          mediumDateFormat: mediumDateFormat,
          longDateFormat: longDateFormat,
          yearMonthFormat: yearMonthFormat,
          decimalFormat: decimalFormat,
          twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat,
        );

  @override
  String get aboutListTileTitleRaw => r'À propos de $applicationName';

  @override
  String get alertDialogLabel => r'Alerte';

 ...

  @override
  int get firstDayOfWeekIndex => 0;

  static const LocalizationsDelegate<MaterialLocalizations> delegate =
      _TzmMaterialLocalizationsDelegate();
}

I have't added all the translations yet, I wanted to make sure that it's working first.

This is the app.dart file

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:smt_mobile/base/locales.dart';

import 'package:smt_mobile/l10n/app_locales.dart';
import 'package:smt_mobile/l10n/language/tamazight_localizations.dart';
import 'package:smt_mobile/base/base.dart';
import 'package:smt_mobile/bloc/locale/locale.dart';
import 'package:smt_mobile/ui/setting/page/language_setting_page.dart';
import 'package:smt_mobile/ui/setting/page/notification_settings_page.dart';
import 'package:smt_mobile/ui/setting/page/settings_page.dart';
import 'package:smt_mobile/ui/student/pages/student_list_page.dart';
import 'package:smt_mobile/ui/student/pages/student_details_page.dart';

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  final LocaleBloc _localeBloc = LocaleBloc();

  @override
  void initState() {
    _localeBloc.dispatch(FetchLocale());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new BlocProvider(
      bloc: _localeBloc,
      child: BlocBuilder(
        bloc: _localeBloc,
        builder: (BuildContext context, LocaleState state) {
          if (state is LocaleLoading) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          Locale locale;
          if (state is LocaleFetched) {
            locale = state.locale;
          }

          if (state is LocaleUpdated) {
            locale = state.locale;
          }

          return MaterialApp(
            locale: locale,
            localizationsDelegates: [
              AppLocalizationsDelegate(),
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              TzmMaterialLocalizations.delegate,
            ],
            supportedLocales: [
              const Locale('fr', 'FR'),
              const Locale('tzm', 'MA'),
              const Locale('en', 'US'),
            ],
            onGenerateTitle: (BuildContext context) =>
                AppLocalizations.of(context).title,
            home: StudentListPage(),
            routes: {
              AppRoutes.students: (BuildContext context) => StudentListPage(),
              AppRoutes.settings: (BuildContext context) => SettingsPage(),
              AppRoutes.notificationSettings: (BuildContext context) =>
                  NotificationSettingsPage(),
              AppRoutes.languageSettings: (BuildContext context) =>
                  LanguageSettingPage(),
            },
            onGenerateRoute: (RouteSettings settings) {
              if (settings.name == AppRoutes.studentDetails) {
                String id = settings.arguments;
                return MaterialPageRoute(builder: (BuildContext context) {
                  return StudentDetailsPage(
                    id: id,
                  );
                });
              }
            },
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _localeBloc.dispose();
    super.dispose();
  }
}

And pubspec.yaml

name: name

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  intl: 0.15.8

  # A composable, cross-platform, Future-based API for making HTTP requests.
  http: ^0.12.0+2

  # A Flutter package that helps implement the BLoC pattern.
  bloc: ^0.13.0
  flutter_bloc: ^0.13.0

  # An abstract class that helps to implement equality without needing to explicitly override == and hashCode.
  equatable: ^0.2.3

  # SQLite database support for Flutter
  sqflite: ^1.1.5

  # A comprehensive, cross-platform path manipulation library for Dart.
  path: ^1.6.2

  # Get current device information from within the Flutter application
  device_info: ^0.4.0+1

  # Provides an API for querying information about an application package.
  package_info: ^0.4.0+3

  # A Flutter plugin for finding commonly used locations on the filesystem.
  path_provider: ^1.1.0

  # Http client for Dart, which supports Interceptors, Global configuration,
  #  FormData, Request Cancellation, File downloading, Timeout etc.
  dio: ^2.1.3

  # A Flutter plugin to store data in secure storage.
  flutter_secure_storage: ^3.2.1+1

  # Flutter plugin for reading and writing simple key-value pairs. Wraps NSUserDefaults on iOS and SharedPreferences on Android
  shared_preferences: ^0.5.2

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  intl_translation: ^0.17.4

flutter:
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - .config
    - assets/images/
    - assets/icons/

I get an exception when I try to change app language to the newly added one (the third option on the screenshot) tzm-language

flutter: tzm_MA
flutter: UpdateLocale
flutter: Transition { currentState: LocaleUpdated { locale: fr_FR }, event: UpdateLocale, nextState: LocaleUpdated { locale: tzm_MA } }
flutter: ════════
flutter: Warning: This application's locale, tzm_MA, is not supported by all of its
flutter: localization delegates.
flutter: > A AppLocalizations delegate that supports the tzm_MA locale was not found.
flutter: See https://flutter.dev/tutorials/internationalization/ for more
flutter: information about configuring an app's locale, supportedLocales,
flutter: and localizationsDelegates parameters.
flutter: ════════
flutter:
flutter: tzm_MA
flutter: true
flutter: fr_FR
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Invalid argument(s): Invalid locale 'tzm_MA'
#0      Intl._throwLocaleError 
package:intl/intl.dart:239
#1      Intl.verifiedLocale 
package:intl/intl.dart:233
#2      new DateFormat 
package:intl/…/intl/date_format.dart:246
#3      _TzmMaterialLocalizationsDelegate.load 
package:smt_mobile/…/language/tamazight_localizations.dart:25
<asynchronous suspension>
#4      _loadAll 
package:flutter/…/widgets/localizations.dart:57
#5      _LocalizationsState.load 
package:flutter/…/widgets/localizations.dart:508
#6      _LocalizationsState.didUpdateWidget 
package:flutter/…/widgets/localizations.dart:497
#7      StatefulElement.update 
package:flutter/…/widgets/framework.dart:3879
#8      Element.updateChild 
package:flutter/…/widgets/framework.dart:2753
#9      ComponentElement.performRebuild 
package:flutter/…/widgets/framework.dart:3750
#10     Element.rebuild (package:flutter/src/widgets/framewor<…>

flutter analyze:

Analyzing smt_mobile...                                                 
No issues found! (ran in 3.9s)

flutter doctor -v

[✓] Flutter (Channel stable, v1.5.4-hotfix.2, on Mac OS X 10.14.4 18E226, locale fr-FR)
    • Flutter version 1.5.4-hotfix.2 at /Users/hamid/tools/flutter
    • Framework revision 7a4c33425d (3 weeks ago), 2019-04-29 11:05:24 -0700
    • Engine revision 52c7a1e849
    • Dart version 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/hamid/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.2.1, Build version 10E1001
    • ios-deploy 1.9.4
    • CocoaPods version 1.6.1

[✓] Android Studio (version 3.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 32.0.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] IntelliJ IDEA Ultimate Edition (version 2019.1.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 35.3.3
    • Dart plugin version 191.7141.49

[✓] VS Code (version 1.34.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.0.2

[✓] Connected device (1 available)
    • iPhone X • 1DCF973E-04B2-45AB-BF99-ED3D3EEEE9C2 • ios • com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator)

Thank you so much for your help

boukmi commented 5 years ago

Any help please?

timsneath commented 4 years ago

We're closing this issue because it seems to be a question or request for help rather than a clearly reproducible bug, regression or new feature request.

Good places to ask questions or work through problems where you're more likely to get a fast response include:

Thanks for using Flutter!

TahaTesser commented 4 years ago

Closing based on this comment

github-actions[bot] commented 3 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.