Skip to content

Instantly share code, notes, and snippets.

@Duobe
Last active July 31, 2019 15:19
Show Gist options
  • Select an option

  • Save Duobe/22c217d72f0e449d911fec2e78f81f56 to your computer and use it in GitHub Desktop.

Select an option

Save Duobe/22c217d72f0e449d911fec2e78f81f56 to your computer and use it in GitHub Desktop.
单例实现只实例化一次,暴露一个全局变量allTranslations
import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
///
/// Preferences related
///
const String _storageKey = "MyApplication_";
const List<String> _supportedLanguages = ['en','fr'];
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
class GlobalTranslations {
Locale _locale;
Map<dynamic, dynamic> _localizedValues;
VoidCallback _onLocaleChangedCallback;
///
/// Returns the list of supported Locales
///
Iterable<Locale> supportedLocales() => _supportedLanguages.map<Locale>((lang) => new Locale(lang, ''));
///
/// Returns the translation that corresponds to the [key]
///
String text(String key) {
// Return the requested string
return (_localizedValues == null || _localizedValues[key] == null) ? '** $key not found' : _localizedValues[key];
}
///
/// Returns the current language code
///
get currentLanguage => _locale == null ? '' : _locale.languageCode;
///
/// Returns the current Locale
///
get locale => _locale;
///
/// One-time initialization
///
Future<Null> init([String language]) async {
if (_locale == null){
await setNewLanguage(language);
}
return null;
}
/// ----------------------------------------------------------
/// Method that saves/restores the preferred language
/// ----------------------------------------------------------
getPreferredLanguage() async {
return _getApplicationSavedInformation('language');
}
setPreferredLanguage(String lang) async {
return _setApplicationSavedInformation('language', lang);
}
///
/// Routine to change the language
///
Future<Null> setNewLanguage([String newLanguage, bool saveInPrefs = false]) async {
String language = newLanguage;
if (language == null){
language = await getPreferredLanguage();
}
// Set the locale
if (language == ""){
language = "en";
}
_locale = Locale(language, "");
// Load the language strings
String jsonContent = await rootBundle.loadString("locale/i18n_${_locale.languageCode}.json");
_localizedValues = json.decode(jsonContent);
// If we are asked to save the new language in the application preferences
if (saveInPrefs){
await setPreferredLanguage(language);
}
// If there is a callback to invoke to notify that a language has changed
if (_onLocaleChangedCallback != null){
_onLocaleChangedCallback();
}
return null;
}
///
/// Callback to be invoked when the user changes the language
///
set onLocaleChangedCallback(VoidCallback callback){
_onLocaleChangedCallback = callback;
}
///
/// Application Preferences related
///
/// ----------------------------------------------------------
/// Generic routine to fetch an application preference
/// ----------------------------------------------------------
Future<String> _getApplicationSavedInformation(String name) async {
final SharedPreferences prefs = await _prefs;
return prefs.getString(_storageKey + name) ?? '';
}
/// ----------------------------------------------------------
/// Generic routine to saves an application preference
/// ----------------------------------------------------------
Future<bool> _setApplicationSavedInformation(String name, String value) async {
final SharedPreferences prefs = await _prefs;
return prefs.setString(_storageKey + name, value);
}
///
/// Singleton Factory
///
static final GlobalTranslations _translations = new GlobalTranslations._internal();
factory GlobalTranslations() {
return _translations;
}
GlobalTranslations._internal();
}
GlobalTranslations allTranslations = new GlobalTranslations();
{
"app_title": "My Application Title",
"main_title": "My Main Title",
"main_body": "My Main Body"
}
{
"app_title": "Le titre de mon application",
"main_title": "Mon titre principal",
"main_body":"Mon corps principal"
}
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'all_translations.dart';
void main() async {
// Initializes the translation module
await allTranslations.init();
// then start the application
runApp(MyApplication(),);
}
class MyApplication extends StatefulWidget {
@override
_MyApplicationState createState() => _MyApplicationState();
}
class _MyApplicationState extends State<MyApplication> {
@override
void initState(){
super.initState();
// Initializes a callback should something need
// to be done when the language is changed
allTranslations.onLocaleChangedCallback = _onLocaleChanged;
}
///
/// If there is anything special to do when the user changes the language
///
_onLocaleChanged() async {
// do anything you need to do if the language changes
print('Language has been changed to: ${allTranslations.currentLanguage}');
}
///
/// Main initialization
///
@override
Widget build(BuildContext context){
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
// Tells the system which are the supported languages
supportedLocales: allTranslations.supportedLocales(),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
final String language = allTranslations.currentLanguage;
final String buttonText = language == 'fr' ? '=> English' : '=> Français';
return Scaffold(
appBar: AppBar(title: Text(allTranslations.text('main_title'))),
body: Container(
width: double.infinity,
child: Column(
children: <Widget>[
RaisedButton(
child: Text(buttonText),
onPressed: () async {
await allTranslations.setNewLanguage(language == 'fr' ? 'en' : 'fr');
setState((){});
},
),
Text(allTranslations.text('main_body')),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment