Flutter localization in easy steps

Overview

localize_and_translate

Flutter localization in easy steps

Pub Example

Share your love to this ❤️

Fork Star Watch

Screenshots

screenshot screenshot

Tutorial

Video

Methods

Method Job
init() initialize things, before runApp()
"word".tr() word translation - string extension
translate('word') word translation
translate('word',{"key":"value"}) word translation with replacement arguments
setNewLanguage(context,newLanguage:'en',restart: true, remember: true,) change language
isDirectionRTL() is Direction RTL check
currentLanguage Active language code
locale Active Locale
locals() Locales list
delegates Localization Delegates

Installation

  • add .json translation files as assets
  • For example : 'assets/lang/ar.json' | 'assets/lang/en.json'
  • structure should look like
{
    "appTitle": "تطبيق تجريبى", 
    "buttonTitle": "English", 
    "textArea": "هذا مجرد نموذج للتأكد من اداء الأداة"
}
  • define them as assets in pubspec.yaml
flutter:
  assets:
    - assets/lang/en.json
    - assets/lang/ar.json

Initialization

  • Add imports to main.dart
  • Make main() async and do the following
  • Ensure flutter activated WidgetsFlutterBinding.ensureInitialized()
  • Initialize await translator.init(); with neccassry parameters
  • Inside runApp() wrap entry class with LocalizedApp()
  • Note : make sure you define it's child into different place "NOT INSIDE"
import 'package:flutter/material.dart';
import 'package:localize_and_translate/localize_and_translate.dart';

main() async {
  // if your flutter > 1.7.8 :  ensure flutter activated
  WidgetsFlutterBinding.ensureInitialized();

  await translator.init(
    localeType: LocalizationDefaultType.device,
    languagesList: <String>['ar', 'en'],
    assetsDirectory: 'assets/lang/',
  );

  runApp(
    LocalizedApp(
      child: MyApp(),
    ),
  );
}
  • LocalizedApp() child example -> MaterialApp()
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
      localizationsDelegates: translator.delegates, // Android + iOS Delegates
      locale: translator.locale, // Active locale
      supportedLocales: translator.locals(), // Locals list
    );
  }
}

Usage

  • use translate("appTitle")
  • use setNewLanguage(context, newLanguage: 'ar', remember: true, restart: true);
class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(),
      appBar: AppBar(
        title: Text('appTitle'.tr()),
        // centerTitle: true,
      ),
      body: Container(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            SizedBox(height: 50),
            Text(
              'textArea'.tr(),
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 35),
            ),
            OutlineButton(
              onPressed: () {
                translator.setNewLanguage(
                  context,
                  newLanguage: translator.currentLanguage == 'ar' ? 'en' : 'ar',
                  remember: true,
                  restart: true,
                );
              },
              child: Text('buttonTitle'.tr()),
            ),
          ],
        ),
      ),
    );
  }
}

Contributors

Contributors List

Comments
  • Tried calling: restart() when try to convert the app language

    Tried calling: restart() when try to convert the app language

    I have a problem, when I try to converter the app language, I faced a problem,

    [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'restart' was called on null. E/flutter ( 6490): Receiver: null E/flutter ( 6490): Tried calling: restart() E/flutter ( 6490): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5) E/flutter ( 6490): #1 LocalizedApp.restart (package:localize_and_translate/src/main.class.dart:258:11) E/flutter ( 6490): #2 LocalizeAndTranslate.setNewLanguage (package:localize_and_translate/src/main.class.dart:197:20) E/flutter ( 6490): <asynchronous suspension> E/flutter ( 6490): #3 _settingsState._onBackPressed.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:erp_accounting_app/drawer_pages/setting.dart:159:32) E/flutter ( 6490): #4 new Future.delayed.<anonymous closure> (dart:async/future.dart:326:39)

    this is my code :

    translator.setNewLanguage( context, newLanguage: translator.currentLanguage == 'ar' ? 'en' : 'ar', remember: true, restart: true, );

    what is the problem ??

    bug 
    opened by mohmmed750 9
  • Index out of range on Web

    Index out of range on Web

    Everything is working fine with me on iOS and Android but once I run my app on the web (Chrome) I got this error from the widget LocalizedApp

    ════════ Exception caught by widgets library ═══════════════════════════════════
    The following IndexError was thrown building MyApp(dirty):
    RangeError (index): Index out of range: no indices are valid: 0
    
    The relevant error-causing widget was
    MyApp
    lib/main.dart:54
    When the exception was thrown, this was the stack
    dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 236:49  throw_
    dart-sdk/lib/_internal/js_dev_runtime/private/js_array.dart 581:7             _get]
    packages/localize_and_translate/src/main.dart 192:51                          get locale
    packages/UnitedPalestine/main.dart 85:28                                      build
    packages/flutter/src/widgets/framework.dart 4569:28                           build
    ...
    
    

    Any extra steps I need to do to make it works on the web?

    opened by Dahleh 4
  • Text direction doesnt get updated when changing app locale with setLanguage()

    Text direction doesnt get updated when changing app locale with setLanguage()

    The app should be killed and restarted again after changing language with setLanguage() for the text direction to update(RTL ,LTR). The restart filed does restart the app and updates text but doesn't update text direction

    bug 
    opened by real-john-doe 4
  • i don't really know where is the problem

    i don't really know where is the problem

    i made this function it should be working it checks if a shared preference has ar value and it should enter this function, it does enter the function but it some how exists in "to" part after checking it using the breakpoints 3b0376ab-2d03-46a9-914c-087a85774201 thanks in advance

    bug wontfix 
    opened by cherifburette 4
  • Unhandled Exception: Null check operator used on a null value

    Unhandled Exception: Null check operator used on a null value

    [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value #0 LocalizedApp.restart (package:localize_and_translate/localize_and_translate.dart:20:58) #1 LocalizeAndTranslate.setNewLanguage (package:localize_and_translate/src/main.dart:134:20)

    enhancement 
    opened by gabrielpatricksouza 2
  • Migrating from 2.2.2 to 3.0.2 not working

    Migrating from 2.2.2 to 3.0.2 not working

    when i run the app it throws this error

    I/flutter (31556): --LocalizeAndTranslate : deviceLocale(ar)
    E/flutter (31556): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at line 53, character 1)
    E/flutter (22483): }
    E/flutter (22483): ^
    E/flutter (22483): 
    E/flutter (22483): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1394:5)
    E/flutter (22483): #1      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:918:20)
    E/flutter (22483): #2      _parseJson (dart:convert-patch/convert_patch.dart:31:10)
    E/flutter (22483): #3      JsonDecoder.convert (dart:convert/json.dart:505:36)
    E/flutter (22483): #4      JsonCodec.decode (dart:convert/json.dart:153:41)
    E/flutter (22483): #5      LocalizeAndTranslate.initLanguage (package:localize_and_translate/src/main.class.dart:107:20)
    E/flutter (22483): <asynchronous suspension>
    E/flutter (22483): #6      LocalizeAndTranslate.init (package:localize_and_translate/src/main.class.dart:87:13)
    E/flutter (22483): <asynchronous suspension>
    E/flutter (22483): #7      main (package:system/main.dart:17:20)
    E/flutter (22483): #8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:241:25)
    E/flutter (22483): #9      _rootRun (dart:async/zone.dart:1184:13)
    E/flutter (22483): #10     _CustomZone.run (dart:async/zone.dart:1077:19)
    E/flutter (22483): #11     _runZoned (dart:async/zone.dart:1619:10)
    E/flutter (22483): #12     runZonedGuarded (dart:async/zone.dart:1608:12)
    E/flutter (22483): #13     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:233:5)
    E/flutter (22483): #14     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
    E/flutter (22483): #15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
    E/flutter (22483): 
    

    here is how i am initializing it

    void main() async{
      WidgetsFlutterBinding.ensureInitialized();
      await translator.init(
        localeDefault: LocalizationDefaultType.device,
        languagesList: <String>['ar', 'en'],
        assetsDirectory: 'assets/langs/',
      );
    
    
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp , DeviceOrientation.portraitDown])
          .then((_) => runApp(
         Phoenix(
          child: LocalizedApp(
            child: BillingSystem(),
            ),
          )
        ),
      );
    }
    
    class BillingSystem extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          localizationsDelegates: translator.delegates, // Android + iOS Delegates
          locale: translator.locale, // Active locale
          supportedLocales: translator.locals(),
          title: 'Billing System',
          theme: ThemeData(
            primaryColor: Color(0xff146eb4),
              textTheme:
              TextTheme(
                  headline6: TextStyle(color: Colors.black , fontSize: 22.0 , fontWeight: FontWeight.w500),
                  bodyText1: TextStyle(color: Colors.black , fontSize: 16) ,
              )
          ),
          home: AuthenticationPage(),
        );
      }
    }
    
    
    opened by RYOKSEC 2
  • Add arguments to translate method

    Add arguments to translate method

    whats changed translate method can now accept arguments to be replaced with passed values translator.translate("word",{"{a1}":"value1","{a2}","value2"}) examples

    ///we well use translator.translate("word",{"{a1}":"banana","{a2}":"orange"})
    "word":"This is {a1} and {a2}" => This is banana and orange
    "word":"This is {a1} and {a2}, {a1} is good" => This is banana and orange, banana is good
    

    note as this is a package not a plugin i removed android and ios code to avoid version conflicts

    opened by mo-ah-dawood 2
  • supporting web

    supporting web

    localize and translate are not supporting flutter web yet?

    i get this error when trying to run as web :

    --LocalizeAndTranslate : Google(true) | LangList[ar, en] | Dir(assets/langs/) | Active(en.json)
    Error: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/package_info)
    
    invalid 
    opened by AhmedWagdi1 1
  • Unhandled Exception: NoSuchMethodError: The method 'restart' was called on null.

    Unhandled Exception: NoSuchMethodError: The method 'restart' was called on null.

    [VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'restart' was called on null. Receiver: null Tried calling: restart() #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5) #1 LocalizedApp.restart (package:localize_and_translate/src/main.class.dart:258:11) #2 LocalizeAndTranslate.setNewLanguage (package:localize_and_translate/src/main.class.dart:197:20)

    duplicate 
    opened by ThamerRamzi 1
  • Tried calling: restart() when i try to convert the app language

    Tried calling: restart() when i try to convert the app language

    I have a problem, when I try to converter the app language, I faced a problem,

    [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'restart' was called on null. E/flutter ( 6490): Receiver: null E/flutter ( 6490): Tried calling: restart() E/flutter ( 6490): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5) E/flutter ( 6490): #1 LocalizedApp.restart (package:localize_and_translate/src/main.class.dart:258:11) E/flutter ( 6490): #2 LocalizeAndTranslate.setNewLanguage (package:localize_and_translate/src/main.class.dart:197:20) E/flutter ( 6490): <asynchronous suspension> E/flutter ( 6490): #3 _settingsState._onBackPressed.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:erp_accounting_app/drawer_pages/setting.dart:159:32) E/flutter ( 6490): #4 new Future.delayed.<anonymous closure> (dart:async/future.dart:326:39)

    this is my code :

    translator.setNewLanguage( context, newLanguage: translator.currentLanguage == 'ar' ? 'en' : 'ar', remember: true, restart: true, );

    what is the problem ??

    duplicate 
    opened by mohmmed750 1
  • remove 404 from not found strings

    remove 404 from not found strings

    at first this package is very good,

    please remove 404 from the string if the key is not found

    Why

    in some cases i forgot to set the key in my json file so i need to use the default one The good advantage for removing it is to allow us use a default strings may be just make one json file for Arabic and leave the English use the default strings note that the keys may be readable strings like this "Withdraw profits": "سحب الأرباح" now if the language is arabic the right side will be used else the left will be used

    enhancement 
    opened by mo-ah-dawood 1
  • UI is partially re-created after calling setNewLanguage.

    UI is partially re-created after calling setNewLanguage.

    We again ran into the problem that after calling method setNewLanguage(context, newLanguage: newLang, restart: true) part of the UI is updated with new translates, but part is not, including the previous screen in the back stack. If I open a new screen, then it is displayed with a new translation. We managed to fix the problem some time ago, but now it has reappeared.

    A rough sketch of the creation of LocalizedApp:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      final locale = Preferences().language;
      await translator.init(
        language: locale,
        languagesList: ['en', 'ru'],
        assetsDirectory: 'assets/i18n/',
      );
    
      runZonedGuarded(
        () => runApp(
          LocalizedApp(
            child: DependenciesWidget( // Providers
              environment: environment,
              child: ConfiguratorWidget( // BlocListeners without using UI staff
                  child: BlocListener<LocalizationBloc, LocalizationState>(
                    listener: (context, state) {
                      final localeCode = state.language.localizationPackageValue;
                      var newLang = localeCode.length > 2
                          ? localeCode.substring(0, 2)
                          : localeCode;
                      translator.setNewLanguage(
                        context,
                        newLanguage: newLang,
                        restart: true,
                      );
                    },
                    child: MaterialAppWrapperWidget(),
                  ),
              ),
            ),
          ),
        ),
        FirebaseCrashlytics.instance.recordError,
      );
    }
    
    • flutter doctor Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 2.0.5, on macOS 11.6 20G165 darwin-x64, locale en-GB) [✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2) [✓] Xcode - develop for iOS and macOS [✓] Chrome - develop for the web [!] Android Studio (version 2020.3) ✗ Unable to find bundled Java version. [✓] Connected device (2 available)
    bug 
    opened by TaranenkoDenis 0
  • WEB: When change lang to ar drawer doesn't change direction.

    WEB: When change lang to ar drawer doesn't change direction.

    Hi, There is an issue when changing the language from en to ar in Flutter web the direction of some widgets doesn't change, but in mobile apps (android and ios) working perfectly.

    bug 
    opened by ossama0808 1
  • ar widget direction when change the lang without restart

    ar widget direction when change the lang without restart

    must restart the app when change the lang from ar or to ar ?? i need to change the direction of the widget without restarting the app .. give any advice of the way to make that .. thank you anyway .

    enhancement 
    opened by eslam-elswesy 1
  • unable to load asset error when the users device language is not present.

    unable to load asset error when the users device language is not present.

    if users device locale is Japanese for example and japanese isnt tranlated yet, if localeDefault: LocalizationDefaultType.device, then the above error will be thrown, if localeDefault: LocalizationDefaultType.asDefined,, there will be no exception but for languages that are actually translated, still the default en locale will be used

    enhancement 
    opened by real-john-doe 0
