Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Created November 2, 2023 23:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rodydavis/f189b8904c3d691dc1649230cda966d2 to your computer and use it in GitHub Desktop.
Render a widget as a stream instead of a single funciton
import 'dart:async';
import 'package:flutter/widgets.dart';
abstract class StreamWidget extends StatefulWidget {
const StreamWidget({Key? key}) : super(key: key);
Stream<Widget> build(BuildContext context);
void initState() {}
void dispose() {}
void reassemble() {}
Widget? buildEmpty(BuildContext context) => null;
Widget? buildError(BuildContext context, Object? error) => null;
@override
State<StreamWidget> createState() => _StreamWidgetState();
}
class _StreamWidgetState extends State<StreamWidget> {
@override
void initState() {
widget.initState.call();
super.initState();
}
@override
void dispose() {
widget.dispose.call();
super.dispose();
}
@override
void reassemble() {
widget.reassemble.call();
super.reassemble();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: widget.build(context),
builder: (context, snapshot) {
if (snapshot.hasError) {
final result = widget.buildError(context, snapshot.error);
if (result != null) return result;
}
if (snapshot.hasData) {
return snapshot.data!;
} else {
final result = widget.buildEmpty(context);
if (result != null) return result;
}
return const SizedBox.shrink();
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment