我是 Bloc 模式和流媒体的新手。我想在按下按钮时显示一个警告对话框,但我找不到方法。其实我的代码是:
Widget button() {
return RaisedButton(
child: Text('Show alert'),
color: Colors.blue[700],
textColor: Colors.white,
onPressed: () {
bloc.submit();
});
}
return Scaffold(
appBar: AppBar(
title: Text("Title"),
),
body: StreamBuilder(
stream: bloc.getAlert,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text("I have Dataaaaaa ${snapshot.data}");
} else
return ListView(
children: <Widget>[
Container(
button()
)
...
还有 BLoC:
final _submissionController = StreamController();
Stream get submissionStream=> _submissionController.stream;
Sink get submissionSink=> _submissionController.sink;
我试图做类似的事情:
Widget button() {
return StreamBuilder(
stream: submissionStream
builder: (context, snapshot){
if (snapshot.hasData){
return showDialog(...)
}else
return RaisedButton(
child: Text('Show alert'),
color: Colors.blue[700],
textColor: Colors.white,
onPressed: () {
bloc.submit();
});
}
但是,当然,它没有用。
最佳答案
构建工作时不能显示对话框。当您有新数据时,您将创建一个新的小部件。在这种情况下不使用流可能对您更好,但如果有必要,您应该使用
WidgetsBinding.instance.addPostFrameCallback((_) => yourFunction(context));
或
Future.microtask(() => showDialogFunction(context));
在你的如果
if (snapshot.hasData) {
WidgetsBinding.instance.addPostFrameCallback((_) => showDialogFunction(context));
}
此代码将在构建方法之后启动,因此对话框将立即显示。
Bloc函数总是返回widget,所以当stream有数据时总是返回button()或者不同wiget
关于view - Flutter:bloc,如何显示警报对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53370814/