static_translations 1.0.0+1

  • Readme
  • Changelog
  • Example
  • Installing
  • 73

static_translations #

A Flutter library to provide a consistent and reliable way to reference translation values in a typesafe way.

Using the library #

Add the repo to your Flutter pubspec.yaml file.

dependencies:
  static_translations: <<version>> 

Then run...

flutter packages get

Creating Static References #

The library utilizes the TranslationEntry class to ensure all dynamic strings exist in a code-safe way. To simplify maintenance and standardize things in a way teams of developers can easily follow, it is recommended that the variable name and the key of the TranslationEntry be all lower case separated with underscores and the same value.

The TranslationEntry must provide a default translation for when the Translator is unable to load replacement values. This ensures the application can function with a default language no matter what else may go wrong.

Example:

import 'package:meta/meta.dart';
import 'package:static_translations/static_translations.dart';

@immutable
class MyTranslations {
  MyTranslations._();

  static const button_submit = TranslationEntry(
    key: 'button_submit',
    value: 'Submit',
  );

  static const welcome_message = TranslationEntry(
    key: 'welcome_message',
    value: 'Welcome, {name}',
  );

  static const what_is_your_name = TranslationEntry(
    key: 'what_is_your_name',
    value: 'What is your name?',
  );
}

Using Loaders #

The TranslationLoader class provides many convenience factory constructors for loading translations values by different means. These loaders may be blocking or non-blocking.

A blocking loader waits to resolve it's Future until it has completed loading and processing the translations. A non-blocking loader will resolve the Future immediately, and apply the translations to the cache when they are available.

It is recommended that applications utilize non-blocking loaders for app initialization and then optionally use blocking loaders to load franslations unrelated to app startup.

Example:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  var translator = Translator(
    loaders: {
      'en': [
        TranslationLoader.asset('assets/languages/$language.json'),
        TranslationLoader.asynchronous(
          TranslationLoader.network(
            'https://raw.githubusercontent.com/peiffer-innovations/static_translations/master/example/assets/languages/$language.json',
          ),
        ),
      ],
    },
  );

  await translator.initialize();

  runApp(MyApp(translator: translator));
}

Binding to Provider #

While not required, the Translator class is designed to work with the provider package to be used as a type of dependency injection.

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

class MyApp extends StatefulWidget {
  MyApp({
    Key key,
    @required this.translator,
  })  : assert(translator != null),
        super(key: key);

  final Translator translator;

  @override
  Widget build(BuildContext context) {
    return Provider<Translator>.value(
      value: translator,
      child: MaterialApp(
        ...
      ),
    );
  }
}

Using Translation Values #

Assuming you bound the Translator to the widget tree using Provider like the above example, getting translation values is quite simple. Simply retrieve the Translator from the Provider, and call the translate function.

If no loader has set a value for a given TranslationEntry's key then the default value for the TranslationEntry will be used. Effectively this really means that only translation files need to be loaded for the non-default languages and an empty array can be passed to the Translator for the default language's loaders.

Example:

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

class HelloWidget extends StatelessWidget {
  MyWidget({
    Key key,
    this.name,
  })  : assert(name != null),
        super(key: key);

  final String name;

  Widget build(BuildContext context) {
    var translator = Translator.of(context);

    return Text(
      translator.translate(
        MyTranslations.welcome_message,
        {
          'name': name,
        },
      ),
    );
  }
}

[1.0.0+1] - May 31st, 2020 #

  • Switching to verified publisher and GH Action for publishing

[1.0.0] - May 31st, 2020 #

  • Initial release

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:static_translations/static_translations.dart';
import 'package:static_translations_example/src/my_translations.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  var translator = Translator(
    language: 'en',
    loaders: {
      'en': [
        TranslationLoader.asset('assets/languages/en.json'),
        TranslationLoader.asynchronous(
          TranslationLoader.network(
            'https://raw.githubusercontent.com/peiffer-innovations/static_translations/master/example/assets/languages/en.json',
          ),
        ),
      ],
      'es': [
        TranslationLoader.asset('assets/languages/es.json'),
        TranslationLoader.asynchronous(
          TranslationLoader.network(
            'https://raw.githubusercontent.com/peiffer-innovations/static_translations/master/example/assets/languages/es.json',
          ),
        ),
      ],
    },
  );

  await translator.initialize();

  runApp(MyApp(translator: translator));
}

class MyApp extends StatelessWidget {
  MyApp({
    Key key,
    @required this.translator,
  })  : assert(translator != null),
        super(key: key);

  final Translator translator;

  @override
  Widget build(BuildContext context) {
    return Provider<Translator>.value(
      value: translator,
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: MyHomePage(name: 'John Doe'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key key,
    this.name,
  }) : super(key: key);

  final String name;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<StreamSubscription> _subscriptions = [];
  String _language;
  Translator _translator;

  @override
  void initState() {
    super.initState();

    _translator = Translator.of(context);
    _subscriptions.add(_translator.translationsStream.listen((_) {
      if (mounted == true) {
        setState(() {});
      }
    }));

    _language = _translator.language;
  }

  void dispose() {
    _subscriptions.forEach((sub) => sub.cancel());

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          _translator.translate(MyTranslations.title),
        ),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              _translator.translate(
                MyTranslations.welcome_message,
                {
                  'name': widget.name,
                },
              ),
            ),
            SizedBox(height: 16.0),
            DropdownButton(
              items: [
                for (var language in _translator.supportedLanguages)
                  DropdownMenuItem(
                    child: Text(
                      _translator.translate(
                        MyTranslations.fromKey(language),
                      ),
                    ),
                    value: language,
                  ),
              ],
              onChanged: (value) => setState(() {
                _language = value;
                _translator.setLanguage(_language);
              }),
              value: _language,
            )
          ],
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  static_translations: ^1.0.0+1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:static_translations/static_translations.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
47
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
73
Learn more about scoring.

We analyzed this package on Jul 8, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

because of import path [static_translations] that is in a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
flutter 0.0.0
meta ^1.1.8 1.1.8 1.2.1
provider ^4.1.2 4.2.0
rest_client ^1.0.2 1.0.3
Transitive dependencies
charcode 1.1.3
collection 1.14.12 1.14.13
convert 2.1.1
crypto 2.1.5
http 0.12.1
http_parser 3.1.4
intl 0.16.1
json_class 1.0.3
logging 0.11.4
nested 0.0.4
path 1.7.0
pedantic 1.9.0 1.9.1
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
uuid 2.2.0
vector_math 2.0.8
Dev dependencies
flutter_test