fnotes/lib/theme_bloc.dart

88 lines
2.6 KiB
Dart
Raw Normal View History

import 'package:drift/drift.dart';
2024-03-17 13:15:50 +00:00
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fnotes/database.dart';
import 'package:fnotes/persisted_brightness.dart';
2024-06-11 21:02:26 +00:00
import 'package:google_fonts/google_fonts.dart';
2024-03-17 13:15:50 +00:00
class PersistedThemeBloc extends Bloc<ThemeEvent, ThemeState> {
PersistedThemeBloc(Brightness brightness)
: super(ThemeState.withBrightness(brightness)) {
on<ThemeChangedEvent>(switchTheme);
on<LoadThemeEvent>(loadTheme);
2024-03-17 13:15:50 +00:00
}
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;
2024-03-17 13:15:50 +00:00
}
}
class ThemeEvent {}
class LoadThemeEvent extends ThemeEvent {}
class ThemeChangedEvent extends ThemeEvent {}
2024-03-17 13:15:50 +00:00
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());
2024-03-17 13:15:50 +00:00
}
factory ThemeState.withBrightness(Brightness brightness) {
return ThemeState(
2024-06-11 21:02:26 +00:00
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurpleAccent, brightness: brightness),
),
);
2024-03-17 13:15:50 +00:00
}
}