Home > database >  How to access a variable present in state in cubit in flutter?
How to access a variable present in state in cubit in flutter?

Time:04-12

I am using cubit for state management in my app. I have a variable in the state called prices which I want to access:

Future<void> fetchMonthlyTotals(String userId) async {
    //var userId = await getUserId();
    var prices =
        await myDB().getPrices(userId);
    print(prices .toString());
    // ignore: unnecessary_null_comparison
    if (prices != null && prices .isNotEmpty) {
      emit(MonthlyTotalsState(monthlyTotals: prices ));
    } else {
      debugPrint("prices is empty");
    }
  }

This is the class where I want to access prices variable:

void getExpenses() async {
    var prices = //get price from cubit
    print(prices);
}

Both the codes are in different classes and are present in the same package

How do I access the price variable?

Kindly comment if more information is needed.

CodePudding user response:

If you need to use this value inside the UI you should use a CubitBuilder. It will update your UI whenever the state changes.

CubitBuilder<ReportinCubit, MonthlyTotalsState>(
        builder: (_, monthlyTotalState) {
          return Center(
            child: Text('Monthly Total Prices: ${monthlyTotalState.prices}'),
          );
        },
      ),

CodePudding user response:

If you need to use this value inside the UI you should use a BlocBuilder. It will update your UI whenever the state changes. If you however want to do something like showing a dialog or navigating in response to a state change you should use a BlocListener. If you want to do a combination of both of the mentioned use-cases you can use a BlocConsumer

BlocBuilder<ReportinCubit, MonthlyTotalsState>(
        builder: (_, monthlyTotalState) {
          return Center(
            child: Text('Monthly Total Prices: ${monthlyTotalState.prices}'),
          );
        },
      ),
  • Related