mmcib
mmcib

Reputation: 141

Flutter - cubit - changing boolean value inside cubit

I would like to change bool values from the cubit, but I can't figure out how to do it.

What I want to achieve is, for instance: if (boolean value stored in cubit is true) "show widget A" : "show widget B"

My code:

class ChangeBoolCubit extends Cubit<bool> {
  ChangeBoolCubit() : super(false);

  bool one = false;
  bool two = true;

  void changeValue(bool booleanToChange) {
    booleanToChange = !state;
    emit(booleanToChange);
  }
}

View:

class BoolView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Changing Bool')),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Center(
            child: BlocBuilder<ChangeBoolCubit, bool>(
              builder: (context, state) {
                return (ChangeBoolCubit().one)
                    ? Text('TRUE: ${ChangeBoolCubit().one}')
                    : Text('FALSE: ${ChangeBoolCubit().one};');
              },
            ),
          ),
          Center(
            child: BlocBuilder<ChangeBoolCubit, bool>(
              builder: (context, state) {
                return (ChangeBoolCubit().two)
                    ? Text('TRUE: ${ChangeBoolCubit().two}')
                    : Text('FALSE: ${ChangeBoolCubit().two};');
              },
            ),
          ),
      ],),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            child: const Icon(Icons.add),
            onPressed: () => context.read<ChangeBoolCubit>().changeValue(ChangeBoolCubit().one),
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            child: const Icon(Icons.remove),
            onPressed: () => context.read<ChangeBoolCubit>().changeValue(ChangeBoolCubit().two),
          ),
        ],
      ),
    );
  }
}

I'm sorry for probably that trivial question, but I'm new to Cubit/Bloc.

Upvotes: 4

Views: 1852

Answers (2)

태유아빠
태유아빠

Reputation: 1

I handled it by writing this:

class ConnectionStateCubit extends Cubit<bool> {
  ConnectionStateCubit() : super(false);

  void enableConnection() => emit(true);
  void disableConnection() => emit(false);
}

The code using the builder is as follows.

Widget build(BuildContext context) {
    var connectionStateCubit = BlocProvider.of<ConnectionStateCubit>(context);
    return BlocBuilder<ConnectionStateCubit, bool>(builder: (context, state) {
        return ElevatedButton(
            onPressed: () {
                if (!state) {
                    print("connection");
                    connectionStateCubit.enableConnection();
                } else {
                    print("disconnection");
                    connectionStateCubit.disableConnection();
                }
            },
            style: ElevatedButton.styleFrom(
                shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(10))),
                side: const BorderSide(color: Colors.white, width: 5.0),
                backgroundColor: state ? Colors.deepOrange : Colors.green,
            ),
            child: const Text(
                "Connection",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold),
                ),
            ),
        );
    });
}

Upvotes: 0

Victor Kwok
Victor Kwok

Reputation: 652

You should use the state in the BlocBuilder.

For example:

BlocBuilder<ChangeBoolCubit, bool>(
          builder: (context, state) {
            return state
                ? Text('TRUE: ${ChangeBoolCubit().one}')
                : Text('FALSE: ${ChangeBoolCubit().one};');
          },
        )

However, I think this is what you want:

class ChangeBoolState {
    final bool one;
    final bool two;
    ChangeBoolState({this.one = false, this.two = true});
    ChangeBoolState copyWith({
        bool? one,
        bool? two,
    }){
        return RegisterState(
            one: one != null ? one : this.one,
            two: two != null ? two : this.two
        );
    }
}

class ChangeBoolCubit extends Cubit<ChangeBoolState> {
    void changeOne() {
        emit(state.copyWith(
            one: !state.one,
        ));
    }
}

then use it like this:

BlocBuilder<ChangeBoolCubit, bool>(
          builder: (context, state) {
            return state.one
                ? Text('TRUE: ${state.one}')
                : Text('FALSE: ${state.two};');
          },
        )

Upvotes: 5

Related Questions