skip to Main Content

could I ask for assistance for this problem? My CombosBloc does not receive the CategoryChangedEvent. It was created in main with lazy: false and I am calling the event like this: context.read().add(CategoryChangedEvent(newCategory: widget.task![‘category’]));

This is inside an initState of a screen a few clicks away from the home of the app. My Bloc is setup like this:

class CombosBloc extends Bloc<CombosEvent, CombosState> {
  /// Default constructor. Values are set to default.
  ///
  CombosBloc() : super(const CombosInitial()) {
    on<CategoryChangedEvent>((event, emit) {
      print('OnEvent: ${event.newCategory}');
      emit(state.copyWith(category: event.newCategory));
    });

    on<OrderChangedEvent>((event, emit) {
      emit(state.copyWith(order: event.newOrder));
    });
    on<ArchivedChangedEvent>((event, emit) {
      emit(state.copyWith(archived: event.newArchived));
    });
  }
}

/// Basic event.
sealed class CombosEvent extends Equatable {
  const CombosEvent();

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

/// Event when a value on the Category Combo is changed.
final class CategoryChangedEvent extends CombosEvent {
  /// Default constructor.
  const CategoryChangedEvent({required this.newCategory});

  /// New value.
  final String newCategory;
}

/// Event when a value on the Task Combo is changed.
final class OrderChangedEvent extends CombosEvent {
  /// Default constructor.
  const OrderChangedEvent({required this.newOrder});

  /// New value.
  final String newOrder;
}

/// Event when a value on the Show Archived Switch is changed.
final class ArchivedChangedEvent extends CombosEvent {
  /// Default constructor.
  const ArchivedChangedEvent({required this.newArchived});

  /// New value.
  final bool newArchived;
}

part of 'combos_bloc.dart';

/// Combos State.
final class CombosState extends Equatable {
  /// Default constructor.
  const CombosState({
    required this.category,
    required this.categoryFilter,
    required this.order,
    required this.archived,
  });

  /// Category Combo value.
  final String category;

  /// Used in the filter Combo. It has the additional value "All".
  final String categoryFilter;

  /// Ordering value.
  final String order;

  /// Show Archived Only Switch value.
  final bool archived;

  /// copyWith method.
  CombosState copyWith({
    String? category,
    String? order,
    bool? archived,
  }) {
    return CombosState(
      category: category ?? this.category,
      categoryFilter: categoryFilter ?? this.categoryFilter,
      order: order ?? this.order,
      archived: archived ?? this.archived,
    );
  }

  @override
  List<Object> get props => [category, categoryFilter, order, archived];
}

/// Initial State for the Combos.
final class CombosInitial extends CombosState {
  /// Default constructor. All default values.
  const CombosInitial()
      : super(
          category: '',
          categoryFilter: 'Todas',
          order: 'Mais recentes',
          archived: false,
        );
}

main.dart:

void main() {
  initializeDateFormatting('pt_BR', null).then(
    (_) {
      WidgetsFlutterBinding.ensureInitialized();
      runApp(
        MultiBlocProvider(providers: [
          BlocProvider(create: (_) => CombosBloc(), lazy: false),
        ], child: TimeManager()),
      );
    },
  );
}

Trying to trigger the event:

@override
  void initState() {
    if (widget.isEditing) {
      title = 'Editar tarefa';
      _nameController.text = widget.task!['name'];
      _descController.text = widget.task!['desc'];
      print("widget.task!['category']: ${widget.task!['category']}");
      context
          .read<CombosBloc>()
          .add(CategoryChangedEvent(newCategory: widget.task!['category']));
    super.initState();
  }

The print above shows that map has data in it.

Now I have used a BlocObserver:
I saw changes for my others blocs, but none for CombosBloc. That was with debbuging (F5)
When I tried running without debbuging, I saw this:

CombosBloc Change { currentState: CombosInitial(, Todas, Mais
recentes, false), nextState: CombosState(Estudos, Todas, Mais
recentes, false) }

Didn’t understand why this happened.

I’m trying to capture a variable from CombosBloc state like this:

  void initState() {
    values = context.read<CategoriesCubit>().getCategoryNames();
    selected = context.read<CombosBloc>().state.category;
    print('selected: $selected');
    super.initState();
  }

selected is empty, both with F5 and Ctrl + F5. That causes the crash, as the selected variable is of late type.

2

Answers


  1. double check that the widget where you are dispatching the CategoryChangedEvent has access to the CombosBloc. You mentioned using context.read(), which is correct. Ensure that the context is associated with the BlocProvider where the CombosBloc is provided.

    Example:

    context.read<CombosBloc>().add(CategoryChangedEvent(newCategory: 'your_category'));
    
    Login or Signup to reply.
  2. The event probably is not triggered because you are calling the event in the initState method, where the widgets are not attached yet and the builder is not listening.

    So just make sure your widget is attached and listening using this code in your initState method.

    @override
    void initState() {
      WidgetsBinding.instance.addPostFrameCallback((Duration duration) {
        if (widget.isEditing) {
          title = 'Editar tarefa';
          _nameController.text = widget.task!['name'];
          _descController.text = widget.task!['desc'];
          print("widget.task!['category']: ${widget.task!['category']}");
          context
              .read<CombosBloc>()
              .add(CategoryChangedEvent(newCategory: widget.task!['category']));
        }
      });
    
      super.initState();
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search