Created
November 7, 2022 10:01
-
-
Save sinnoorc/fe8ca9890004f59d7ba8d25c6f39e156 to your computer and use it in GitHub Desktop.
Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HomeController extends GetxController with StateMixin<List<Users>> { | |
final UserApi _userApi = UserApi(); | |
RxList<Users> users = <Users>[].obs; | |
@override | |
void onInit() { | |
super.onInit(); | |
fetchUsers(); | |
} | |
void fetchUsers() async { | |
try { | |
final response = await _userApi.getUsers(); | |
if (response.statusCode == 200) { | |
final userModel = UserModel.fromJson(response.data); | |
if (userModel.users != null) { | |
users.assignAll(userModel.users!); | |
change(users, status: RxStatus.success()); | |
} else { | |
change(null, status: RxStatus.error('No user found')); | |
} | |
} | |
} on DioError catch (e) { | |
final ApiException apiException = ApiException.fromDioError(e); | |
change(null, status: RxStatus.error(apiException.toString())); | |
} | |
} | |
void addUser({Map<String, dynamic>? data}) async { | |
try { | |
final response = await _userApi.postUser(data: data); | |
if (response.statusCode == 200) { | |
fetchUsers(); | |
} | |
} on DioError catch (e) { | |
final ApiException apiException = ApiException.fromDioError(e); | |
throw apiException; | |
} | |
} | |
void updateUser(String id, {Map<String, dynamic>? data}) async { | |
try { | |
final response = await _userApi.putUser(id, data: data); | |
if (response.statusCode == 200) { | |
fetchUsers(); | |
} | |
} on DioError catch (e) { | |
final ApiException apiException = ApiException.fromDioError(e); | |
throw apiException; | |
} | |
} | |
void deleteUser(String id) async { | |
try { | |
final response = await _userApi.deleteUser(id); | |
if (response.statusCode == 200) { | |
fetchUsers(); | |
} | |
} on DioError catch (e) { | |
final ApiException apiException = ApiException.fromDioError(e); | |
throw apiException; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment