Supporting multiple languages for constant strings in Flutter
Create a Localizations.dart file
Add the following code to that file:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show SynchronousFuture;
class DemoLocalizations {
DemoLocalizations(this.locale);
final Locale locale;
static DemoLocalizations of(BuildContext context) {
return Localizations.of<DemoLocalizations>(context, DemoLocalizations);
}
static Map<String, Map<String, String>> _localizedValues = {
'en': {
'title': 'App title',
'googleLogin': 'Login with Google'
},
'es': {
'title': 'Título de App',
'googleLogin': 'Conectar con Google'
},
};
String get title {
return _localizedValues[locale.languageCode]['title'];
}
String get googleLogin {
return _localizedValues[locale.languageCode]['googleLogin'];
}
}
class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations> {
const DemoLocalizationsDelegate();
@override
bool isSupported(Locale locale) => ['en', 'es'].contains(locale.languageCode);
@override
Future<DemoLocalizations> load(Locale locale) {
// Returning a SynchronousFuture here because an async "load" operation
// isn't needed to produce an instance of DemoLocalizations.
return new SynchronousFuture<DemoLocalizations>(new DemoLocalizations(locale));
}
@override
bool shouldReload(DemoLocalizationsDelegate old) => false;
}
Import Localizations.dart into the file where you use the strings.
Add the delegate
DemoLocalizationsDelegate
in theMaterialApp
MaterialApp(
localizationsDelegates: [
MyLocalizationsDelegate(),
],
...
)
- Substitute
new Text("App Title"),
withnew Text(DemoLocalizations.of(context).title),
For each new string you want to localize, you need to add the translated text to each language's map and then add the String get... line. It's a bit cumbersome but it does what you need it to.
This is a quick overview of one way of doing it. You can read more about it in the Flutter docs: https://flutter.io/tutorials/internationalization/
I asked on gitter and I got the following:
Translation/Internationalization isn't a feature we consider "done" yet. https://pub.dartlang.org/packages/intl works in Flutter. We have a bug tracking this more generally: flutter/flutter#393
More complete internationalization (i18n) and accessibility support are two of the big arcs of work ahead of Flutter in the coming months. Another example of i18n work we have planned, is completing Right-to-left (RTL) layouts for our provided Widgets (e.g. teaching the Material library's Scaffold to place the Drawer on the left when the locale is an RTL language). RTL Text support works today, but there are no widgets which are out-of-the-box RTL-layout aware at this moment.