我想三行共享一个流,每一行都可以暂停和恢复。
现在,我只能使用StreamController和StreamBuilder共享一个流到三行,但我不知道如何暂停和恢复。
https://github.com/WingCH/Fluuter-Exercise
...
class StreamDemoState extends State<StreamDemo> {
StreamController _streamController;
Stream<int> timerStream;
@override
void initState() {
super.initState();
//Timer
Duration interval = Duration(seconds: 1);
timerStream = Stream.periodic(interval, (data) {
return data;
});
_streamController = StreamController.broadcast();
_streamController.addStream(timerStream);
}
Widget build(BuildContext context) {
...
Padding(
padding: EdgeInsets.all(10),
child: StreamBuilder<Object>(
stream: _streamController.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: <Widget>[
Text(
snapshot.data.toString(),
style: TextStyle(
color: Colors.blueGrey,
fontWeight: FontWeight.bold,
fontSize: 80),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () {
//listen / resume
},
child: Text('listen'),
),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20.0),
child: OutlineButton(
onPressed: () {
//Pause
},
child: Text('Paused'),
),
),
OutlineButton(
onPressed: null,
child: Text('--'),
),
],
)
],
);
} else {
return Text('no Date');
}
}),
),
...
}
Run Code Online (Sandbox Code Playgroud)
我面临着同样的问题,这就是我想到的:您可以使用timerStream 上的侦听器一一添加事件,而不是在StreamController 上调用addStream。Listen 返回一个 StreamSubscription,您可以使用 SubscriberSubsription.pause 暂停 intStream。
替换_streamController.addStream(timerStream);为以下内容(我自己没有运行过,所以可能有一些拼写错误):
var _timerSubscription = timerStream.listen((event) => _streamController.add(event));
Run Code Online (Sandbox Code Playgroud)
现在您可以分别将//resume和替换//pause为以下内容:
// Resume
_timerSubscription.resume();
Run Code Online (Sandbox Code Playgroud)
// Pause
_timerSubscription.pause();
Run Code Online (Sandbox Code Playgroud)
请注意,通过多次调用暂停的流pause()将需要相同数量的调用来resume()取消暂停 - 如果这是不希望的行为,您将需要禁用暂停按钮(或者如果流处于已经暂停了)。
另外,当 StreamController 不再使用时,不要忘记取消 StreamSubscription 并关闭它们!
| 归档时间: |
|
| 查看次数: |
6569 次 |
| 最近记录: |