Slide 24
Slide 24 text
library safety_stream_builder;
import 'dart:async';
import 'package:flutter/material.dart';
typedef Widget AsyncWidgetSafetyBuilder(BuildContext context, T data);
typedef Widget BuildHandler(BuildContext context);
class SafetyStreamBuilder extends StreamBuilder {
static BuildHandler _buildErrorWidget = _defaultBuildErrorWidget;
static BuildHandler _buildBlankWidget = _defaultBuildBlankWidget;
final AsyncWidgetSafetyBuilder _builder;
final Widget blankWidget;
final Widget errorWidget;
factory SafetyStreamBuilder({
@required AsyncWidgetSafetyBuilder builder,
Key key,
T initialData,
Stream stream,
Widget blankWidget,
Widget errorWidget,
}) =>
SafetyStreamBuilder._(
builder: builder,
unusedBuilder: (_, __) => null, // dummy
key: key,
initialData: initialData,
stream: stream,
blankWidget: blankWidget,
errorWidget: errorWidget,
);
SafetyStreamBuilder._({
@required AsyncWidgetSafetyBuilder builder,
@required AsyncWidgetBuilder unusedBuilder,
Key key,
T initialData,
Stream stream,
this.blankWidget,
this.errorWidget,
}) : _builder = builder,
super(
key: key,
initialData: initialData,
stream: stream,
builder: unusedBuilder,
);
@override
Widget build(BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return errorWidget != null ? errorWidget : _buildErrorWidget(context);
}
if (!snapshot.hasData) {
return blankWidget != null ? blankWidget : _buildBlankWidget(context);
}
return _builder(context, snapshot.data);
}
static Widget _defaultBuildErrorWidget(BuildContext _) =>
const Icon(Icons.error_outline);
static Widget _defaultBuildBlankWidget(BuildContext _) => Container();
static void handleError({@required BuildHandler build}) =>
_buildErrorWidget = build;
static void handleBlank({@required BuildHandler build}) =>
_buildBlankWidget = build;
}
ᶃϑΝΠϧʹίʔυΛॻ͘