May
May

Reputation: 167

Flutter how do you return value or error from stream

I want to use this method, but instead of returning Future<void>, I want to return a value from it. This value is either a final list of bytes or an error (if error happens anytime).

I don't know how to that, since you can't return a value from onDone or onError. If I use await for instead of listen, the errors behave strangely. How to do that?

Future<void> _downloadImage() async {
    _response = await http.Client()
        .send(http.Request('GET', Uri.parse('https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg')));
    _total = _response.contentLength ?? 0;

    _response.stream.listen((value) {
      setState(() {
        _bytes.addAll(value);
        _received += value.length;
      });
    }).onDone(() async {
      final file = File('${(await getApplicationDocumentsDirectory()).path}/image.png');
      await file.writeAsBytes(_bytes);
      setState(() {
        _image = file;
      });
    });
  }

Upvotes: 0

Views: 648

Answers (0)

Related Questions