AsyncNotifierListener<N extends BaseNotifier<BaseAsyncState<S>>, S extends Object?>.withData constructor

AsyncNotifierListener<N extends BaseNotifier<BaseAsyncState<S>>, S extends Object?>.withData({
  1. required Widget child,
  2. void dataListener(
    1. S data
    )?,
  3. VoidCallback? loadingListener,
  4. void errorListener(
    1. ErrorState error
    )?,
  5. bool listenWhen(
    1. S? previous,
    2. S? current
    )?,
  6. void onInit(
    1. N notifier
    )?,
  7. Key? key,
})

dataListener, loadingListener, and errorListener are optional callbacks invoked for side effects when the state is BaseAsyncState.data, BaseAsyncState.loading, or BaseAsyncState.error, respectively.

listenWhen is an optional predicate that determines whether to call listeners when the data changes.

onInit is an optional callback invoked with the notifier when the widget is initialized.

Note: Do not manually call the notifier's onInit() method here. The notifier itself will automatically trigger its own onInit() when it is created, so calling it again would result in duplicate invocations.

Example (incorrect usage):

AsyncNotifierListener<MyAsyncNotifier, String>(
  // Do NOT do this:
  onInit: (notifier) => notifier.onInit(),
  dataListener: (data) => print(data),
  loadingListener: () => print('Loading...'),
  errorListener: (error) => print('Error: \\${error.message}'),
  child: MyWidget(),
)

child is the widget below this widget in the tree. key is the widget key.

Implementation

AsyncNotifierListener.withData({
  required super.child,

  /// Optional callback for side effects when the state is [BaseAsyncState.data].
  final void Function(S data)? dataListener,

  /// Optional callback for side effects when the state is [BaseAsyncState.loading].
  final VoidCallback? loadingListener,

  /// Optional callback for side effects when the state is [BaseAsyncState.error].
  final void Function(ErrorState error)? errorListener,
  bool Function(S? previous, S? current)? listenWhen,
  super.onInit,
  super.key,
}) : super(
        listener: (state) => state.when(
          error: (e) => errorListener?.call(e),
          loading: () => loadingListener?.call(),
          data: (data) => dataListener?.call(data),
        ),
        listenWhen: (previous, current) =>
            listenWhen?.call(previous.data, current.data) ?? true,
      );