toWidget method

Widget toWidget({
  1. required Widget onSuccess(
    1. BuildContext context,
    2. T data
    ),
  2. Widget onLoading(
    1. BuildContext context
    )?,
  3. Widget onError(
    1. BuildContext context,
    2. Object? error
    )?,
})

Simplifies usage of FutureBuilder

Implementation

Widget toWidget({
  required Widget Function(BuildContext context, T data) onSuccess,
  Widget Function(BuildContext context)? onLoading,
  Widget Function(BuildContext context, Object? error)? onError,
}) {
  return FutureBuilder<T>(
    future: this,
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return onLoading?.call(context) ?? Center(child: CircularProgressIndicator());
      } else if (snapshot.hasError) {
        return onError?.call(context, snapshot.error) ??
            Center(child: Text("Error: ${snapshot.error}"));
      } else if (snapshot.hasData) {
        return onSuccess(context, snapshot.data as T);
      } else {
        return Center(child: Text("No data"));
      }
    },
  );
}