Reputation: 403
I am trying to figure out the optimal approach in creating a Flutter DropDownButton using Bloc/Cubit. I have a working solution but it is ugly.
I have a Product Page with Category DropDown button. To populate the data, I am using BlocBuilder for CategoryCubit
categoryField
var categoryField = Column(
children: [
BlocBuilder<CategoriesCubit, CategoriesState>(
builder: (context, state) {
if (state is CategoriesLoaded) {
if (product != null && state.selectedCategory == null) {
BlocProvider.of<CategoriesCubit>(context)
.selectCategory(product!.category);
}
List<DropdownMenuItem<Category>> dropDownItems = state.categories
.map((e) => DropdownMenuItem<Category>(
value: e,
child: Text(e.categoryName),
))
.toList();
void onChange<Category>(cat) {
BlocProvider.of<CategoriesCubit>(context).selectCategory(cat);
BlocProvider.of<ProductsCubit>(context)
.updateProductCategory(cat);
}
return CustomDropdown<Category>(
labelText: "Select Category",
value: state.selectedCategory,
items: dropDownItems,
context: context,
onChanged: onChange,
);
}
return const SizedBox(
width: 10,
);
},
),
],
);
CategoryLoadedState
class CategoriesLoaded extends CategoriesState {
final List<Category> categories;
final List<Category>? filteredData;
final int? sortIndex;
final bool sortAscending;
final Category? selectedCategory;
CategoriesLoaded({
required this.categories,
this.filteredData,
this.sortIndex,
required this.sortAscending,
this.selectedCategory,
});
}
This field is inside a ProductPage Stateful Widget wrapped in ProductCubit and CategoryCubit. To populate the dropdown, I wrapped the widget to a BlocProvider monitoring the CategoryCubit. Also, the default value is from the CategoryLoaded state.
onChange of the dropdown value, I set the Product.category value by updating the StreamController of my ProductCubit.
This works, but what I actually want to do is just populate the dropwdown item list, then read the initial value from the ProdutCubit - Product.category rather than CategoryCubit - selectedCategory.
I also tried calling the Category API directly to get the Category List without using Bloc but I think API async call is not allowed in Stateless Widget.
Upvotes: 1
Views: 472