How can I change bool true false with cubit?

Issue

I want to show an icon if bool editI == true and don’t show it if editI == false.
But I can’t change the value of editI in cubit.dart and pass to page.dart

I have this

cubit

class LayoutCubit extends Cubit<LayoutStates> {
  LayoutCubit() : super(LayoutInitState());

  static LayoutCubit get(context) => BlocProvider.of(context);
...
 bool editI = false;

  void changeEditI(editI) {
    print(editI);
    editI = !editI;
    emit(LayoutChangeEditIState());
    print(editI);
  }

page

class ProfileScreen extends StatelessWidget {
    final String? id;
  const ProfileScreen({Key? key, required this.id}) : super(key: key);
    @override
    Widget build(BuildContext context) {
      return BlocConsumer<LayoutCubit, LayoutStates>(
        listener: (context, state) {},
        builder: (context, state) {
            var cubit = LayoutCubit.get(context);
            cubit.getUserDataById(id!);
            return Scaffold(
            ...
            IconButton(
              onPressed: (() { 
                cubit.changeEditI(editI);
              }),
              icon: const Icon( Icon.edit,size: 20))
            ...
            child: ListTile(
              ...        
              trailing: editI == true ? IconButton(
                onPressed: () {}, 
                icon:const Icon(Icon.delete)): null,
              ...

Solution

You do not overwrite the old value, but the local variable:

void changeEditI(bool editI) {
    print(editI);
    this.editI = !editI;
    emit(LayoutChangeEditIState());
    print(editI);
}

or simply:

void changeEditI() {
    print(editI);
    editI = !editI;
    emit(LayoutChangeEditIState());
    print(editI);
}

Additionally editI must be part of the state. emit(state) only works if the new state is different from the old. Furthermore, everything you need for building should be part of the state.

Answered By – Mäddin

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.