gen_lang is a dart library for internationalization. Extracts messages to generate dart files required by Intl, inspired by Intl_translation and Flutter i18n

Overview

gen_lang

gen_lang is a dart library for internationalization. Extracts messages to generate dart files required by Intl.

Now, three steps for internationalization

  1. Preparing Json files
  2. Run gen_lang
  3. Use it in coding

Installation

Add these libraries into pubspec.yaml

dependencies: 
    flutter_localizations: 
        sdk: flutter 
dev_dependencies:
    gen_lang: 0.1.3

Usage

pub run gen_lang:generate

A below table shown all supported arguments:

Argument Description
--source-dir A source folder contains all string json files (defaults to "res/string")
--output-dir A output folder stores all generated files (defaults to "lib/generated")
--template-locale Use string_{template-locale}.json as a template to search KEY. If string_en does not exist, this script will use the first string json file as a template (defaults to "en")

Source of Json Files

By default, the json files are required to locate at res/string. Using --source-dir argument can change the default source path. These files must be named in this pattern string_{Locale}.json

Example of the files,

|--- lib 
|--- res 
     |--- string 
         |--- string_en.json 
         |--- string_zh_TW.json 
         |--- string_ja.json 

Supported Message Type

Simple message

Define a json key and message without parameters

{ 
    "simpleMessage": "This is a simple Message"
}

Message with parameters

Define a message with parameters. Use ${parameterName} in a message.

{
    "messageWithParams": "Hi ${yourName}, Welcome you!"
}

Plural messages with parameters

Define messages in a plural form. ${how many} is a reserved parameter in a plural message. This parameters support integer only. For Intl, Intl.plural() supports these plural keyword including 'Zero', 'One', 'Two', 'Few', 'Many' and 'Other'. Define a json key into this pattern {jsonKey} {pluralKeyword}. For 'Other', need to define 'POther' for the plural keyword.

Example

{ 
    "pluralMessageZero": "Hi ${interviewerName}, I have no working experience.", 
    "pluralMessageOne": "Hi ${interviewerName}, I have one year working experience.", 
    "pluralMessageTwo": "Hi ${interviewerName}, I have two years of working experience.", 
    "pluralMessageFew": "Hi ${interviewerName}, I have few years of working experience.", 
    "pluralMessageMany": "Hi ${interviewerName}, I worked for a long time.", 
    "pluralMessagePOther": "Hi ${interviewerName}, I have ${howMany} years of working experience."
}

To know plural rules more, please read Intl's plural rules source code.

Gender message with parameters

Define a message in gender form. ${targetGender} is a reserved parameter in a gender message. This parameters support string value with 'male', female' and 'other'. For Intl, Intl.gender() supports these keyword including 'Male', 'Female' and 'Other'. Define a json key into this pattern {jsonKey} {genderKeyword}. For 'Other', need to define 'GOther' for the gender keyword.

Example

{ 
    "genderMessageMale": "Hi ${name}, He is boy.", 
    "genderMessageFemale": "Hi ${name}, She is girl", 
    "genderMessageGOther": "Hi ${name}, he/she is boy/girl." 
}

Usage of i18n.dart

The script will generate two files into the output folder including i18n.dart and messages_all.dart. Import i18n.dart into your source code. Then finish internationalization tasks.

Example

import 'package:gen_lang_example/generated/i18n.dart';

...

