Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Preface: Today just see, can [carry own original article] participate in “programmer essential small knowledge” activity, very excited. Remember before there are a few technical articles on a platform, I feel the nuggets technology atmosphere is stronger, I want to move over.
“Silent Glory days” is my username at Jane book.
International Multilingual Flutter based on INTL
The body of the
Project address: github.com/bettersun/h…
The APP can switch languages in real time and save the switched languages at the same time. The default startup language is Simplified Chinese, and the next startup language is saved.
The APP is available in four languages: Simplified Chinese, traditional Chinese, English and Japanese.
The above first
Simplified Chinese
Traditional Chinese
English
Japanese
1. Add dependencies
pubspec.yaml
# internationalization flutter_localizations: SDK: flutter_cupertino_localizations: intl: intl_translation: Shared_preferences:Copy the code
2. Manually add multi-language classes and generate multi-language files
Manually add more language class message. Dart follow link (the link content is very detailed) : www.jianshu.com/p/82c665646…
3. Generate arB files based on message.dart
flutter pub pub run intl_translation:extract_to_arb --output-dir=lib/localization lib/localization/message.dart
Copy the code
4. Generate multi-language DART files
The generated ARB file is renamed to the arB of each language (for example, message_zh_CN. Arb). Then run the command to generate the dart file
Example: Simplified Chinese:
flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/localization --no-use-deferred-loading lib/localization/message.dart lib/localization/message_zh_CN.arb
Copy the code
English:
flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/localization --no-use-deferred-loading lib/localization/message.dart lib/localization/message_en.arb
Copy the code
5. Define global language switch Controller(locale_controller.dart)
import 'package:flutter/material.dart'; typedef ChangeLocaleCallback = void Function(Locale locale); /// multilingual switch class LocaleController {/// language switch callback method ChangeLocaleCallback onLocaleChanged; /// Internals static final LocaleController _localeController = LocaleController._internal(); factory LocaleController() { return _localeController; } LocaleController._internal(); } /// LocaleController LocaleController = LocaleController();Copy the code
6. Define multilingual delegates (locale_delegate.dart)
BsMessageLocalDelegate
BsCupertinoLocalDelegate
BsMaterialLocalizationsDelegate
7. The main method reads the Locale in the local storage and sets it to the startup APP
If no, use simplified Chinese by default
void main() async { WidgetsFlutterBinding.ensureInitialized(); final SharedPreferences preferences = await SharedPreferences.getInstance(); String localeName = preferences. GetString (preferencekey.localename); LocaleName = localeName?? LocaleConst.zhCN.toString(); // start runApp(BsApp(localeName: localeName)); }Copy the code
8. Start App initializes multi-language delegate and binds global events to change App State
Class _BsAppState extends State<BsApp> {BsMessageLocalDelegate; // BsCupertinoLocalDelegate for iOS _bsCupertinoLocalDelegate; / / system gm (copy, paste, etc.) BsMaterialLocalizationsDelegate _bsMaterialLocalizationsDelegate; @override void initState() { super.initState(); final Locale locale = toLocale(widget.localeName); _bsMessageLocalDelegate = BsMessageLocalDelegate(locale); _bsCupertinoLocalDelegate = BsCupertinoLocalDelegate(locale); _bsMaterialLocalizationsDelegate = BsMaterialLocalizationsDelegate(locale); Switch callback method / / / / language binding global event to change the State of the App localeController. OnLocaleChanged = onLocaleChange; } // Locale String toLocale toLocale(String localName) {assert(localName! = null); final List<String> localeCode = localName.split('_'); if (localeCode.length > 1) { return Locale(localeCode[0], localeCode[1]); } else if (localeCode.isNotEmpty) { return Locale(localeCode[0]); /// Language switch void onLocaleChange(Locale newLocale) {setState(() {_bsMessageLocalDelegate = BsMessageLocalDelegate(newLocale); _bsCupertinoLocalDelegate = BsCupertinoLocalDelegate(newLocale); _bsMaterialLocalizationsDelegate = BsMaterialLocalizationsDelegate(newLocale); }); } @override Widget build(BuildContext context) { return MaterialApp( title: Theme: ThemeData(primarySwatch: Color. Blue,), // Language delegate localizationsDelegates: [ _bsMessageLocalDelegate, _bsCupertinoLocalDelegate, _bsMaterialLocalizationsDelegate, GlobalWidgetsLocalizations. Delegate,], / / support language supportedLocales: const <Locale>[ LocaleConst.zhCN, LocaleConst.zhHK, LocaleConst.en, LocaleConst.en, ], home: const BsHome(), ); }}Copy the code
9. Call the global event in the language switching event to trigger the setState in the App to change the App language in real time and save the switched language
Future<void> _changeLocale() async {_localeIndex++; Locale locale = LocaleConst.zhCN; If (_localeIndex % _localeTotal == 0) {locale = localeconst.zhcn; } if (_localeIndex % _localeTotal == 1) { locale = LocaleConst.zhHK; } if (_localeIndex % _localeTotal == 2) { locale = LocaleConst.en; } if (_localeIndex % _localeTotal == 3) { locale = LocaleConst.ja; Change language} / / / / called global event trigger to start the App in the setState localeController. OnLocaleChanged (locale); final SharedPreferences preferences = await SharedPreferences.getInstance(); Save/language/after switch to local store preferences. The setString (PreferenceKey localeName, locale. The toString ()); }Copy the code