One thing Flutter doesen’t let you do out of the box is multilanguage support. There are a few ways around this issue, today we’ll see one of those. It’s not an hard way but it gives you a good control over your output.
1. Yaml file additions
First of all we’ll need to add a few lines to our .yaml file. We’ll need to add two packages, the intl package and flutter_localizations:
2. The localizationsDelegates and localeResolutionCallback
The two most important parts of our configuration are the localizationsDelegates and the localeResolutionCallback, let’s check the first. The
LocalizationsDelegates are classes which define a series of localized values by loading them. On our main class, as parameters for the MaterialApp we need to set our delegates:
AppLocalizationsDelegate is our custom class that will manage localized data, where we’ll need to set our
supportedLanguages and which language to load. So we’ll need to create also an abstract class called Languages, that will extend our subclassed for all our languages:
LanguageIt/Es/De/En are our classes with localized strings, but first we’ll have to add a string to our abstract Languages, which will need us to add it also to our other files:
Next step is to add a
localeResolutionCallback to our
MaterialApp. This will determine which language is the one our app should be displayed. Also we’ll need to add the supportedLocales property, to let our
MaterialApp know which ones are supported.
We are ok for now. To use localized strings then we’ll need to call Languages with the string we added:
The result will be
- “Io sono un testo” for Italian language
- “Ich bin ein Text” for German language
- “Soy un texto” for Spanish language
- “I am a text” for english language or a not supported language.
Most apps will be ok this way, the phone language will determine which locale is the default for our app, but we can add a bit more spice by making our app change language on the fly, but we’ll need to add a bit more code.
3. Switch on the go
To achieve our next goal we’ll need to add a state management package, I choose Provider as, in my opinion is pretty easy to implement and understand. We’ll need to create a
ChangeNotifier which will contain the current locale and initialize it as the system one:
Next, we have to create a setter for our new locale and call
notifyListeners() in order to let our app know when to redraw itself:
Then we’ll have to configure Provider on our main and get the locale from the Provider, getting it as a consumer. Be aware that the locale getter is a future, so we’ll have to add a FutureBuilder:
Last, but not least, let’s add some buttons that will change our language:
This is a pretty easy implementation, we can also add the locale as a shared preference so it is saved and language change can be permanent, but i’ll leave to you any other implementation you need. Good work, we did it also today!