我是新手,我正在使用套接字,该套接字可以保持流数据,我需要在应用程序栏上对其进行更新。所以我必须要有状态的小部件
class _HomePageState extends State<HomePage> {
TickerAppBar appBar = TickerAppBar();
//Some declarations
@override
void initState() {
// TODO: implement initState
super.initState();
connectionSetup();
}
connectionSetup() async {
this.socket.connect(connectionString);
this.socket.sendSubscription(subscriptionString);
await processData();
}
Future<Null> processData() async{
subscription = socket.streamController.stream.listen(
(data) {
appBar.setStreamData(data); //Passing data into appbar widget
//rest of the code of current widget
}
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBar,
//rest of the code
)
}
}
class TickerAppBar extends StatefulWidget implements PreferredSizeWidget {
String streamData;
_TickerAppBarState child = _TickerAppBarState();
setStreamData(data){
this.streamData = data;
child.processData(); //To invoke the function every time the data is passed
}
}
class _TickerAppBarState extends State<TickerAppBar>{
Future<String> processData() async{
//Cannot set state here since its a constructor and the widget is not mounted.
}
}
那么,每次将数据传递到tickerappbar时如何设置数据?这样我的自定义应用栏就会显示每秒显示的新数据。
答案 0 :(得分:0)
我建议您遵循BLoC模式,在该模式中,您可以在一个位置定义流并从任何小部件订阅所述流,一旦准备好数据,就可以写入该流并将其共享在所有已订阅的小部件上。