forked from hamed-rezaee/dart_design_patterns_collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepository.dart
64 lines (49 loc) · 1.56 KB
/
repository.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import 'package:collection/collection.dart';
abstract class BaseRepository<T> {
Future<T?> getById(int id);
Future<List<T>> getAll();
Future<void> insert(T item);
Future<void> update(T item);
Future<void> delete(int id);
}
class NetworkUserRepository implements BaseRepository<UserModel> {
@override
Future<UserModel?> getById(int id) => throw UnimplementedError();
@override
Future<List<UserModel>> getAll() => throw UnimplementedError();
@override
Future<void> insert(UserModel item) => throw UnimplementedError();
@override
Future<void> update(UserModel item) => throw UnimplementedError();
@override
Future<void> delete(int id) => throw UnimplementedError();
}
class MockUserRepository implements BaseRepository<UserModel> {
final List<UserModel> datasource = <UserModel>[];
@override
Future<UserModel?> getById(int id) async =>
datasource.firstWhereOrNull((UserModel element) => element.id == id);
@override
Future<List<UserModel>> getAll() async => datasource;
@override
Future<void> insert(UserModel user) async => datasource.add(user);
@override
Future<void> update(UserModel user) async {
final int index =
datasource.indexWhere((UserModel element) => element.id == user.id);
datasource[index] = user;
}
@override
Future<void> delete(int id) async =>
datasource.removeWhere((UserModel element) => element.id == id);
}
class UserModel {
UserModel({
required this.id,
required this.name,
required this.email,
});
final int id;
final String name;
final String email;
}