Quit-Your-Addictions/lib/blocs/new_habit_cubit.dart

109 lines
2.7 KiB
Dart
Raw Permalink Normal View History

2024-01-07 01:49:35 +01:00
import 'package:bloc/bloc.dart';
import 'package:Rabbit_Habit/models/habit_sammler_model.dart';
import 'package:Rabbit_Habit/models/new_habit_model.dart';
import 'package:Rabbit_Habit/repo/habit_repository.dart';
import 'package:hive_flutter/hive_flutter.dart';
class NewHabitCubit extends Cubit<NewHabit> {
NewHabitCubit()
: super(const NewHabit(name: '', description: '', iconCodePoint: 57825));
setNewHabitName(String name) {
emit(state.copyWith(name: name));
}
setNewHabitDescription(String description) {
emit(state.copyWith(description: description));
}
setNewHabitIconCodePoint(int iconCodePoint) {
emit(state.copyWith(iconCodePoint: iconCodePoint));
}
Future<void> getHabitToEdit(String id) async {
Box<HabeichHabit> box = await Hive.openBox('habits');
try {
HabeichHabit? habit = box.get(id);
if (habit == null) return;
emit(
state.copyWith(
name: habit.name,
description: habit.description,
iconCodePoint: habit.icon,
),
);
} catch (e) {
// add error handling to crashlytics
} finally {
await box.close();
}
}
Future<void> addNewHabit(
String name,
String description,
int iconCodePoint,
) async {
Box<HabeichHabit> box = await Hive.openBox('habits');
try {
final DateTime now = DateTime.now();
await HabitRepository(box).addHabit(
now.millisecondsSinceEpoch.toString(),
HabeichHabit(
name: name,
description: description,
icon: iconCodePoint,
frequency: 'daily',
goal: null,
streak: 0,
onlyOn: [],
doneOn: [],
createdAt: now,
updatedAt: now,
),
);
} catch (e) {
// add error handling to crashlytics
} finally {
await box.close();
}
}
Future<void> updateHabit(
String id,
String name,
String description,
int iconCodePoint,
) async {
Box<HabeichHabit> box = await Hive.openBox('habits');
try {
final DateTime now = DateTime.now();
HabeichHabit prevHabit = box.get(id)!;
await HabitRepository(box).updateHabit(
id,
prevHabit.copyWith(
name: name,
description: description,
icon: iconCodePoint,
updatedAt: now,
),
);
} catch (e) {
// add error handling to crashlytics
} finally {
await box.close();
}
}
Future<void> deleteHabit(String id) async {
Box<HabeichHabit> box = await Hive.openBox('habits');
try {
await HabitRepository(box).deleteHabit(id);
} catch (e) {
// add error handling to crashlytics
} finally {
await box.close();
}
}
}