Dart Streams上的错误StreamTransformer int不是EventSink <dynamic>

时间:2019-05-19 06:12:40

标签: dart

现在尝试学习Dart和泛型,我正在这段代码中学习有关流的知识,但是我似乎无法弄清我的代码有什么问题

import 'dart:async';

void main() {
  StreamController<int> controller = new StreamController<int>();

  num i = 0;

  Future.doWhile(() {
    controller.add(i++);

    if (i == 100) {
      return false;
    }
    return true;
  });

  var result = controller.stream.transform(
      StreamTransformer<int, EventSink<dynamic>>.fromHandlers(
          handleData: (int number, EventSink<dynamic> sink) {
    if (number == 70) {
      sink.addError("Hit seventy");
    } else {
      sink.add(number);
    }
  }));

  result.listen((data) => print(data));
}

上面的代码给我带来了以下错误

type 'int' is not a subtype of type 'EventSink<dynamic>' of 'data'
EventSinkWrapper.add (dart:async/stream_transformers.dart)
main.<anonymous closure> (file:///var/www/html/learning/dart/rr.dart:23:12)
HandlerEventSink.add (dart:async/stream_transformers.dart:228:7)
SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:120:24) 

1 个答案:

答案 0 :(得分:1)

StreamTransformer的通用类型是输入数据的类型和输出数据的类型。您的变压器将int映射到dynamic(尽管按照当前的编写,它实际上仅发出int)。

您在StringTransformer构造函数上的类型不正确。 (此外,不必在handleData lambda的定义上重复这些类型,因为可以从转换器的类型中推导出它们。)

尝试:

void main() {
  StreamController<int> controller = new StreamController<int>();

  num i = 0;

  Future.doWhile(() {
    controller.add(i++);
    return i < 100;
  });

  var result = controller.stream.transform(
    StreamTransformer<int, dynamic>.fromHandlers(
      handleData: (number, sink) {
        if (number == 70) {
          sink.addError("Hit seventy");
        } else {
          sink.add(number);
        }
      },
    ),
  );

  result.listen((data) => print(data));
}