如何在 flutter 中访问 cubit 状态中存在的变量?
How to access a variable present in state in cubit in flutter?
我在我的应用程序中使用 cubit 进行状态管理。我在状态中有一个名为 prices
的变量,我想访问它:
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");
}
}
这是我要访问 prices
变量的 class:
void getExpenses() async {
var prices = //get price from cubit
print(prices);
}
这两个代码在不同的 class 中并且存在于同一个包中
如何访问 price
变量?
如果需要更多信息,请发表评论。
如果您需要在 UI 中使用此值,您应该使用 CubitBuilder
。
只要状态发生变化,它就会更新您的 UI。
CubitBuilder<ReportinCubit, MonthlyTotalsState>(
builder: (_, monthlyTotalState) {
return Center(
child: Text('Monthly Total Prices: ${monthlyTotalState.prices}'),
);
},
),
如果您需要在 UI 中使用此值,您应该使用 BlocBuilder
。
只要状态发生变化,它就会更新您的 UI。
但是,如果你想做一些事情,比如显示对话框或导航以响应状态变化,你应该使用 BlocListener
。如果您想结合上述 use-cases 两者,您可以使用 BlocConsumer
BlocBuilder<ReportinCubit, MonthlyTotalsState>(
builder: (_, monthlyTotalState) {
return Center(
child: Text('Monthly Total Prices: ${monthlyTotalState.prices}'),
);
},
),
你也可以这样使用
BlocBuilder<Cubit, CubitState>(
buildWhen: (previous, current) => current is MonthlyTotalsState
builder: (context, state) {
if(state is MonthlyTotalsState){
return Center(
child: Text('Monthly TotalPrices:${state.monthlyTotals}'),
);
}
return const SizedBox();
},
),
我在我的应用程序中使用 cubit 进行状态管理。我在状态中有一个名为 prices
的变量,我想访问它:
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");
}
}
这是我要访问 prices
变量的 class:
void getExpenses() async {
var prices = //get price from cubit
print(prices);
}
这两个代码在不同的 class 中并且存在于同一个包中
如何访问 price
变量?
如果需要更多信息,请发表评论。
如果您需要在 UI 中使用此值,您应该使用 CubitBuilder
。
只要状态发生变化,它就会更新您的 UI。
CubitBuilder<ReportinCubit, MonthlyTotalsState>(
builder: (_, monthlyTotalState) {
return Center(
child: Text('Monthly Total Prices: ${monthlyTotalState.prices}'),
);
},
),
如果您需要在 UI 中使用此值,您应该使用 BlocBuilder
。
只要状态发生变化,它就会更新您的 UI。
但是,如果你想做一些事情,比如显示对话框或导航以响应状态变化,你应该使用 BlocListener
。如果您想结合上述 use-cases 两者,您可以使用 BlocConsumer
BlocBuilder<ReportinCubit, MonthlyTotalsState>(
builder: (_, monthlyTotalState) {
return Center(
child: Text('Monthly Total Prices: ${monthlyTotalState.prices}'),
);
},
),
你也可以这样使用
BlocBuilder<Cubit, CubitState>(
buildWhen: (previous, current) => current is MonthlyTotalsState
builder: (context, state) {
if(state is MonthlyTotalsState){
return Center(
child: Text('Monthly TotalPrices:${state.monthlyTotals}'),
);
}
return const SizedBox();
},
),