Owner
Mohamed Sayed
Software Engineer | in love with flutter
Mohamed Sayed
WIP: generate easy localization key code

Generates translation key code for the easy localization package. Support for json and yaml formats.You can see examples in the assets/ folder. Gettin

null 3 Oct 24, 2022
Flutter plugin to display a simple steps indicator line widget

steps_indicator A simple steps indicator widget Installation Add steps_indicator: ^1.3.0 in your pubspec.yaml dependencies. And import it: import 'pac

Hugo EXTRAT 49 Oct 18, 2022
Open source Flutter package, bar indicator made of a series of selected and unselected steps

Step Progress Indicator Open source Flutter package, bar indicator made of a series of selected and unselected steps. Made by Sandro Maglione, check o

Sandro Maglione 138 Dec 15, 2022
It's an open source project for the steps tracking (Pedometer) built with Flutter.

Flutter Steps Tracker It's an open source project for the steps tracking (Pedometer) built with Flutter and integrated with Firebase as the initial ba

Tarek Alabd 56 Nov 5, 2022
A Flutter step_tracker plugin is collect information from user and display progress through a sequence of steps. this plugin also have privilege for fully customization from user side. like flipkart, amazon, myntra, meesho.

step_tracker plugin A Flutter step_tracker plugin is collect information from user and display progress through a sequence of steps. this plugin also

