【问题标题】:BlocListener does not build widget on state changeBlocListener 不会在状态更改时构建小部件
【发布时间】:2021-02-21 05:10:15
【问题描述】:

我正在尝试根据 bloc 的状态显示文本,因此我决定使用 BlocListener,因为我认为这是小部件的主要目的。我想在状态为 AuthFailed 时显示文本。

BlocListener

BlocListener<AuthBloc, AuthState>(
  listener: (context, state) {
    if (state is AuthFailed)
      return Text(
        'Oops, Invalid Credentials.',
        style: TextStyle(color: Colors.red),
      );
  },
  child: Container(),
),

问题是,当状态为 AuthFailed 时文本不会出现,但如果我改用 BlocBuilder,它就可以工作。

BlocBuilder

BlocBuilder<AuthBloc, AuthState>(
  builder: (context, state) {
    if (state is AuthFailed)
      return Text(
        'Oops, Invalid Credentials.',
        style: TextStyle(color: Colors.red),
      );
    return Container(
      width: 0,
      height: 0,
    );
  },
),

【问题讨论】:

    标签: flutter flutter-bloc


    【解决方案1】:

    您应该使用 BlocBuilder 来完成该任务。 builder 的目的是根据状态返回一个小部件。

    BlocListener 用于基于状态的路由或显示小吃店等任务。当你想根据状态做某事时。

    文档非常好,请查看:

    https://pub.dev/packages/flutter_bloc

    此外,侦听器函数是一个 void 函数,因此当您返回文本小部件时,它会被丢弃。如果您使用 linting,您可能会收到警告。

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2020-03-18
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多