futurize method

Future<void> futurize(
  1. Future<T> body(), {
  2. T? initialData,
  3. String? errorMessage,
})

Fetches data asynchronously and updates the state accordingly.

The body function should return a Future which resolves to the new state.

Implementation

Future<void> futurize(
  Future<T> Function() body, {
  T? initialData,
  String? errorMessage,
}) async {
  _value ??= initialData;

  try {
    final T newValue = await body();
    status = switch (newValue) {
      null => GetStatus<T>.loading(),
      var val when val._isEmpty() => GetStatus<T>.empty(),
      var val => GetStatus<T>.success(val)
    };
  } catch (error) {
    status = GetStatus<T>.error(errorMessage ?? error.toString());
  } finally {
    refresh();
  }
}