Flutter global material localizations and initialize date formatting not working together
Asked Answered
U

2

19

I am using localisation in a flutter app but also want to localise the date format using initialise date formatting. My main looks like this ...

  void main() {
    runApp(new MaterialApp(
    supportedLocales:
    [const Locale('en', 'US'),
    const Locale('en', 'AU')],
    localizationsDelegates: [
      const DemoLocalizationsDelegate(),
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate
    ],
    home: new ThirdPageWidget(),
    navigatorObservers: [routeObserver],
    ));
 }

Also I have a initializeDateFormatting in a stateful widget like this ...

@override
void initState() {
   super.initState();
   initializeDateFormatting().then((_) {
      dateFormat = new DateFormat.yMd('en_AU');
      print(dateFormat.format(DateTime.now()));
});

Now when the locale is en_AU the format of the date is month/day/year american style but when I remove this line of code

GlobalMaterialLocalizations.delegate,

The date correctly displays day/month/year. Does any one know what I can do to fix this? How important is it to have the GlobalMaterialLocalizations.delegate?

Uncanny answered 10/9, 2018 at 1:34 Comment(0)
C
36

I solved the problem by adding in pubspec.yaml the following dependency:

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

be careful with the indentation.

Carmel answered 30/12, 2019 at 22:19 Comment(3)
Probably also have to import this to the main.dart: import 'package:flutter_localizations/flutter_localizations.dart'; Printer
It's yaml, of course indentation is important :)Jolandajolanta
and run flutter pub getMahout
B
1

I too had this issue and, after playing around a little, found that when using Material localisations it appears default to US if you do not specify the supported locales.

Adding the following supported locales allowed the UK date format to be shown rather than the US one.

        localizationsDelegates: [
          const DemoLocalizationsDelegate(),
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        supportedLocales: [
          const Locale('en', 'US'), // English US
          const Locale('en', 'GB'), // English UK
          // ... other locales the app supports
        ],

I didn't have to explicitly initialise the DateFormat class as Material appears to handle this too.

Barbra answered 29/7, 2019 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.