Created
November 2, 2023 23:16
-
-
Save rodydavis/f189b8904c3d691dc1649230cda966d2 to your computer and use it in GitHub Desktop.
Render a widget as a stream instead of a single funciton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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