feat(flutter): 重构播放页并增加语言切换
This commit is contained in:
1 parent
f1efbc5be8
commit
8c43e9e385
34 files changed
+1331
-879
No files matched your search
@@ -0,0 +1,53 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// 全局界面语言状态。
|
||||
///
|
||||
/// `null` 表示没有用户选择,继续跟随系统语言;一旦用户在“我的”里选择,
|
||||
/// 选择结果会持久化并在下一次启动时恢复。
|
||||
class LocaleController extends ChangeNotifier {
|
||||
/// 创建语言状态控制器。
|
||||
LocaleController({SharedPreferencesAsync? preferences})
|
||||
: _preferences = preferences ?? SharedPreferencesAsync();
|
||||
|
||||
static const String preferenceKey = 'app.locale';
|
||||
static const Set<String> supportedCodes = {'zh', 'en', 'id'};
|
||||
|
||||
final SharedPreferencesAsync _preferences;
|
||||
Locale? _locale;
|
||||
bool _disposed = false;
|
||||
|
||||
/// 用户选择的语言;为空时由 MaterialApp 跟随系统。
|
||||
Locale? get locale => _locale;
|
||||
|
||||
/// 当前语言的展示代码。
|
||||
String get languageCode => _locale?.languageCode ?? 'system';
|
||||
|
||||
/// 读取本地语言选择;未设置时保持跟随系统。
|
||||
Future<void> load() async {
|
||||
final code = await _preferences.getString(preferenceKey);
|
||||
if (code == null || !supportedCodes.contains(code)) return;
|
||||
_locale = Locale(code);
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// 立即切换并持久化语言。
|
||||
Future<void> select(Locale locale) async {
|
||||
if (!supportedCodes.contains(locale.languageCode)) return;
|
||||
_locale = locale;
|
||||
_notify();
|
||||
await _preferences.setString(preferenceKey, locale.languageCode);
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user