上一篇说到了一个StreamController
在使用过程中没有办法监听两次,
官方提供了广播的方式可以满足这个功能,但是原本的数据保存功能就没有办法再次使用了。这里提供简单的演示代码,功能还是点击按钮,进行数字改变,代码如下:
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
StreamController<int> streamController = StreamController<int>.broadcast(
onListen: (){
print('数据流添加监听');
},
onCancel: (){
print('数据流撤销监听');
},
sync: true,//同步(false)或者异步(true),同步会把数据立刻发送,异步需要等到空闲时候
);
StreamSubscription streamSubscription;
@override
void initState() {
super.initState();
streamSubscription = streamController.stream.listen(
(event) {
print('数据流转的值:$event');
},
onDone: (){
print('数据流关闭');
},
onError: (error){
print('数据流发生错误');
}
);
}
@override
void dispose() {
super.dispose();
streamSubscription.cancel();
streamController.close();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
body: Center(
child: Column(
children: [
StreamBuilder<int>(
stream: streamController.stream,
builder: (BuildContext context,AsyncSnapshot<int> snapshot){
if(!snapshot.hasData){
return Text('NaN');
}
switch(snapshot.connectionState){
case ConnectionState.none:
break;
case ConnectionState.waiting:
break;
case ConnectionState.active:
var value = snapshot.data;
return Text('$value');
break;
case ConnectionState.done:
break;
}
return Text('NaN');
},
),
RaisedButton(
onPressed: (){
streamController.add(Random().nextInt(10));//这样写也能把值发射出去
},
child: Text('改下值'),
)
],
),
),
),
);
}
}