Localization (translation) done ‘easy’ in flutter app

Reading time: 2 minutes

The important thing for most mobile applications is to have localization for 2 or more languages, which makes a much better user experience in general. There are few solutions out there. I found this one especially easy to use easy_localization.

First, let’s get it:

dependencies:
  flutter:
    sdk: flutter
	easy_localization: ^2.3.3

This is how ‘en-US.json’ looks inside:

{
  "hello" : "Hello"
}

Similar ‘uk-UA.json’:

{
  "hello" : "Привіт"
}

We’ll need to let flutter know that this files need to be included in app:

flutter:
  uses-material-design: true
  assets:
    - assets/translations/

In order to use easy_translation, we will wrap App with EasyLocalization class, describing supported locales, the path to find them and fallback locale to use as default:

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_examples/example/translation_example.dart';

void main() {
  runApp(EasyLocalization(
      supportedLocales: [Locale('en', 'US'), Locale('uk', 'UA')],
      path: 'assets/translations',
      fallbackLocale: Locale('en', 'US'),
      child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: TranslationExample(),
    );
  }
}

Example how to use this from Text widget:

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';

class TranslationExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Center(child: Text("${tr('hello')}")));
  }
}

We include “tr(‘key’)” as placeholder for our localized string.

Result will depend on your smartphone language settings, like this:

Leave a Reply

Your email address will not be published. Required fields are marked *