Ugurcan Ucar
Ugurcan Ucar

Reputation: 406

Flutter Cubit After state change my variable resets

On my screen, it has a list and i can choose some elements. When i choose i want to save it to a variable and can use it later in another screen. So i using cubit in here.I using like that :

My UI:

BlocProvider(
                create: (context) => TherapyCubit(),
                child: Wrap( 
                  children: [
                    for (final therapy in therapyList)
                      EllipsisCard(
                        therapy: therapy,
                      )
                  ],
                ),
              )

EllipsisCard:

InkWell(
      onTap: () {
        setState(() {
          isSelected = !isSelected;
        });
        if (isSelected) {
          context.read<TherapyCubit>().addTherapy(widget.therapy);
        } else {
          context.read<TherapyCubit>().deleteTherapy(widget.therapy);
        }
      },
      child: Container(..

Cubit:

class TherapyCubit extends Cubit<TherapyState> {
  TherapyCubit() : super(TherapyInitial());

  List<Therapy> selectedTherapies = [];

  void addTherapy(Therapy therapy) {
    selectedTherapies.add(therapy);
    inspect(selectedTherapies);
  }

  void deleteTherapy(Therapy therapy) {
    selectedTherapies.remove(therapy);
  }
}

Cubit State:

abstract class TherapyState extends Equatable {
  const TherapyState();

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

class TherapyInitial extends TherapyState {}

On my page i have a state named like "step". That thing has 2 step. When my step is 1 i showing first page and when my step is 2 i showing second page with Visibility.

enter image description here

But when i press back button i setting step state to 1 again so showing first page again but now i cant see any of my choosen elements. And on cubit my list (selectedTherapies) is being empty again. Why its being like that ? How can i solve it ?

Upvotes: 2

Views: 1488

Answers (1)

ratloser
ratloser

Reputation: 118

There are two options:

  • Either the cubit is replaced (try adding a print inside your Cubit constructor to diagnose)
  • Or your UI isn't showing the selectedTherapies List properly

Where did you placed your BlocProvider inside the widget tree?

Upvotes: 3

Related Questions