【发布时间】:2020-12-29 04:29:05
【问题描述】:
为了在下拉按钮中显示 categoryList,我使用的是 Cubit,它可以正常工作。我的问题:可以使用 Cubit 来显示 selectedCategory 吗?不使用 setState? Now when select category it doesnt show me selectedCategory. 肘:
class CategoriesCubit extends Cubit<CategoriesState> {
final DataBase dataBase;
final Category category;
CategoriesCubit(this.dataBase, this.category)
: super(CategoriesInitial());
StreamSubscription streamSubscription;
Future getCategories() async {
streamSubscription = dataBase.getCategories().listen((data) {
emit(CategoriesLoaded(data));
});
}
void setCategory(String selectedCategory) {
category.categoryID = selectedCategory;
}
}
主要:
class Main extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => CategoriesCubit(DataBase(), Category()),
child: DropDownButton(),
);
}
}
class DropDownButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
context.bloc<CategoriesCubit>().getCategories();
final category = context.bloc<CategoriesCubit>().category;
return Container(
child: BlocBuilder<CategoriesCubit, CategoriesState>(
builder: (context, state) {
if (state is CategoriesLoaded) {
return DropdownButton(
value: category.categoryID,
hint: Text('choose category'),
items: state.categories
.map((category) => DropdownMenuItem(
child: Text(category.categoryName),
value: category.categoryID,
))
.toList(),
onChanged: (selectedCategory) {
context.bloc<CategoriesCubit>().setCategory(selectedCategory);
print(selectedCategory);
},
);
}
},
),
);
}
}
【问题讨论】:
标签: flutter dart bloc flutter-bloc