Flutter — how to implement Multilingual i10n functionality
Service Delivery Management App
welcome back friends, In our previous blog, we presented an expedited demonstration of the Ride or Service Delivery Management application, which utilizes the Flutter platform coupled with the Parse back-end service by Back4App.
You can access the complete source code here.
In case you prefer video blogs, here is a link to video tutorial.
If you are finding this blog for the first time, please access previous blogs for a quick demo, about how to setup your project, build first hand UI pages. so that you know exactly what to expect in this and following blogs.
In today’s session, we are going to make our app multilingual. I will show you how you can implement a functionality which let’s user pick their preferred language and entire app changes UI into said language.
Our idea is to make it super straightforward: users can just click one little menu button, pick their preferred language and that changes the app’s language on the fly.
First step is to use `flutter_localizations`, add the package as a dependency to your `pubspec.yaml` file, as well as the `intl` package:
flutter pub add flutter_localizations --sdk=flutter
flutter pub add intl:any
This creates a `pubspec.yaml` file with the following entries:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: any
after we installed required dependencies, let’s update `app.dart` file.
// please see comple-te script source in the GitHub repository; the excerpt below focuses only on localization-related segments portion of the code responsible solely for handling localization.
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class _AppState extends State<App> {
...
// Locale _locale = "en" as Locale;
Locale _locale = const Locale('en');
// setLocale method dynamically changes language
void setLocale(Locale value) {
setState(() {
_locale = value;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateTitle: (context) {
return AppLocalizations.of(context)!.helloWorld;
},
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
locale: _locale,
home: LogIn(handleBrightnessChange: handleBrightnessChange, setLocale: setLocale)
},
);
}
}
// notice, how setLocale function is passed through page constructor
home: LogIn(handleBrightnessChange: handleBrightnessChange, setLocale: setLocale)
don’t forget to include setLocale in your App state definition.
class LogIn extends StatefulWidget {
static const routeName = '/login';
LogIn({super.key, required this.handleBrightnessChange
, required this.setLocale});
Function(bool useLightMode) handleBrightnessChange;
Function(Locale locale) setLocale;
@override
LogInState createState() => LogInState();
}
adding Multilingual Drop-down Menus in Navigation Bars for Enhanced User Experience
PreferredSizeWidget createCustomerNavBar(BuildContext context, widget) {
return AppBar(
leading: IconButton(
icon: const Icon(Icons.electric_rickshaw_outlined, color: Colors.greenAccent)),
// using localization strings
title: Text(AppLocalizations.of(context)!.cAppTitle, style: cBodyText,),
actions: <Widget>[
PopupMenuButton(
initialValue: 1,
tooltip: 'toggle language',
onSelected: (item) {
switch (item) { // Your Enum Value which you have passed
case 1:
widget.setLocale(const Locale.fromSubtags(languageCode: 'en'));
break;
case 2:
widget.setLocale(const Locale.fromSubtags(languageCode: 'es'));
break;
}
},
itemBuilder: (BuildContext context) => <PopupMenuEntry>[
const PopupMenuItem(
value: 1,
child: Text('English'),
),
const PopupMenuItem(
value: 2,
child: Text('Spanish', style: cNavText,),
),
],
),
...
],
);
}
Finally, utilize the provided code for dynamic display of chosen languages based on user selection from available options.
return MaterialApp(
onGenerateTitle: (context) {
return AppLocalizations.of(context)!.helloWorld; // use localization strings
}...
now we will need to build localization files to hold on to string translations. Add a new `.yaml` file to the root directory of the Flutter project. Name this file `l10n.yaml` and include following content:
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
This file configures the localization tool. In this example, you’ve done the following:
- Put the App Resource Bundle (`.arb`) input files in `${FLUTTER_PROJECT}/lib/l10n`. The `.arb` provide localization resources for your app. — Set the English template as `app_en.arb`. — Told Flutter to generate localization in the `app_localization.dart` file.
In `${FLUTTER_PROJECT}/lib/l10n`, add the `app_en.arb` template file. For example:
{
"helloWorld": "Hello World!",
"@helloWorld": {
"description": "The conventional newborn programmer greeting"
}
}
Add another bundle file called `app_es.arb` in the same directory. In this file, add the Spanish translation of the same message.
{
"helloWorld": "¡Hola Mundo!"
}
Now, run `flutter pub get` or `flutter run` and code generation takes place automatically.
Please do not forget to Like and bookmark this article and subscribe to my YouTube and X accounts to more content.