37 lines
1.2 KiB
Dart
37 lines
1.2 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class LocaleCubit extends Cubit<Locale> {
|
|
static const String _localeKey = 'app_locale';
|
|
|
|
LocaleCubit() : super(const Locale('zh', 'CN')) {
|
|
_loadSavedLocale();
|
|
}
|
|
|
|
Future<void> _loadSavedLocale() async {
|
|
try {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final languageCode = prefs.getString('${_localeKey}_lang') ?? 'zh';
|
|
final countryCode = prefs.getString('${_localeKey}_country') ?? 'CN';
|
|
emit(Locale(languageCode, countryCode));
|
|
} catch (e) {
|
|
emit(const Locale('zh', 'CN'));
|
|
}
|
|
}
|
|
|
|
Future<void> setLocale(Locale locale) async {
|
|
try {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString('${_localeKey}_lang', locale.languageCode);
|
|
await prefs.setString('${_localeKey}_country', locale.countryCode ?? '');
|
|
emit(locale);
|
|
} catch (e) {
|
|
debugPrint('❌ [LocaleCubit] 保存语言设置失败: $e');
|
|
}
|
|
}
|
|
|
|
bool get isChinese => state.languageCode == 'zh';
|
|
bool get isEnglish => state.languageCode == 'en';
|
|
}
|