MaterialApp(
      localizationsDelegates: [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: S.delegate.supportedLocales,
      
      ...
      ...

        S.of(context).simpleMessage; // Simple Message 
        S.of(context).messageWithParams('developer'); // Message with parameters
        S.of(context).pluralMessage(10, 'King Wu'); // Plural Message with parameters
        S.of(context).genderMessage('male', 'King Wu'); // Gender Message with parameters

Running Script in Example

Go into example folder. Run the command

cd example
pub run gen_lang:generate

Then will generate i18n.dart and messages_all.dart

Comments
  • Remove warning interpolation braces not needed

    Remove warning interpolation braces not needed

    This workaround fixes this issue.

    Basically, it adds an exception for Dart linter so that there is no warnings.

    This trick is heavily used in build_value_generator.

    opened by areille 5
  • Upgrade args Package

    Upgrade args Package

    after upgrading to Flutter 2.0 and update some package to be compatible with Flutter 2.0, i got this issue:

    Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and gen_lang 0.1.3 depends on args >=0.12.1 <2.0.0, flutter_launcher_icons >=0.9.0 is incompatible with gen_lang 0.1.3.
    
    And because no versions of gen_lang match >0.1.3 <0.2.0, flutter_launcher_icons >=0.9.0 is incompatible with gen_lang ^0.1.3.
    

    can you upgrade the args package?

    opened by maerlynflagg 2
  • Usage in BottomNavigationBarItem

    Usage in BottomNavigationBarItem

    Hello,

    First thank you for the good library!

    I'm facing an issue when trying to set a BottomNavigationBarItem Title.

    BottomNavigationBarItem(
                    icon: Icon(Icons.dialpad),
                    title: new Text( S.of(context).example )
                  )
    

    It throws the following errors:

    Invalid constant value.

    The values in a const list literal must be constants. Try removing the keyword 'const' from the list literal.

    Arguments of a constant creation must be constant expressions. Try making the argument a valid constant, or use 'new' to call the constructor

    Using a simple string, such as Text('Test') it works.

    Do you think it's possible to solve this issue?

    Thank you!

    opened by Pexeed 2
  • Build Errors in Null Safety Project Dart 2.13

    Build Errors in Null Safety Project Dart 2.13

    generated files not working anymore.

    is there a way to bring the gen_lang package to the current versions?

    lib/generated/i18n.dart:4126:55: Error: The parameter 'fallback' can't have a value of 'null' because of its type 'Locale', but the implicit default value is 'null'.
     - 'Locale' is from 'dart:ui'.
    Try adding either an explicit non-'null' default value or the 'required' modifier.
      LocaleListResolutionCallback listResolution({Locale fallback}) { 
    

    lib/generated/i18n.dart:15:26: Error: A value of type 'S?' can't be returned from a function with return type 'S' because 'S?' is nullable and 'S' isn't.

    
    lib/generated/i18n.dart:4129:16: Warning: Operand of null-aware operation '??' has type 'Locale' which excludes null.
     - 'Locale' is from 'dart:ui'.
    
    
    lib/generated/i18n.dart:4127:12: Error: A value of type 'Locale Function(List<Locale>, Iterable<Locale>)' can't be returned from a function with return type 'Locale? Function(List<Locale>?, Iterable<Locale>)' because 'List<Locale>?' is nullable and 'List<Locale>' isn't.
     - 'Locale' is from 'dart:ui'.
     - 'List' is from 'dart:core'.
     - 'Iterable' is from 'dart:core'.
        return (List<Locale> locales, Iterable<Locale> supported) {
    
    lib/generated/messages_all.dart:1049:14: Error: The value 'null' can't be returned from a function with return type 'MessageLookupByLibrary' because 'MessageLookupByLibrary' is not nullable.
     - 'MessageLookupByLibrary' is from 'package:intl/message_lookup_by_library.dart' 
    
    opened by maerlynflagg 1
  • error when try to run the app

    error when try to run the app

    Launching lib/config/main_production.dart on Android SDK built for x86 64 in debug mode...
    Initializing gradle...
    Resolving dependencies...
    Running Gradle task 'assembleProductionDebug'...
    
    Compiler message:
    file:///Users/shiv/apps/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_stetho-0.2.2/lib/src/http_client_response.dart:4:7: Error: The non-abstract class 'StethoHttpClientResponse' is missing implementations for these members:
     - HttpClientResponse.compressionState
    Try to either
     - provide an implementation,
     - inherit an implementation from a superclass or mixin,
     - mark the class as abstract, or
     - provide a 'noSuchMethod' implementation.
    
    class StethoHttpClientResponse extends StreamView<List<int>>
          ^^^^^^^^^^^^^^^^^^^^^^^^
    org-dartlang-sdk:///third_party/dart/sdk/lib/_http/http.dart:1967:42: Context: 'HttpClientResponse.compressionState' is defined here.
      HttpClientResponseCompressionState get compressionState;
                                             ^^^^^^^^^^^^^^^^
    Compiler failed on /Users/shiv/projects/ex/flutter_starter_kit/lib/config/main_production.dart
    
    FAILURE: Build failed with an exception.
    
    * Where:
    Script '/Users/shiv/apps/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 665
    
    * What went wrong:
    Execution failed for task ':app:compileflutterBuildProductionDebugX64'.
    > Process 'command '/Users/shiv/apps/flutter/bin/flutter'' finished with non-zero exit value 1
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    
    * Get more help at https://help.gradle.org
    
    BUILD FAILED in 9s
    Finished with error: Gradle task assembleProductionDebug failed with exit code 1
    
    opened by kushwahashiv 1
  • Translation issue with quote

    Translation issue with quote

    Declaring a string that contains ' (for example l'aggiornamento) the resulting generation will contains double quotes.

    Futhermore if you insert a \n the resulting string will be broken because in the generated file the \n breaks the line (it's not kept inside the text) and the string it's splitted into 2 strings and this results in a broken file that cannot be compiled

    Possible solution: use double quote when initialize the string object in the generated file

    opened by dariof28 1
  • When I'm trying to set S.of(context).text to AppBar always en location

    When I'm trying to set S.of(context).text to AppBar always en location

    Location changes correctly but in application bar text always in en location

    `class RegisterPage extends StatelessWidget { final UserRepository userRepository;

    RegisterPage({Key key, @required this.userRepository}) : assert(userRepository != null), super(key: key);

    @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(S.of(context).app_bar_register), ), body: BlocProvider( create: (context) { return RegisterBloc( authenticationBloc: BlocProvider.of(context), userRepository: userRepository, ); }, child: RegisterForm(), ), ); } }`

    opened by artem-bakuta 0
  • Avoid using braces in interpolation when not needed

    Avoid using braces in interpolation when not needed

    Hello,

    I am using last version of this package alongside with dart 2.6.1 :

    dart --version output:

    Dart VM version: 2.6.1 (Mon Nov 11 13:12:24 2019 +0100) on "macos_x64"

    On VSCode, dart linter shows these infos on gen_lang generated files :

    Screen Shot 2019-12-02 at 11 07 25

    It concerns mostly messages with parameters :

    String yearsAgo(val) {
        return Intl.message("${val} years ago", name: 'yearsAgo', args: [val]);
    }
    

    This is the link to Dart language specs about string interpolation.

    Thanks

    enhancement 
    opened by areille 0
  • Version solving failed with firebase packages

    Version solving failed with firebase packages

    I have encountered this issue when I try using one of the following packages

    firebase_crashlytics: ^2.4.4
    firebase_messaging: ^11.2.4
    firebase_core: ^1.10.66
    flutter_local_notifications: ^9.1.5
    

    with gen_lang: ^0.1.3 Issue seems to be related with args, cause of this log when I run flutter pub get :

    Because no versions of gen_lang match >0.1.3 <0.2.0 and gen_lang 0.1.3 depends on args >=0.12.1 <2.0.0, gen_lang ^0.1.3 requires args >=0.12.1 <2.0.0. And because dbus >=0.2.0 depends on args ^2.0.0, gen_lang ^0.1.3 is incompatible with dbus >=0.2.0. And because flutter_local_notifications >=9.1.5 <10.0.0-dev.1 depends on flutter_local_notifications_linux ^0.4.0 which depends on dbus ^0.6.0, gen_lang ^0.1.3 is incompatible with flutter_local_notifications >=9.1.5 <10.0.0-dev.1.

    Is there any planned update for this? Or am I missing anything!?

    opened by riccardogabellone 0
  • Support for nested JSON properties

    Support for nested JSON properties

    Hi!

    It would be nice to be able to put nested objects in the JSON file to sort properties by more intuitive groups rather than separating them by a prefix.

    opened by NatoBoram 0
  • The value 'null' can't be assigned to the parameter type 'I18nOption' because 'I18nOption' is not nullable.

    The value 'null' can't be assigned to the parameter type 'I18nOption' because 'I18nOption' is not nullable.

    Hello,

    Getting the following error when trying to run flutter pub run gen_lang:generate

    Failed to precompile gen_lang:generate:
    Error: Cannot run with sound null safety, because the following dependencies
    don't support null safety:
    
     - package:args
     - package:gen_lang
     - package:ansicolor
    
    For solutions, see https://dart.dev/go/unsound-null-safety
    /c:/flutter/.pub-cache/hosted/pub.dartlang.org/gen_lang-0.1.3/bin/generate.dart:17:35: Error: The value 'null' can't be assigned to the p
    arameter type 'I18nOption' because 'I18nOption' is not nullable.
     - 'I18nOption' is from 'package:gen_lang/core_18n.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/gen_lang-0.1.3/lib/core_18n.dar
    t').
      var parser = _generateArgParser(null);
                                      ^
    pub finished with exit code 1
    

    Running flutter pub run --no-sound-null-safety gen_lang:generate still gives the same error:

    /c:/flutter/.pub-cache/hosted/pub.dartlang.org/gen_lang-0.1.3/bin/generate.dart:17:35: Error: The value 'null' can't be assigned to the p
    arameter type 'I18nOption' because 'I18nOption' is not nullable.
     - 'I18nOption' is from 'package:gen_lang/core_18n.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/gen_lang-0.1.3/lib/core_18n.dar
    t').
      var parser = _generateArgParser(null);
                                      ^
    pub finished with exit code 254
    

    flutter doctor Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel dev, 1.27.0-4.0.pre, on Microsoft Windows [Version 10.0.19042.804], locale en-AU) [√] Android toolchain - develop for Android devices (Android SDK version 30.0.3) [√] Chrome - develop for the web [√] Android Studio (version 4.1.0) [√] Connected device (3 available)

    • No issues found!

    Thanks! Damian

    opened by kasperado1 1
  • Fixed sort

    Fixed sort

    Hello.

    There is some issue with random sort order of locales in generated files (i18n.dart and messages_all.dart). Maybe platform related. For example: i18n.dart on Max OS: return const [ Locale("en", ""), Locale("uk", ""), Locale("pl", ""), Locale("ru", ""),
    ]; On Ubuntu: return const [ Locale("en", ""), Locale("ru", ""), Locale("pl", ""), Locale("uk", ""), ];

    messages_all.dart - even worse. We want this files to be included in git, instead of regenerate them each time we run build. So it would be great if sort could be fixed.

    opened by drstranges 0
Owner
kw101
Product Owner | UX Design | Flutter | Android | Nodejs | VueJS | ReactJS | AngularJS | Unity
kw101
Semi-automated Text Translator for Websites and Apps

macOS/Ubuntu/Windows: attranslate is a semi-automated tool for "synchronizing" translation-files. attranslate is optimized for fast and smooth rollout

Felix Kirchengast 272 Dec 21, 2022
Flutter Translate is a fully featured localization / internationalization (i18n) library for Flutter.

Flutter Translate is a fully featured localization / internationalization (i18n) library for Flutter. It lets you define translations for your content

Florin Bratan 333 Dec 27, 2022
Flutter app backed by Redux, shows animations, internationalization (i18n), ClipPath, fonts and others...

A Flutter tourism app that is backed-by Redux, shows animations, internationalization (i18n, English <=> Arabic), ClipPath, and fonts. YouTube demo I

Abdulmomen Kadum عبدالمؤمن كاظم 277 Dec 28, 2022
Text analyzer that extracts tokens from text for use in full-text search queries and indexes.

Tokenize text, compute document readbility and compare terms in Natural Language Processing. THIS PACKAGE IS PRE-RELEASE, and SUBJECT TO DAILY BREAKIN

GM Consult Pty Ltd 5 Dec 12, 2022
Generate secure passwords, check for exposed passwords, get visual feedback for password strength or get form validation with a minimum password strength required.

password_strength_checker Generate secure passwords, check for exposed passwords, get visual feedback for password strength or get form validation wit

Dario Varriale 6 Aug 8, 2023
Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON.

JSON to Dart Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON. This library is designed to ge

Javier Lecuona 1.2k Dec 25, 2022
Expenses tracker built with Flutter and Dart making use of Provider, Intl, Syncfusion Flutter Datepicker and more

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

Atuoha Anthony 2 Dec 10, 2022
Toast Library for Flutter, Easily create toast messages in single line of code

Create Toast messages on a Flutter Event. fluttertoast: ^8.0.8 Toast Library for Flutter, Easily create Personalised toast messages in single line of

Bouziani Mohammed 1 Feb 14, 2022
Socket library for creating real-time multiplayer games. Based on TCP, with the ability to send messages over UDP (planned).

Game socket The library was published in early access and is not stable, as it is being developed in parallel with other solutions. English is not a n

Stanislav 10 Aug 10, 2022
A simple and customizable flutter package for inputting phone number in intl / international format uses Google's libphonenumber

Intl Phone Number Input A simple and customizable flutter package for inputting phone number in intl / international format uses Google's libphonenumb

Ogunye Nathaniel Oluwatobiloba 138 Dec 11, 2022
A simple and customizable flutter package for inputting phone number in intl / international format

Intl Phone Number Input A simple and customizable flutter package for inputting

null 1 Jul 21, 2022
null 1 Jan 29, 2022
Alternative i18n tool for Dart and Flutter.

Simple internationalization (i18n) package for Dart and Flutter. Supports: AngularDart Flutter hot reload deferred loading of translations social dist

fnx.io 32 Dec 10, 2022
Flutter app using MVVM architecture pattern , dio , provider , intl packages.

News App Simple news application using free news API for fetching realtime data from the internet. Features -Used MVVM architecture pattern. Packages

null 3 Mar 25, 2022
Tool made in Dart that allows you to dynamically generate JSON files from data models written in Dart.

Dart JSON Generator Versión v1.1.1 Dart JSON Generator es una herramienta que permite generar archivos JSON a partir de mapas como modelos de datos en

Joinner Medina 7 Nov 23, 2022
I18n made easy, for Flutter!

flutter_i18n I18n made easy, for Flutter! Table of contents Why you should use flutter_i18n? Loaders FileTranslationLoader NetworkFileTranslationLoade

Matteo Pietro Dazzi 199 Dec 14, 2022
Lightweight i18n solution for Flutter

fast_i18n Lightweight i18n solution. Use JSON, YAML or CSV files to create typesafe translations. About this library ?? Minimal setup, create JSON fil

Tien Do Nam 186 Dec 26, 2022
Small sample app to work on simplifying the i18n process

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

Shi-Hao Hong 11 Jul 19, 2020
Flutter package: Easy and powerful internationalization using Dart extensions.

i18n_extension Non-boilerplate Translation and Internationalization (i18n) for Flutter Start with a widget with some text in it: Text("Hello, how are

Marcelo Glasberg 262 Dec 29, 2022
gui automation based on pyautogui python as backend and flutter desktop as frontend, drag and drop tool, no coding required.

GUI_AUTOMATION gui automation based on pyautogui python as backend and flutter desktop as frontend, drag and drop tool, no coding required. Install py

Hassan Kanso 34 Oct 30, 2022