// The app speaks English and Chinese. Code writes English; Chinese comes from // the table in l10n/zh.dart through tr()/trArgs(), and AppText for the many // Text leaves. 设置 → 常规 → 语言 chooses between the system language, Chinese // and English; a language we have no table for reads English, and a missing // entry falls back to the English source, so text never disappears. import 'dart:async'; import 'dart:ui' show PlatformDispatcher; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'l10n/zh.dart'; enum AppLanguage { system, zh, en } /// 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'), // Only Chinese is translated; every other system language reads // English. 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'; /// What a language choice reads as: a language names itself. String languageLabel(AppLanguage choice) => switch (choice) { AppLanguage.system => tr('System'), AppLanguage.zh => '中文', AppLanguage.en => 'English', }; /// The Chinese text for [en], or [en] when there is none. String tr(String en) => isEnglish ? en : (chineseStrings[en] ?? en); /// Same, for text built from parts: `trArgs('{0} subagents', [n])`. The /// English template is filled as written; Chinese entries use the same /// `{0}`, `{1}` placeholders. String trArgs(String template, [List args = const []]) { var out = isEnglish ? template : (chineseStrings[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 en) => L10n.instance.tr(en); 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 source 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, ); } }