buildFromSnapshot method

Widget buildFromSnapshot(
  1. BuildContext context,
  2. AsyncSnapshot<T> snapshot
)

Builds the appropriate widget based on the snapshot state.

This method handles all the common logic for building widgets from AsyncSnapshot states (data, error, loading, empty).

Empty Data Detection: The method considers data as "empty" if it is:

  • null
  • An empty collection (List, Map, Set, Iterable)
  • An empty String

When data is empty, the empty state is shown instead of calling the builder.

Implementation

Widget buildFromSnapshot(BuildContext context, AsyncSnapshot<T> snapshot) {
  // Check for errors first (highest priority)
  if (snapshot.hasError) {
    return (errorBuilder != null)
        ? errorBuilder!(context, snapshot.error)
        : OptionError(error: snapshot.error);
  }

  // Check for data availability
  if (snapshot.hasData) {
    final data = snapshot.data;
    // If data is non-null and not empty, use the builder
    if (data != null && !_isEmpty(data)) {
      return builder(context, data);
    }
    // If data is null or empty, show empty state
    return (emptyBuilder != null)
        ? emptyBuilder!(context)
        : (isProd)
            ? const SizedBox()
            : const OptionEmpty(text: 'No data available');
  }

  // Default to loading state when no data and no error
  return (loadingBuilder != null)
      ? loadingBuilder!(context)
      : const OptionLoading();
}