You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cloudsolutions-atoms/lib/controllers/providers/loading_notifier.dart

46 lines
1.5 KiB
Dart

import 'package:flutter/material.dart';
import '../../exceptions/api_exception.dart';
/// ## Change Notifier Class To Handle The State While Waiting The Futures Value
class LoadingNotifier with ChangeNotifier {
bool _loading = false;
/// - Returns [TRUE] if [waitApiRequest] function called
/// - Returns [FALSE] if [waitApiRequest] function completed in both states (failed, succeed)
bool get loading => _loading;
/// - [fun] : Callback function that contains the API request.
/// - [onError] : Optional callback function to handle the request on failure with [APIException] parameter.
/// - [onSuccess] : Optional callback function to handle the request on succeed.
Future waitApiRequest(Function fun, {Function(APIException)? onError, Function? onSuccess}) async {
if (_loading == true) {
debugPrint('loading_notifier.dart : another action already started');
return;
}
_loading = true;
debugPrint('loading_notifier.dart : start loading');
notifyListeners();
try {
await fun();
if (onSuccess != null) {
await onSuccess();
}
} on APIException catch (error) {
debugPrint("loading_notifier.dart : [_waitResult] returns this message ${error.message} : ${error.arguments} ${error.error?.errorCode} ");
if (onError != null) {
await onError(error);
}
} finally {
stopLoading();
debugPrint('loading_notifier.dart : stop loading');
}
}
/// ## Stop loading and Notify listeners
void stopLoading() {
_loading = false;
notifyListeners();
}
}