-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathhome_repository.dart
73 lines (65 loc) · 2.13 KB
/
home_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
65
66
67
68
69
70
71
72
73
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/res/errors.dart';
import '../../core/res/strings.dart';
import '../../core/utils/injection.dart';
import '../../core/utils/logger.dart';
@immutable
abstract class HomeRepository {
/// Posts the feedback as submitted by the user and throws a suitable exception if something goes wrong.
Future<void> postFeedback(String feedback);
}
class FakeHomeRepository extends HomeRepository {
@override
Future<void> postFeedback(String feedback) async {
// Simulate network delay
await Future.delayed(Duration(seconds: 1));
if (Random().nextBool()) {
// random network error
throw NetworkException();
} else {
// fake successfull operation
return;
}
}
}
class APIHomeRepository extends HomeRepository {
final String classTag = "APIHomeRepository";
@override
Future<void> postFeedback(String feedback) async {
final SharedPreferences sharedPreferences = sl.get<SharedPreferences>();
String? name = sharedPreferences.getString(S.nameKeySharedPreferences);
String? email = sharedPreferences.getString(S.emailKeySharedPreferences);
final String tag = classTag + "postFeedback";
http.Response response;
try {
response = await sl.get<http.Client>().post(
Uri.parse(S.postFeedbackUrl),
body: <String, dynamic>{
S.feedbackNameKey: name,
S.emailKey: email,
S.feedbackMessageKey: feedback
},
);
} catch (e) {
Log.e(tag: tag, message: "NetworkError:" + e.toString());
throw NetworkException();
}
if (response.statusCode == 201) {
Log.i(tag: tag, message: "Feedback Posted Successfully");
// return true;
return;
} else if (response.statusCode == 400) {
throw ValidationException(response.body);
} else {
Log.s(
tag: tag,
message:
"Unknown response code -> ${response.statusCode}, message ->" +
response.body);
throw UnknownException();
}
}
}