我是集团模式和流媒体方面的新手.我想在按下按钮时显示一个警报对话框,但是找不到解决方法.其实我的代码是:
I´m new in the bloc pattern and stream stuff. I want to show up an alert dialog when I press a button, but I can´t find a way to do it. Actually my code is:
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(); }); }但是,当然,它没有用.
But, of course, it didn´t work.
推荐答案构建工作时无法显示对话框.当您有新数据时,就可以创建一个新的小部件.在这种情况下,可能不使用流可能会更好,但是如果需要,您应该使用
You can't show a dialog when build working. When you have new data, then you create a new widget. Probably better for you will be not using the stream in this case, but if it necessary you should use
WidgetsBinding.instance.addPostFrameCallback((_)=> yourFunction(context));
WidgetsBinding.instance.addPostFrameCallback((_) => yourFunction(context));
或
Future.microtask(()=> showDialogFunction(context));
Future.microtask(() => showDialogFunction(context));
在您的情况下
if(snapshot.hasData){WidgetsBinding.instance.addPostFrameCallback((_)=> showDialogFunction(context));}
此代码将在构建方法后启动,因此将立即显示对话框.
This code will be launched after build method, so dialog will show immediately.
Bloc函数始终返回小部件,因此在流中有数据时始终返回button()或其他wiget
Bloc function always return widget, so always return button() or different wiget when stream has data
更多推荐
Flutter:集团,如何显示警报对话框
发布评论