-
Notifications
You must be signed in to change notification settings - Fork 1
/
unauthorized_401_example.dart
54 lines (46 loc) · 1.31 KB
/
unauthorized_401_example.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
import 'package:dio/dio.dart';
import 'package:error_handler/error_handler.dart';
/// update [User] class with your own fields
class User {
final String name;
final String role;
User(this.name, this.role);
factory User.fromJson(Map<String, dynamic> map) {
return User(map['name'] as String, map['role'] as String);
}
}
/// First create API call
FutureResponse<User> login(String gmail, String password) async {
final body = {"gmail": gmail, "password": password};
final response = await Dio().post(
"http://your.domain.com/login",
data: body,
);
return response.convert(User.fromJson);
}
/// Wrap it with [ErrorHandler.stream] or [ErrorHandler.future]
StreamState<User> safeLogin(String gmail, String password) =>
errorHandler.stream(() => login(gmail, password));
void main() {
final event = safeLogin("example@domain.com", "password");
event.listen((event) {
event.whenOrNull(
loading: () {
print("please wait");
},
data: (data, response) {
print("login successfully");
print(data);
},
error: (exception) {
exception.whenOrNull(
responseException: (response) {
if (response.statusCode == 401) {
print("user is unauthorized");
}
},
);
},
);
});
}