• Stars
    star
    279
  • Rank 147,967 (Top 3 %)
  • Language
    Dart
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate Flutter localization from a simple online Google Sheets.

Flutter Google Sheet localizations generator

Generates a localizations delegate from an online Google Sheet file.

Install

Add the following to your pubspec.yaml:

dependencies:
  flutter_sheet_localization: <latest>
  flutter_localizations:
    sdk: flutter

dev_dependencies:
  flutter_sheet_localization_generator: <latest>
  build_runner: <latest>

Usage

1. Create a Google Sheet

Create a sheet with your translations (following the bellow format, an example sheet is available here) :

example

Make sure that your sheet is shared :

share

Extract from the link the DOCID and SHEETID values : https://docs.google.com/spreadsheets/d/<DOCID>/edit#gid=<SHEETID>) :

2. Declare a localization delegate

Declare the following AppLocalizationsDelegate class with the SheetLocalization annotation pointing to your sheet in a lib/localization.dart file :

import 'package:flutter/widgets.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_sheet_localization/flutter_sheet_localization.dart';

part 'localization.g.dart';

@SheetLocalization("DOCID", "SHEETID", 1) // <- See 1. to get DOCID and SHEETID
// the `1` is the generated version. You must increment it each time you want to regenerate
// a new version of the labels.
class AppLocalizationsDelegate
    extends LocalizationsDelegate<AppLocalizationsData> {
  const AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => localizedLabels.containsKey(locale);

  @override
  Future<AppLocalizationsData> load(Locale locale) =>
      SynchronousFuture<AppLocalizationsData>(localizedLabels[locale]!);
  @override
  bool shouldReload(AppLocalizationsDelegate old) => false;
}

3. Generate your localizations

Run the following command to generate a lib/localization.g.dart file :

flutter packages pub run build_runner build

4. Configure your app

Update your Flutter app with your newly created delegate :

MaterialApp(
    locale: AppLocalizations.languages.keys.first, // <- Current locale
    localizationsDelegates: [
    const AppLocalizationsDelegate(), // <- Your custom delegate
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    ],
    supportedLocales:
        AppLocalizations.languages.keys.toList(), // <- Supported locales
    // ...
);

5. Display your labels

final labels = AppLocalizations.of(context);
print(labels.dates.month.february);
print(labels.templated.hello(firstName: "World"));
print(labels.templated.contact(Gender.male, lastName: "John"));

Regeneration

Because of the caching system of the build_runner, it can't detect if there is a change on the distant sheet and it can't know if a new generation is needed.

The version parameter of the @SheetLocalization annotation solves this issue.

Each time you want to trigger a new generation, simply increment that version number and call the build runner again.

Google Sheet format

You can see an example sheet here.

Global format

The file should have :

  • A first header row
    • Column 0 : "Key"
    • then each supported language code ("en", "fr", ...)
  • Following rows for labels
    • Column 0 : the label key (can be a hierarchy, separated by dots)
    • then each translation based on language code of the column

Ignoring a column

Sometimes you may need to add comments for translators. For this, simply add a column with a name between parenthesis and the column will be completely ignored by the generator.

Example :

Key (Comments) fr en
example.man(Gender.male) This is a man title on home page homme man
example.man(Gender.female) This is a woman title on home page femme woman

Conditionals

It is pretty common to have variants of a label based on a condition (for example: Genders, Plurals, ...).

Simply duplicate your entries and end them with (<ConditionName>.<ConditionCase).

Example :

Key fr en
example.man(Gender.male) homme man
example.man(Gender.female) femme woman

See example for more details.

Plurals

The conditionals can be used the same way for plurals :

Example :

Key fr en
example.man(Plural.zero) hommes man
example.man(Plural.one) homme man
example.man(Plural.multiple) hommes men

From your Dart code, you can then define an extension :

extension PluralExtension on int {
  Plural plural() {
    if (this == 0) return Plural.zero;
    if (this == 1) return Plural.one;
    return Plural.multiple;
  }
}

See example for more details.

Dynamic labels

You can insert a {{KEY}} template into a translation value to have dynamic labels.

A Dart function will be generated to be used from your code.

/// Sheet
values.hello, "Hello {{first_name}}!"

/// Code
print(labels.values.hello(firstName: "World"));

Typed parameters

You can also add one of the compatible types (int, double, num, DateTime) to the parameter by suffixing its key with :<type>.

/// Sheet
values.price, "The price is {{price:double}}\$"

/// Code
print(labels.values.price(price: 10.5));

Formatted parameters

You can indicate how the templated value must be formatted by ending the value with a formatting rule in brackets [<rule-key>]. This can be particulary useful for typed parameters.