Roshan nahak 5 Oct 21, 2022
Boozin fitness - A sample app to that will pull data from Google Fit to get the steps count and calories burned

boozin_fitness A sample app to that will pull data from Google Fit to get the st

Abhishek Kumar Gupta 1 Nov 23, 2022
Dart Alura Course First Steps with Language

Dart: primeiros passos com a linguagem This repository contains all the files de

Gabriel Pessoni 13 Nov 23, 2022
SmallTask - Take small steps to achieve big things

SmallTask - Take small steps to achieve big things. Have you ever felt that when you are working on a project you kinda get confused about what to do?

Yuji 2 Mar 7, 2022
A basic boilerplate template for starting a Flutter GetX project. GetX, Dio, MVVM, get CLI, Localization, Pagination etc are implemented.

Flutter GetX Template (GetX, Dio, MVVM) This Flutter Template using GetX package for State management, routing and Dependency Injection (bindings). We

Hasan Abdullah 214 Jan 9, 2023
TOML localization for Flutter

toml_localizations A minimal TOML localization package for Flutter. TOML is a minimal, easy to read, configuration file format, which allows you to re

Erlend 1 Mar 8, 2022
Yet another localization approach in Flutter

Flutter Global Summit Vol.2 schedule Source code of the mobile application that displays the schedule of the Flutter Global Summit Vol.2 conference th

Anna Leushchenko 3 Mar 24, 2022
Kurdish localization for flutter

Flutter Kurdish Localization ?? This package provides unofficial localization su

Amin Samad 16 Oct 25, 2022
"FlutterMoneyFormatter" is a Flutter extension to formatting various types of currencies according to the characteristics you like, without having to be tied to any localization.

FlutterMoneyFormatter FlutterMoneyFormatter is a Flutter extension to formatting various types of currencies according to the characteristics you like

Fadhly Permata 81 Jan 1, 2023
A tool which automatically generates Flutter localization resources from CSV and Excel files.

flappy_translator A tool which automatically generates Flutter localization resources from CSV and Excel files. This is especially useful as any team

Smart&Soft 55 Sep 15, 2022
Flutter project. The sample of Localization.

localization A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Aoi Umigishi 1 Jan 5, 2022
Create flutter project with all needed configuration in two minutes (theme, localization, connect to firebase, FCM, local notifications, safe API call, error handling, animation..etc)

Flutter GetX Template Flutter Getx template to make starting project fast and easy . Introduction We all face the same problem when we want to start a

Emad Beltaje 150 Jan 7, 2023
Generates a new Flutter app with http client, theme, routing and localization features.

Starter Template Generates a new Flutter app with http client, theme, routing and localization features. Brick Uses: dio as http client pretty_dio_log

Cem Avcı 12 Nov 3, 2022
Note provider - Note App using Provider state management, Sqflite and Localization for two language Arabic and English.

note_provider Sqflite with provider statemanagement Getting Started This project is a starting point for a Flutter application. A few resources to get

Mohanned Anwar 0 Jan 1, 2022
Internationalization and localization support

Provides internationalization and localization facilities, including message translation, plurals and genders, date/number formatting and parsing, and

Dart 497 Dec 21, 2022