首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带Cubit的DropDownButton

带Cubit的DropDownButton
EN

Stack Overflow用户
提问于 2020-09-11 00:11:01
回答 1查看 304关注 0票数 1

为了在dropdownbutton中显示categoryList,我使用的是Cubit,它工作正常。我的问题:可以使用Cubit来显示selectedCategory吗?而不使用setState?现在,当选择类别时,它不会显示selectedCategory。库比特:

代码语言:javascript
复制
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;
  }
}

Main:

代码语言:javascript
复制
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);
              },
            );
          }
        },
      ),
    );
  }
}
EN

回答 1

Stack Overflow用户

发布于 2020-09-18 19:03:51

您当前的Cubit实现存在一些问题。

  1. Cubits应该是不可变的。您不应该将状态保留在它们内部的变量中,因为您正在使用anything.
  2. Your variable.
  3. You're在BlocBuilder外部检索当前选定的类别,并且它不会在Cubit的状态更改时进行更新。
  4. 由于您没有发出setCategory,因此Cubit的状态保持不变。CategoriesCubit的任务是控制类别的获取状态。最好不要向其中添加其他任务。

我建议将selectedCategoryId作为小部件的内部状态保留在小部件中,除非您需要在多个小部件之间共享它或将它保留在它的祖先中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63833674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档