course-work/lib/logic/itemscubit.dart

66 lines
1.4 KiB
Dart
Raw Normal View History

2022-12-27 05:19:59 +00:00
import 'package:cubit_form/cubit_form.dart';
import 'package:equatable/equatable.dart';
import 'package:selfprivacy/models/item.dart';
import 'package:selfprivacy/logic/server_api.dart';
export 'package:provider/provider.dart';
part 'itemsstate.dart';
class ItemsCubit extends Cubit<ItemsState> {
ItemsCubit()
: super(
const ItemsState(
<Item>[],
false,
),
);
final ServerApi api = ServerApi();
Future<void> load() async {
refresh();
}
Future<void> refresh() async {
emit(state.copyWith(isLoading: true));
final resp = await api.getItems();
final List<Item> items = resp.data;
if (items.isNotEmpty) {
emit(
ItemsState(
items,
false,
),
);
} else {
emit(state.copyWith(isLoading: false));
}
}
Future<void> create(final Item item) async {
await api.createItem(item);
final List<Item> items = List<Item>.from(state.items);
items.add(item);
emit(state.copyWith(items: items));
}
Future<void> delete(final Item item) async {
final List<Item> items = List<Item>.from(state.items);
await api.deleteItem(item);
items.removeWhere((final Item u) => u.id == item.id);
emit(state.copyWith(items: items));
}
@override
void clear() async {
emit(
const ItemsState(
<Item>[],
false,
),
);
}
}