【发布时间】:2020-10-02 05:40:53
【问题描述】:
得到这个错误:
1. 函数“stream”不能返回“Stream”类型的值,因为它的返回类型为“Stream”。 (return_of_invalid_type at blahblah)
2.参数类型'Stream'不能赋值给参数类型'Stream'。 (argument_type_not_assignable at blahblah)
为什么? 这是基于 Flutter 团队的this video 创建流构建器的代码
void main() {
runApp(MyApp());
//listen to subscribe to stream
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Center(
child: Stream(),
),
),
);
}
}
class Stream extends StatefulWidget {
@override
_StreamState createState() => _StreamState();
}
class _StreamState extends State<Stream> {
@override
Widget build(BuildContext context) {
return StreamBuilder(
//Error number 2
stream: NumberCreator().stream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.connectionState == ConnectionState.done) {
return Text('done');
} else if (snapshot.hasError) {
return Text('Error!');
} else {
return Text(snapshot.data);
}
},
);
}
}
class NumberCreator {
NumberCreator() {
Timer.periodic(Duration(seconds: 1), (timer) {
//add count to stream
_controller.sink.add(_count);
_count++;
});
}
var _count = 1;
final _controller = StreamController<int>();
//error number 1
Stream<int> get stream => _controller.stream;
dispose() {
_controller.close();
}
}
我们是否需要 statefulWidget 来创建 stramBuilder?
【问题讨论】:
-
我尝试复制粘贴并运行代码,这解决了我的错误
Stream<dynamic> get stream => _controller.stream;