Home > Blockchain >  How to change the state in a bloc?
How to change the state in a bloc?

Time:11-28

I just started to study the bloc and I have a question. I need to change the color when the state is selected, and according to my logic, I have to do state = Colors.red, but unfortunately this is not the case. Can you please tell me what should I do to change the status?

Here is my bloc -

class SumBloc extends Bloc<Color, SumState> {
  SumBloc() : super(SumNotChosen()) {
    on<Color>((event, emit) {
      final state = this.state;
      if(state is SumSelected) {
        emit(state.color) // ??????
      }
    });
  }
}

Here are my states -

abstract class SumState {}

class SumNotChosen extends SumState{}
class SumSelected extends SumState{
  final Color color;
  SumSelected({required this.color});
}

CodePudding user response:

You can use more simpler cubit for this functionality.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class SumCubit extends Cubit<Color> {
  SumCubit() : super(Colors.red);
  void select() => emit(Colors.green);
  void chooseColor(Color color) => emit(color);
}

class DemoWidget extends StatelessWidget {
  const DemoWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: BlocProvider(
        create: (context) => SumCubit(),
        child: Center(
          child: BlocBuilder<SumCubit, Color>(
            builder: (context, state) {
              return ListTile(
                title: const Text('hello'),
                tileColor: state,
                onTap: () => context.read<SumCubit>().select(),
                onLongPress: () =>
                    context.read<SumCubit>().chooseColor(Colors.black),
              );
            },
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

When using bloc you should listen to events and change states accordingly.

sum_state.dart

part of 'sum_bloc.dart';

abstract class SumState {
  final Color? color;

  const SumState({this.color});
}

class SumInitial extends SumState {}

class SumSelected extends SumState {
  const SumSelected({required super.color});
}

sum_event.dart

part of 'sum_bloc.dart';

abstract class SumEvent {}

class ColorSelected extends SumEvent {
  final Color color;

  ColorSelected({required this.color});
}

sum_bloc.dart

import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';

part 'sum_event.dart';
part 'sum_state.dart';

class SumBloc extends Bloc<SumEvent, SumState> {
  SumBloc() : super(SumInitial()) {
    on<ColorSelected>((event, emit) {
      emit(SumSelected(color: event.color));
    });
  }
}

Here yous listen to SumSelected event and emit new state

  • Related