简体   繁体   English

在 flutter 中的 state 上显示警报

[英]show alert on cubit state in flutter

I know we can return different widgets on certain state of cubit, but how can we show an alert or other interactions on states:我知道我们可以在特定的 state 肘上返回不同的小部件,但是我们如何显示警报或其他状态交互:

BlocBuilder<LoginCubit, LoginState> (
  builder: (context, LoginState loginState) {
    if (loginState is LoginInitial) {
      return Text("LoginInitial");
    } else if (loginState is LoginLoading) {
      return Text("LoginLoading");
    } else if (loginState is LoginLoaded) {
      return Text("LoginLoaded");
    } else if (loginState is LoginError) {
      return Text("LoginError");
    } else {
      return Container();
    }
  },
)

here in LoginError I want to show an alert dialog.在 LoginError 中,我想显示一个警告对话框。

You can use BlocConsumer , which has both a builder and a listener :您可以使用BlocConsumer ,它具有builderlistener

  • The builder attribute is the widget builder callback you already know builder属性是您已经知道的小部件构建器回调
  • The listener is a callback called when the state changes and you can do pretty much anything there. listener是在状态更改时调用的回调,您几乎可以在其中执行任何操作。

For more fine grained control you can use buildWhen and listenWhen , which trigger respectively the builder or listener callbacks if they return true .对于更细粒度的控制,您可以使用buildWhenlistenWhen ,如果它们返回true它们将分别触发builderlistener回调。

For example you can see how I've used BlocConsumer to show a SnackBar when an error state occurs here .例如,您可以看到我如何使用BlocConsumer此处发生错误状态时显示SnackBar

Don't mind the double check on the type不要介意仔细检查类型

if (state is RegionalReportLoadingError)

because it's probably useless (according to the docs) and I just wanted to be sure about that when I did not have the usage of listenWhen very clear.因为它可能没用(根据文档),我只是想确定一下,当我没有非常清楚的使用listenWhen

You can check more about BlocConsumer in the docs (Unfortunately I cannot link the anchor).您可以在文档中查看有关BlocConsumer更多信息(不幸的是,我无法链接锚点)。

Showing dialogs, snackbars, exiting the screen or navigating somewhere else - these kind of tasks should be done in listeners, like this:显示对话框、快餐栏、退出屏幕或导航到其他地方——这些类型的任务应该在监听器中完成,如下所示:

useCubitListener<BookDetailsCubit, BookDetailsPageState>(cubit, (cubit, state, context) {
  state.maybeWhen(
    saveBook: () => context.router.pop<bool>(true),
    deleteBook: () => context.router.pop<bool>(true),
    orElse: () => null,
  );
}, listenWhen: (state) => (state is BookDetailsPageSaveBook || state is BookDetailsPageDeleteBook));

Here I used cubits with hooks.在这里,我使用带钩的肘尺。 useCubitListener() is a global function. More on this in my Flutter cubits + hooks tutorial . useCubitListener()是一个全局 function。更多信息请参阅我的Flutter cubits + hooks 教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM