fnotes/lib/theme_bloc.dart
2024-06-11 23:02:26 +02:00

88 lines
2.6 KiB
Dart

import 'package:drift/drift.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fnotes/database.dart';
import 'package:fnotes/persisted_brightness.dart';
import 'package:google_fonts/google_fonts.dart';
class PersistedThemeBloc extends Bloc<ThemeEvent, ThemeState> {
PersistedThemeBloc(Brightness brightness)
: super(ThemeState.withBrightness(brightness)) {
on<ThemeChangedEvent>(switchTheme);
on<LoadThemeEvent>(loadTheme);
}
void switchTheme(ThemeChangedEvent event, Emitter<ThemeState> emit) async {
await database.delete(database.persistentTheme).go();
var newBrightness =
PersistedBrightness.fromFlutterBrightness(state.theme.brightness)
.toOpposite();
await database
.into(database.persistentTheme)
.insert(PersistentThemeCompanion.insert(
brightness: Value(newBrightness.toString()),
));
emit(ThemeState.withBrightness(newBrightness.toFlutterBrightness()));
}
void loadTheme(LoadThemeEvent event, Emitter<ThemeState> emit) async {
PersistedBrightness persistedBrightness = await getPersistedBrightness();
emit(ThemeState.withBrightness(persistedBrightness.toFlutterBrightness()));
}
static Future<PersistedBrightness> getPersistedBrightness() async {
PersistedBrightness persistedBrightness = PersistedBrightness("light");
await database.select(database.persistentTheme).get().then(
(value) {
var brightnessIter = value.map((row) {
return row.brightness;
});
if (brightnessIter.isNotEmpty) {
persistedBrightness = PersistedBrightness(brightnessIter.first);
}
},
);
return persistedBrightness;
}
}
class ThemeEvent {}
class LoadThemeEvent extends ThemeEvent {}
class ThemeChangedEvent extends ThemeEvent {}
class ThemeState {
final ThemeData theme;
ThemeState({required this.theme});
static Future<ThemeState> fetchAndConstructInitState() async {
PersistedBrightness persistedBrightness = PersistedBrightness('light');
await database.select(database.persistentTheme).get().then(
(value) {
var brightnessIter = value.map((row) {
return row.brightness;
});
persistedBrightness = PersistedBrightness(brightnessIter.first);
},
);
return ThemeState.withBrightness(persistedBrightness.toFlutterBrightness());
}
factory ThemeState.withBrightness(Brightness brightness) {
return ThemeState(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurpleAccent, brightness: brightness),
),
);
}
}