74 lines
2.2 KiB
Dart
Raw Normal View History

2022-01-28 18:34:21 +08:00
import 'package:app_flowy/user/infrastructure/repos/user_setting_repo.dart';
import 'package:equatable/equatable.dart';
import 'package:flowy_infra/theme.dart';
2022-02-19 13:52:52 +08:00
import 'package:flowy_sdk/log.dart';
2022-01-28 18:34:21 +08:00
import 'package:flowy_sdk/protobuf/flowy-user-data-model/user_setting.pb.dart';
import 'package:flutter/material.dart';
2022-01-29 09:24:04 +08:00
import 'package:easy_localization/easy_localization.dart';
2022-02-01 12:15:11 +08:00
import 'package:async/async.dart';
2022-01-28 18:34:21 +08:00
class AppearanceSettingModel extends ChangeNotifier with EquatableMixin {
AppearanceSettings setting;
AppTheme _theme;
Locale _locale;
2022-02-01 12:15:11 +08:00
CancelableOperation? _saveOperation;
AppearanceSettingModel(this.setting)
: _theme = AppTheme.fromName(name: setting.theme),
_locale = Locale(setting.locale.languageCode, setting.locale.countryCode);
2022-01-28 18:34:21 +08:00
AppTheme get theme => _theme;
Locale get locale => _locale;
2022-01-28 18:34:21 +08:00
Future<void> save() async {
2022-02-01 12:15:11 +08:00
_saveOperation?.cancel;
_saveOperation = CancelableOperation.fromFuture(
Future.delayed(const Duration(seconds: 1), () async {
await UserSettingReppsitory().setAppearanceSettings(setting);
}),
);
2022-01-28 18:34:21 +08:00
}
@override
List<Object> get props {
return [setting.hashCode];
}
void swapTheme() {
final themeType = (_theme.ty == ThemeType.light ? ThemeType.dark : ThemeType.light);
if (_theme.ty != themeType) {
_theme = AppTheme.fromType(themeType);
setting.theme = themeTypeToString(themeType);
notifyListeners();
save();
}
}
void setLocale(BuildContext context, Locale newLocale) {
if (_locale != newLocale) {
if (!context.supportedLocales.contains(newLocale)) {
Log.error("Unsupported locale: $newLocale");
newLocale = const Locale('en');
Log.debug("Fallback to locale: $newLocale");
}
context.setLocale(newLocale);
_locale = newLocale;
setting.locale.languageCode = _locale.languageCode;
setting.locale.countryCode = _locale.countryCode ?? "";
2022-01-28 18:48:09 +08:00
notifyListeners();
save();
}
2022-01-28 18:34:21 +08:00
}
2022-02-01 12:15:11 +08:00
void readLocaleWhenAppLaunch(BuildContext context) {
if (setting.resetAsDefault) {
setting.resetAsDefault = false;
save();
setLocale(context, context.deviceLocale);
2022-02-01 12:15:11 +08:00
}
}
2022-01-28 18:34:21 +08:00
}