【问题标题】:How to use flutter_bloc to change the UI when the state is the same but the state content is different状态相同但状态内容不同时如何使用flutter_bloc改变UI
【发布时间】:2020-03-30 20:21:47
【问题描述】:

我正在使用来自 flutter_bloc 包的 BlocBuilder 来响应状态变化。

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BreathalyzerBloc, BreathalyzerState>(
      builder: (context, state) {

        if (state is BreathalyzerConnected) {
          return Center(child: Text('CONNECTED'));
        }

        if (state is BreathalyzerWarmingUp) {
          return Center(child: Text('PREPARE TO BLOW IN ${state.countDown}'));
        }

      },
    );

问题:多个连续事件产生连续的 BreathalyzerWarmingUp 状态,但连续具有不同的 countDown 值(例如,3、2、1)。但是,由于没有实际转换到不同的状态,因此 BlocBuilder 会忽略后续状态,并且 UI 只会显示第一个倒计时值。

期待画面变化如下:

PREPARE TO BLOW IN 3
PREPARE TO BLOW IN 2
PREPARE TO BLOW IN 1

刚刚得到:

PREPARE TO BLOW IN 3

有什么建议吗?

【问题讨论】:

    标签: flutter-bloc


    【解决方案1】:

    将此追溯到 BreathalyzerWarmingUp 上扩展 Equatable 的 props 函数的缺失覆盖。因为缺少道具覆盖,BlocBuilder 将连续的 BreathalyzerWarmingUp 状态视为相等,即使在 countDown 递减时也是如此。

    代码不正确

    class BreathalyzerWarmingUp extends BreathalyzerState {
      final String countDown;
    
      BreathalyzerWarmingUp({@required this.countDown}) : super();
    
      @override
      String toString() => 'BreathalyzerWarmingUp { countDown: $countDown }';
    }
    

    更正的代码:

    class BreathalyzerWarmingUp extends BreathalyzerState {
      final String countDown;
    
      BreathalyzerWarmingUp({@required this.countDown}) : super();
    
      @override
      List<Object> get props {
        return [countDown];
      }
    
      @override
      String toString() => 'BreathalyzerWarmingUp { countDown: $countDown }';
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2020-09-13
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多