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'; class PersistedThemeBloc extends Bloc { PersistedThemeBloc(Brightness brightness) : super(ThemeState.withBrightness(brightness)) { on(switchTheme); on(loadTheme); } void switchTheme(ThemeChangedEvent event, Emitter 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 emit) async { PersistedBrightness persistedBrightness = await getPersistedBrightness(); emit(ThemeState.withBrightness(persistedBrightness.toFlutterBrightness())); } static Future 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 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.lightBlue, brightness: brightness), )); } }