【问题标题】:Unable to get same State from same Click Action Flutter无法从相同的 Click Action Flutter 获得相同的状态
【发布时间】:2020-07-09 01:41:26
【问题描述】:

我在 BlocLibrary 中遇到问题(https://bloclibrary.dev/) 我需要在 BlocListner/BlocBuilder 中接收相同的状态,让我用代码解释一下: 这是 Bloc(稍微解释一下):

class CounterBloc extends Bloc<CounterEvent, AppState> {
  @override
  AppState get initialState => InititalState();

  @override
  Stream<AppState> mapEventToState(CounterEvent event) async* {
    switch (event) {
      case CounterEvent.getState:
        yield Counter(value: 0); 
        break;
  }

这里是状​​态类:

import 'package:flutter_bloc/flutter_bloc.dart';
enum StateEvent { getState }

abstract class AppState extends Equatable {
  const AppState();

  @override
  List<Object> get props => [];
}


class Counter extends AppState {
  final int count;
  const Counter({@required this.count});
  @override
  List<Object> get props => [count];

  @override
  String toString() => 'Counter { count: $count }';
}

这里是我的 bloc 监听器/构建器:

BlocListener<CounterBloc, AppState>(
    listener: (context, state) {
      if (state is Counter) {

  **Here I needed same state, means if I press getState, it should print 0 everytime**
        print(state. value);

      }
    },
    child: BlocBuilder<CounterBloc, AppState>(
      builder: (context, state) {
        return Center(
          child: Text(
            '${value}',
            style: TextStyle(fontSize: 24.0),
          ),
        );
      },
    ),
  )

【问题讨论】:

  • BlocListener 应该定义一个 bloc 参数,该参数指向您要收听的 bloc 类。
  • 如果我按下一次,我可以得到结果意味着可以打印。但是如果我一次又一次按,它不会收到
  • 那么您的 Counter 状态定义缺少 props 函数调用。显示你的 Counter 类。
  • @Thepeanut 我已经用 State Class 更新了问题
  • 好的,我错过了你说你不改变 count 变量的部分。 Bloc 是为了在与旧状态相同时不会推送新状态。这就是为什么监听器只触发一次,因为 count 没有改变。

标签: flutter events state bloc stateful


【解决方案1】:

更改您的 AppState,您可以阅读更多关于 Equatable 用法的信息here。本帖多为this的重复。

如果您希望背靠背的相同状态触发多个转换,则不应使用 Equatable。

abstract class AppState { 
  const AppState();
} 

class Counter extends AppState { 
  final int count; 

  const Counter({@required this.count}); 

  @override
  String toString() => 'Increment { count: $count }'; 
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2020-03-21
    • 2021-12-19
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多