【问题标题】:DropDownButton with Cubit带 Cubit 的下拉按钮
【发布时间】: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


    【解决方案1】:

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

    1. Cubits 应该是不可变的。您不应该将状态保存在它们内部的变量中,而您现在正在使用 category 变量进行操作。
    2. 您正在检索BlocBuilder 之外的当前选定类别,当Cubit 的状态发生更改时,它不会更新。
    3. 当您调用 setCategory 时,Cubit 的状态保持不变,因为您没有发出任何内容。
    4. 您的CategoriesCubit 的任务是控制类别的获取状态。最好不要添加其他任务。

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

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 2017-10-11
      • 2013-07-06
      • 2018-07-27
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 2014-11-20
      • 2021-01-19
      相关资源
      最近更新 更多