11import 'dart:async' ;
22
33import 'package:flutter_riverpod/flutter_riverpod.dart' ;
4+ import 'package:survey_flutter/api/exception/network_exceptions.dart' ;
45import 'package:survey_flutter/uimodels/app_error.dart' ;
6+ import 'package:survey_flutter/usecases/base/base_use_case.dart' ;
7+ import 'package:survey_flutter/usecases/login_use_case.dart' ;
58import 'package:survey_flutter/utils/internet_connection_manager.dart' ;
69
710final loginViewModelProvider =
811 AsyncNotifierProvider .autoDispose <LoginViewModel , void >(LoginViewModel .new );
912
1013class LoginViewModel extends AutoDisposeAsyncNotifier <void > {
11- late InternetConnectionManager internetConnectionManager;
12-
1314 bool isValidEmail (String ? email) {
1415 // Just use a simple rule, no fancy Regex!
1516 return ! (email == null || ! email.contains ('@' ));
@@ -24,31 +25,49 @@ class LoginViewModel extends AutoDisposeAsyncNotifier<void> {
2425 required String password,
2526 }) async {
2627 state = const AsyncLoading ();
27- // TODO: Integrate with API
28-
29- // Handling error part:
28+ final loginUseCase = ref.read (loginUseCaseProvider);
29+ final result = await loginUseCase (
30+ LoginParams (
31+ email: email,
32+ password: password,
33+ ),
34+ );
3035
31- // If it returns unauthorized error (401)
32- //state = const AsyncError(
33- // AppError.unauthorized,
34- // StackTrace.empty,
35- //);
36+ if (result is Failed ) {
37+ final error = result as Failed ;
38+ final exception = error.exception.actualException as NetworkExceptions ;
3639
37- // If it returns timeout error, then check Internet connection
38- internetConnectionManager = ref.read (internetConnectionManagerProvider);
39- final isConnected = await internetConnectionManager.hasConnection ();
40+ if (exception is BadRequest || exception is UnauthorisedRequest ) {
41+ state = const AsyncError (
42+ AppError .unauthorized,
43+ StackTrace .empty,
44+ );
45+ return ;
46+ } else if (exception is RequestTimeout ) {
47+ final isConnected = await _hasInternetConnection ();
48+ if (! isConnected) {
49+ state = const AsyncError (
50+ AppError .noInternetConnection,
51+ StackTrace .empty,
52+ );
53+ return ;
54+ }
55+ }
4056
41- if (! isConnected) {
42- state = const AsyncError (
43- AppError .noInternetConnection,
44- StackTrace .empty,
45- );
46- } else {
4757 state = const AsyncError (
4858 AppError .generic,
4959 StackTrace .empty,
5060 );
61+ return ;
5162 }
63+
64+ state = const AsyncData (null );
65+ }
66+
67+ Future <bool > _hasInternetConnection () async {
68+ final internetConnectionManager =
69+ ref.read (internetConnectionManagerProvider);
70+ return await internetConnectionManager.hasConnection ();
5271 }
5372
5473 @override
0 commit comments