The available formatting rules depend on the type and generally rely on the intl package.

Type rule-key Generated code
double, int, num decimalPercentPattern, currency, simpleCurrency, compact, compactLong, compactSimpleCurrency, compactCurrency, decimalPattern, percentPattern, scientificPattern NumberFormat.<rule-key>(...)
DateTime Any date format valid pattern DateFormat('<rule-key>', ...).format(...)

Examples:

/// Sheet
values.price, "Price : {{price:double[compactCurrency]}}"

/// Code
print(labels.values.price(price: 2.00));
/// Sheet
values.today, "Today : {{date:DateTime[EEE, M/d/y]}}"

/// Code
print(labels.values.today(date: DateTime.now()));

Why ?

I find the Flutter internationalization tools not really easy to use, and I wanted a simple tool for sharing translations. Most solutions also use string based keys, and I wanted to generate pure dart code to improve permormance.

More Repositories

1

flutter_device_preview

Approximate how your app looks and performs on another device.
Dart
1,973
star
2

awesome-monogame

A collection of interesting libraries/tools for Monogame based game projects
957
star
3

figma-to-flutter

A Dart code generator that converts Figma components to Flutter widgets.
Dart
843
star
4

flutter_geocoder

Flutter plugin for forward and reverse geocoding
Dart
180
star
5

Xamarin.Bindings

A list of existing Xamarin binding libraries.
147
star
6

footage

Write videos in Flutter.
Dart
138
star
7

asgard_shop

A sample Flutter app with a custom Design System implementation.
Dart
134
star
8

tap_builder

A simple widget for building interactive areas.
Dart
112
star
9

figma_squircle

Flutter implementation of Figma's corner smoothing.
Dart
109
star
10

vsts-flutter-tasks

Flutter build tasks for Azure DevOps Pipelines/TFS.
JavaScript
108
star
11

bluff

A static website generator in Dart.
Dart
85
star
12

media_gallery

A Flutter plugin that lists native gallery items.
Dart
85
star
13

sleek_button

A simple but yet customizable button.
Dart
64
star
14

derived_colors

Generate color variants.
Dart
58
star
15

flutter_plugin_appcenter

Flutter plugins for accessing Visual Studio App Center services.
Java
56
star
16

built_bloc

Generate the BLoC pattern boilerplate.
Dart
51
star
17

micropub

A minimal pub server based on file system.
Dart
50
star
18

path_icon

Flutter icons from SVG path data.
Dart
48
star
19

dio_retry

Retry interceptor for dio.
Dart
47
star
20

dioc

A dart simple dependency container based on code generation.
Dart
47
star
21

fountain

The modular state management solution for flutter.
Dart
45
star
22

adaptative_demo

An example application for my FlutterViking session.
Dart
44
star
23

measurer

A widget that measure the size of its child.
Dart
43
star
24

spaces

Defining global spacing constants for building consistent and responsive apps.
Dart
39
star
25

flutter_contests

My entries for the flutter create contests.
JavaScript
36
star
26

http_extensions

A set of extensions for the http dart package.
Dart
35
star
27

dio_cache

A plugin for dio that caches responses for better optimization and offline data access.
Dart
34
star
28

sleek_spacing

Uniformize your margins, paddings and gaps.
Dart
34
star
29

built_vector

Generate Flutter vector code from a subset of SVG files.
Dart
33
star
30

flutter_shared_ui_poc

A proof that ui can be shared between flutter mobile and web.
Dart
31
star
31

route_pattern_generator

A Dart static code generator that produces matchers and builders from route uri patterns.
Dart
31
star
32

riverpod_navigation

Managing flutter navigation with riverpod.
Dart
29
star
33

dart-fullstack

Experimenting architectures for developing all layers of a typical application in Dart.
Dart
28
star
34

style-dictionary-figma-flutter

Custom style-dictionary transforms and formats to generate Flutter resources from a Figma Design Token plugin export..
Dart
28
star
35

stateful

A set of common stateful widget implementations.
Dart
23
star
36

Xam.Hero

Xamarin.iOS bindings for Hero library.
Objective-C
23
star
37

feature_flags

A Flutter package to manage feature flagging.
Dart
22
star
38

dart_maybe

No more null check with an dart equivalent of Maybe (Haskel, Elm) / Option (F#).
Dart
20
star
39

keyframes_tween

A tween that allow defining keyframes for various properties.
Dart
14
star
40

freezed_uri_router

Using freezed unions as a router for URIs.
Dart
14
star
41

sleek_typography

Flexible way of customizing text.
Dart
14
star
42

montage

Organize your animations.
Dart
14
star
43

dart-bloc_pattern_sample

A BLoC pattern sample that shares logic between a mobile and a web app.
Dart
13
star
44

ldoc-styles

Various ldoc lua documentation stylesheets.
CSS
13
star
45

sleek

A toolbelt for building your next user interface
Dart
13
star
46

sleek_palette

An opiniated color palette.
Dart
12
star
47

variant

Generate variant definitions for your Flutter application.
Dart
11
star
48

image_native_resizer

A Flutter plugin that resizes images from native API, while keeping important EXIF attributes.
Objective-C
11
star
49

flutter_staggered_animation

Staggered animations made easy.
Dart
11
star
50

uri_template

Build and match uri.
Dart
11
star
51

updated

Managing lifecycle and transitions of updates as a simple dart representation.
Dart
10
star
52

Xam.MaterialTextField

A different beautiful Floating Edit Text ported to Xamarin.
HTML
10
star
53

dart-opencage-geocoder

Dart client for the OpenCage forward/reverse geocoding API
Dart
7
star
54

flutter_resolve

Managing dependencies with simple Widgets.
Dart
6
star
55

reducer

Generates actions and reducer from a set of functions.
Dart
6
star
56

openapi_schema_generator

An generator for schemas defined in OpenAPI V3 definitions
Dart
6
star
57

mutator

An(other) state management attempt on top of ValueNotifier.
Dart
6
star
58

bento

A tool for previewing and exporting Figma design tokens.
Dart
5
star
59

themable_widget_example

An example of how to define really customizable widgets in Flutter.
Dart
5
star
60

flutter_firestore_serialized

Thin layer on top of Firestore to serialize/deserialize document data.
Dart
5
star
61

flutter_bloc_debug

A set of debugger tools for developing an app designed with the BLoC pattern.
Dart
5
star
62

locale_latlng

Get latitude and longitude from a country code.
Dart
5
star
63

node-pngjs-draw

Basic drawing functionnalities for pngjs.
JavaScript
5
star
64

figma

🖌Figma API wrapper written in Dart
Dart
5
star
65

knobs

Create editable property editor.
Dart
5
star
66

widget_video_recorder

Export an animated widget as a video.
Swift
5
star
67

react-motion-waypoint

Animating elements while scrolling with react-motion.
JavaScript
4
star
68

bloc_cli

Create command line interfaces for your BLoCs.
Dart
4
star
69

mobile-localization

A tool for managing localized ressources for all major mobile platforms (iOS, Android, Windows).
JavaScript
4
star
70

love-pixelatlas

A LÖVE texture atlas loader from pixel information of an image.
Lua
4
star
71

tide

A simple state management based on change notifier.
Dart
4
star
72

mapzen-tile-generator

A tool for generating easily a set of map tiles for a city from mapzen metro extracts.
JavaScript
4
star
73

live_code_examples

Several live code examples I've shown during my live streams.
Dart
4
star
74

love-pixelmap

A LÖVE tile map loader from an image.
Lua
3
star
75

dart-react_async

Provides components for building asynchronous user interfaces out of dart-react (inspired by Flutter).
Dart
3
star
76

freezed_gql

A freezed class generator from GraphQL definitions.
3
star
77

theme_definition

Define themes constants from a single configuration file.
Dart
3
star
78

inherited_geolocation

A inherited widget that manages geolocation updates from the user.
Dart
3
star
79

Xam.Cosmos

Xamarin.iOS bindings for Cosmos library.
Swift
2
star
80

aloisdeniel.github.io

My personnal web page.
CSS
2
star
81

mobile_covid19_attestation

A Flutter mobile app that generates a document to go outside in France during COVID-19 quarantine.
Dart
2
star
82

node-manifest-android

Update your Android mobile application manifest (version, bundle idenfifier, ...).
JavaScript
2
star
83

figma_widgets

Equivalent Flutter widgets for the Figma widget API.
Dart
2
star
84

Sparkle.Engine

A really basic 2D game engine on top of MonoGame.
1
star
85

lost-sprites

All sprites from my abandonned game prototypes.
1
star
86

eventified

Create event objects representing each method call to a class.
Dart
1
star
87

mobile-assets

A tool for generating and converting assets for all major mobile platforms (iOS, Android, Windows).
1
star
88

NativeObservables

Converts native Xamarin.iOS or Xamarin.Android components into INotifyPropertyChanged implementations.
1
star
89

node-annotate-icon

Add annotation to icons.
JavaScript
1
star
90

node-manifest-ios

Update your iOS mobile application manifest (Version, Bundle idenfifier, ...).
JavaScript
1
star
91

sleek_gallery

A gallery for sleek.
Dart
1
star