// The app speaks Chinese and English. Our own text is written in Chinese and // translated by lookup: `tr('保存')` in code that builds strings, `AppText` // for the many Text leaves. `设置 → 常规 → 语言` chooses between the system // language, Chinese and English; Chinese is the fallback for a missing entry, // so a new string never disappears. import 'dart:async'; import 'dart:ui' show PlatformDispatcher; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'l10n/en_chat.dart'; import 'l10n/en_core.dart'; import 'l10n/en_servers.dart'; import 'l10n/en_sessions.dart'; import 'l10n/en_settings.dart'; import 'l10n/en_tools.dart'; /// Every English string, keyed by the Chinese text it replaces. final Map englishStrings = { ...enCore, ...enChat, ...enSessions, ...enSettings, ...enTools, ...enServers, }; enum AppLanguage { system('跟随系统', 'System'), zh('中文', '中文'), en('English', 'English'); /// What the choice reads as, in each language. final String zhLabel; final String enLabel; const AppLanguage(this.zhLabel, this.enLabel); String labelFor(bool english) => english ? enLabel : zhLabel; } /// The language the UI is drawn in, and the lookup behind [tr] and [AppText]. class L10n extends ChangeNotifier { L10n._(); static final L10n instance = L10n._(); /// Chinese until [ensureLoaded] has read the stored choice: tests and the /// first frame before the app starts never see a half-changed language. AppLanguage _choice = AppLanguage.zh; AppLanguage get choice => _choice; /// Reads the saved choice. No saved choice means follow the system, which /// is what a fresh install does. Future ensureLoaded() async { try { final prefs = await SharedPreferences.getInstance(); _choice = switch (prefs.getString('language')) { 'zh' => AppLanguage.zh, 'en' => AppLanguage.en, _ => AppLanguage.system, }; } catch (_) { _choice = AppLanguage.system; } notifyListeners(); } Future setLanguage(AppLanguage choice) async { apply(choice); try { final prefs = await SharedPreferences.getInstance(); if (choice == AppLanguage.system) { await prefs.remove('language'); } else { await prefs.setString('language', choice.name); } } catch (_) { // The choice still holds for this run. } } /// Changes the language without touching the stored choice (tests, and the /// first resolve before prefs are read). void apply(AppLanguage choice) { if (_choice == choice) return; _choice = choice; notifyListeners(); } Locale get locale => switch (_choice) { AppLanguage.zh => const Locale('zh', 'CN'), AppLanguage.en => const Locale('en'), AppLanguage.system => _systemIsChinese ? const Locale('zh', 'CN') : const Locale('en'), }; bool get _systemIsChinese { try { return PlatformDispatcher.instance.locale.languageCode == 'zh'; } catch (_) { return true; } } bool get isEnglish => locale.languageCode == 'en'; /// The English text for [zh], or [zh] when none is written yet. String tr(String zh) => isEnglish ? (englishStrings[zh] ?? zh) : zh; /// Same, for text built from parts: `trArgs('{0} 个子代理', [n])`. The /// Chinese template is filled as written; English entries use the same /// `{0}`, `{1}` placeholders. String trArgs(String template, [List args = const []]) { var out = isEnglish ? (englishStrings[template] ?? template) : template; for (var i = 0; i < args.length; i++) { out = out.replaceAll('{$i}', '${args[i] ?? ''}'); } return out; } /// A system language change reaches the app while it runs; the choice /// "follow the system" then has to redraw. void systemLocaleChanged() { if (_choice == AppLanguage.system) notifyListeners(); } } String tr(String zh) => L10n.instance.tr(zh); String trArgs(String template, [List args = const []]) => L10n.instance.trArgs(template, args); /// [Text] that goes through the same lookup. It is const-constructible, so a /// tree does not have to give up `const` to be translated. Content that comes /// from the server (message text, titles) is drawn with plain [Text]: only /// our own strings are keys. class AppText extends StatelessWidget { final String data; final TextStyle? style; final StrutStyle? strutStyle; final TextAlign? textAlign; final TextDirection? textDirection; final Locale? locale; final bool? softWrap; final TextOverflow? overflow; final TextScaler? textScaler; final int? maxLines; final String? semanticsLabel; final TextWidthBasis? textWidthBasis; final TextHeightBehavior? textHeightBehavior; final Color? selectionColor; const AppText( this.data, { super.key, this.style, this.strutStyle, this.textAlign, this.textDirection, this.locale, this.softWrap, this.overflow, this.textScaler, this.maxLines, this.semanticsLabel, this.textWidthBasis, this.textHeightBehavior, this.selectionColor, }); @override Widget build(BuildContext context) { // Reading the resolved locale makes this widget depend on it: when the // language changes, every AppText — including a const one whose widget // instance the parent build reuses — is rebuilt in the new language. final resolved = locale ?? Localizations.localeOf(context); return Text( tr(data), style: style, strutStyle: strutStyle, textAlign: textAlign, textDirection: textDirection, locale: resolved, softWrap: softWrap, overflow: overflow, textScaler: textScaler, maxLines: maxLines, semanticsLabel: semanticsLabel, textWidthBasis: textWidthBasis, textHeightBehavior: textHeightBehavior, selectionColor: selectionColor, ); } }