Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

flutter - How to convert a stream before it reaches StreamBuilder?

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...');
    });
  }
}
question from:https://stackoverflow.com/questions/66052697/how-to-convert-a-stream-before-it-reaches-streambuilder

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()),
  ...
),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...