I'd like to convert a stream before it reaches StreamBuilder, but have no idea what that would look like. As an test, I created the simple countdown below. What I'd like to do is give CountDownConversion to StreamBuilder, but if I uncomment it, I get compile errors. I've been reading up on streams and StreamBuilder, but haven't seen anyone doing this type of conversion before StreamBuilder. If someone could clue me in, I'd appreciate it.
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
Stream<int> countDown() async* {
int i = 42;
while (true) {
await Future.delayed(Duration(seconds: 1));
yield i--;
if (i == 0) break;
}
}
// Stream<String> countDownConverter() {
// final number = countDown();
// return number.toString();
// }
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: countDown(), // <- want countDownConverter() here
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
final String count = snapshot.data.toString();
return Text(count, style: Theme.of(context).textTheme.headline4);
} else return Text('Working...');
});
}
}
Convert countDownConverter
to an async generator as well and use await for
to have it listen to countDown
:
Stream<String> countDownConverter() async* {
await for (int n in countDown()) {
yield n.toString();
}
}
Though ideally instead of writing a conversion method, you could simply use map
on the stream itself:
StreamBuilder(
stream: countDown().map((i) => i.toString()),
...
),