async_var 1.0.3 copy "async_var: ^1.0.3" to clipboard
async_var: ^1.0.3 copied to clipboard

Async Data, Loading notifier, Error all in one variable, reducing boilerplate code and making your code more concise

example/example.md

Example Usage #

Before AsyncVar: #

class EventListViewModel extends ChangeNotifier {
  final NetworkServiceProtocol service;

  EventListViewModel(this.service)
      : _hostedEventsLoading = false,
        _hostedEvents = [],
        _hostedEventsError = null {
    getHostedEvents();
  }

  bool _hostedEventsLoading;
  bool get hostedEventsLoading => _hostedEventsLoading;
  List<EventGet> _hostedEvents;
  List<EventGet> get hostedEvents => _hostedEvents;
  String? _hostedEventsError;
  String? get hostedEventsError => _hostedEventsError;

  Future<void> getHostedEvents() async {
    _hostedEventsLoading = true;
    _hostedEventsError = null;
    notifyListeners();

    try {
      _hostedEvents = await service.getHostedEvents();
    } catch (e) {
      _hostedEventsError = e.toString();
    }

    _hostedEventsLoading = false;
    notifyListeners();
  }
}

After Refactoring with AsyncVar: #

class EventListViewModel extends ChangeNotifier {
  final NetworkServiceProtocol service;

  late final AsyncVar<List<EventGet>> _hostedEvents;
  List<EventGet> get hostedEvents => _hostedEvents.data ?? [];

  EventListViewModel(this.service) {
    _hostedEvents = AsyncVar<List<EventGet>>(
      operation: () async => service.getHostedEvents(),
      parentNotifier: this,
    );
    _hostedEvents.doIt();
  }
}
1
likes
0
points
283
downloads

Publisher

verified publisherflexxxlab.com

Weekly Downloads

Async Data, Loading notifier, Error all in one variable, reducing boilerplate code and making your code more concise

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter

More

Packages that depend on async_var