Lit*_*key 9 alert view stream flutter
我是集团模式和流媒体方面的新手。我想在按下按钮时显示一个警报对话框,但找不到解决方法。实际上我的代码是:
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()
)
...
Run Code Online (Sandbox Code Playgroud)
而BLoC:
final _submissionController = StreamController();
Stream get submissionStream=> _submissionController.stream;
Sink get submissionSink=> _submissionController.sink;
Run Code Online (Sandbox Code Playgroud)
我试图做类似的事情:
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();
});
}
Run Code Online (Sandbox Code Playgroud)
但是,当然,它没有用。
mir*_*cal 11
You can use BlocListener or BlocConsumer from flutter_bloc for showing Dialogs, Snackbars or for navigating to a new page.
With this approach you may want to refactor to rely on the bloc state rather than accessing the stream directly.
Listener is guaranteed to only be called once for each state change, however builder can be called many times. Also you can't do some operations on builders, such as navigating to another page.
return Scaffold(
appBar: AppBar(
title: Text("Title"),
),
body: BlocProvider<YourBloc>(
create: () => YourBloc(),
child: Stack([
SnackbarManager(),
YourScreen(),
]),
),
);
...
/// This is basically an empty UI widget that only
/// manages the snackbar
class SnackbarManager extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocListener<YourBloc, YourBlocState>(
listener: (context, state) {
if (state.hasMyData) {
Scaffold.of(context).showSnackBar(SnackBar(
content:
Text("I got data"),
));
}
},
child: Container(),
);
}
}
Run Code Online (Sandbox Code Playgroud)
Note: BlocConsumer is combination of BlocBuilder and BlocListener, allows you to use listener and builder from same widget.
构建工作时无法显示对话框。当您有新数据时,然后创建一个新的小部件。在这种情况下可能不使用流可能会更好,但是如果有必要,您应该使用
WidgetsBinding.instance.addPostFrameCallback((_)=> yourFunction(context));
要么
Future.microtask(()=> showDialogFunction(context));
如果你
if (snapshot.hasData) {
WidgetsBinding.instance.addPostFrameCallback((_) => showDialogFunction(context));
}
此代码将在构建方法后启动,因此将立即显示对话框。
Bloc函数始终返回小部件,因此在流中有数据时始终返回button()或其他wiget
| 归档时间: |
|
| 查看次数: |
3005 次 |
| 最近记录: |