flutterdartinternationalizationflutter-intl

How to load all dart DateFormat locale in flutter?


In Flutter app, intl package load only 15 languages. However Dart DateFormat support many more. I do not need translation, but need correct DateFormat. How to load all DateFormat locale?


Solution

  • In your highest StatefulWidget add these imports

    import 'package:intl/intl.dart';
    import 'package:intl/date_symbol_data_local.dart';
    

    in its State, override initState and add

      @override
      void initState() {
        super.initState();
        initializeDateFormatting();
      }
    

    For example

    import 'package:flutter/material.dart';
    import 'package:intl/intl.dart';
    import 'package:intl/date_symbol_data_local.dart';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Intl Demo',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new MyHomePage(title: 'Intl Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      DateFormat dateFormat;
      DateFormat timeFormat;
    
      @override
      void initState() {
        super.initState();
        initializeDateFormatting();
        dateFormat = new DateFormat.yMMMMd('cs');
        timeFormat = new DateFormat.Hms('cs');
      }
    
      void _refresh() {
        setState(() {});
      }
    
      @override
      Widget build(BuildContext context) {
        var dateTime = new DateTime.now();
        return new Scaffold(
          appBar: new AppBar(
            title: new Text(widget.title),
          ),
          body: new Center(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(dateFormat.format(dateTime)),
                new Text(timeFormat.format(dateTime)),
              ],
            ),
          ),
          floatingActionButton: new FloatingActionButton(
            onPressed: _refresh,
            tooltip: 'Refresh',
            child: new Icon(Icons.refresh),
          ),
        );
      }
    }
    

    Dart mostly uses the ISO 631 2 letter codes, with country variants if applicable. For example: ja, en_US, en_GB, zh_HK, zh_CN. Occasionally it uses a 3 letter code. To find the full list just search for DateSymbols in the file date_symbol_data_local.dart

    The cs language displays this