Files
CloudHome-Ops/lib/providers/locale_provider.dart

86 lines
1.9 KiB
Dart
Raw Normal View History

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../utils/store_local_cache.dart';
/// 应用支持的语言。
enum AppLocale {
/// 简体中文(默认)。
zh,
/// 英语。
en,
}
/// [AppLocale] 的辅助方法。
extension AppLocaleX on AppLocale {
/// 标准 BCP-47 locale 标识。
Locale get locale {
switch (this) {
case AppLocale.zh:
return const Locale('zh', 'CN');
case AppLocale.en:
return const Locale('en', 'US');
}
}
/// 设置页展示的中文名。
String get label {
switch (this) {
case AppLocale.zh:
return '简体中文';
case AppLocale.en:
return 'English';
}
}
/// 设置页展示的英文名。
String get labelEn {
switch (this) {
case AppLocale.zh:
return 'Chinese (Simplified)';
case AppLocale.en:
return 'English';
}
}
/// 持久化存储用的字符串键。
String get storageKey {
switch (this) {
case AppLocale.zh:
return 'zh_CN';
case AppLocale.en:
return 'en_US';
}
}
}
/// 当前语言提供者(默认简体中文)。
///
/// 通过 [LocaleNotifier.setLocale] 切换,并持久化到本地缓存,
/// 下次启动自动恢复。
class LocaleNotifier extends Notifier<AppLocale> {
static const String _storageKey = 'app_locale';
@override
AppLocale build() {
final saved = StoreLocalCache.instance.getString(_storageKey);
if (saved == AppLocale.en.storageKey) {
return AppLocale.en;
}
return AppLocale.zh;
}
/// 设置语言并持久化。
Future<void> setLocale(AppLocale locale) async {
if (state == locale) return;
state = locale;
await StoreLocalCache.instance.setString(_storageKey, locale.storageKey);
}
}
/// 语言提供者实例。
final localeProvider = NotifierProvider<LocaleNotifier, AppLocale>(
LocaleNotifier.new,
);