我的肘部没有发出冻结的新状态?

My cubit is not emitting a new state with freezed?

我正在尝试使用 Cubit 进行状态管理,并且我有一个带有 @freezed 注释的状态 class。我以前用过 cubits,之前没有看到任何类似的问题。在 cubit 构造函数中,我使用超级构造函数发出初始状态,BLocBuilder 捕获该初始状态。然后,每当我发射一个新的状态时,我的肘实际上并没有发射。这是我的代码的样子:

promotion_state.dart

part of 'promotion_cubit.dart';

@freezed
abstract class PromotionState with _$PromotionState {
  const factory PromotionState.initial() = _Initial;
  const factory PromotionState.loaded({required TrophyIconType trophyIconType}) = _Loaded;
}

promotion_cubit.dart


Future<void> whenMenuPageDisplayed() async {
  emit(const PromotionState.loaded(trophyIconType: TrophyIconType.withAnimation));
}

menu_page.dart

return BlocProvider<PromotionCubit>(
      create: (_) => getIt<PromotionCubit>()..init(),
      child: BlocBuilder<PromotionCubit, PromotionState>(
        builder: (context, state) => state.maybeWhen(
          initial: () => const SizedBox.shrink(),
          loaded: (trophyIconType) {
            print(state);
            return _TrophyIcon(trophyIconType);
          },
          orElse: () => const SizedBox.shrink(),
        ),
      ),
    );

我在哪里调用whenMenuPageDisplayed函数:


@injectable
class MyNavigatorObserver extends NavigatorObserver {
  MyNavigatorObserver(this._promotionCubit);

  final PromotionCubit _promotionCubit;

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (route.settings.name == '/menu') {
      _promotionCubit.whenMenuPageDisplayed();
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (previousRoute!.settings.name == '/menu') {
      _promotionCubit.whenMenuPageDisplayed();
    }
  }
}

print(state); 处于加载状态,终端中不显示任何输出。

对于那些在 google 搜索时偶然发现这个问题的人来说,问题是 getIt 在被请求时正在创建肘的新实例。

解决方案是在作者的案例中用@singleton 或@lazySingleton 注释肘class。