颤动块:点击时更改每个项目的颜色

时间:2020-07-03 10:02:41

标签: flutter flutter-bloc

我正在尝试使用颤振块,所以我创建了这个块:

class CategoriesBloc extends Bloc<CategoriesEvent, CategoriesState> {
  CategoriesBloc() : super(CategoriesInitial());
  List<CategoriesItem> _catItems = [
    CategoriesItem(id: 1, title: "Sugar", prefixIcon: Icons.access_alarms),
    CategoriesItem(id: 2, title: "Calories", prefixIcon: Icons.access_alarms),
    CategoriesItem(id: 3, title: "Salt", prefixIcon: Icons.access_alarms),
    CategoriesItem(id: 4, title: "Fibre", prefixIcon: Icons.access_alarms),
    CategoriesItem(id: 5, title: "Fat", prefixIcon: Icons.access_alarms)
  ];

  List<CategoriesItem> get items => _catItems;

  @override
  Stream<CategoriesState> mapEventToState(
    CategoriesEvent event,
  ) async* {
    if (event is TopCategoriesEvent) {
      yield* _makeCatList(items);
    }
  }
}

Stream<CategoriesState> _makeCatList(List<CategoriesItem> items) async* {
  yield CategoriesStarted(items);
}

class CategoriesItem {
  final int id;
  final String title;
  final IconData prefixIcon;
  final IconData suffixIcon;
  bool selected;

  CategoriesItem(
      {this.id,
      this.title,
      this.prefixIcon,
      this.suffixIcon,
      this.selected = false});
}

现在在主页上,我这样使用:

Container(
              height: 80,
              color: Colors.green[500],
              child: BlocBuilder<CategoriesBloc, CategoriesState>(
                  builder: (context, state) {
                if (state is CategoriesInitial) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                } else if (state is CategoriesStarted) {
                  return _makeCatItems(state.catItems);
                }
                return Container();
              }),

这是我的_makeCatItems方法:

 Widget _makeCatItems(List<CategoriesItem> catItems) {
    print(catItems.length);
    return Container(
      margin: EdgeInsets.only(top: 8.0),
      child: ListView(
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        children: catItems
            .map(
              (item) => Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  InkWell(
                    onTap: () {},
                    child: Container(
                        width: 100,
                        height: 40,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.0),
                          color: Colors.green[300],// change to white when tapped
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            Icon(
                              item.prefixIcon,
                              color: Colors.white,
                            ),
                            Text(
                              item.title,
                              style: TextStyle(color: Colors.white),
                            )
                          ],
                        )),
                  ),
                  SizedBox(
                    width: 16.0,
                  )
                ],
              ),
            )
            .toList(),
      ),
    );
  }

当用户以整体方式单击每个项目时,如何更改背景项目的颜色?

1 个答案:

答案 0 :(得分:1)

您可以在状态下添加一个被轻击的项目的列表,最初为空列表,添加一个事件,该事件在字段中传递项目并将BoxDecoration中的颜色更改为state.tappedItems.contains(item) ? Colors.white : Colors.green[300]。您还需要更改onTap,如下所示:

state.tappedItems.contains(item) 
  ? context.bloc<CategoriesBloc>().add(AddItem())  
  : context.bloc<CategoriesBloc>().add(RemoveItem()),

makeCatItems还需要获取状态作为参数或成为另一个BlocBuilder,以对您而言感觉更好的

E:

将状态更改为(您也需要更改CategoriesState,将final List<CategoriesItem> pressedItems 添加到字段中)

Stream<CategoriesState> _makeCatList(List<CategoriesItem> items, List<CategoriesItem> pressedItems) async* {
  yield CategoriesStarted(items, pressedItems);
}

然后您需要添加事件(CategoryRemoved几乎相同,只需复制并更改名称)

class CategoryAdded extends CategoryEvent {
  final CategoryItem item;

  CategoryAdded(CategoryItem item);
}

因此您同时拥有状态和事件,现在集团需要处理更改。

  @override
  Stream<CategoriesState> mapEventToState(
    CategoriesEvent event,
  ) async* {
    if (event is TopCategoriesEvent) {
      yield* _makeCatList(items);
    } else if (event is CategoryAdded) {
      yield CategoryState(state.items, state.pressedItems..add(event.item));
    } else if (event is CategoryRemoved {
      yield CategoryState(state.items, state.pressedItems..remove(event.item));
    }
  }

现在您的逻辑已设置,现在您只需要更改小部件

 Widget _makeCatItems() {
    return BlocBuilder<CategoryBloc, CategoryState>(
      builder: (context, state) => Container(
      margin: EdgeInsets.only(top: 8.0),
      child: ListView(
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        children: catItems
            .map(
              (item) => Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  InkWell(
                    onTap: () {context.bloc<CategoryBloc>().add(state.pressedItems.contains(item) ? RemoveCategory(item) : AddCategory(item)},
                    child: Container(
                        width: 100,
                        height: 40,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.0),
                          color: state.pressedItems.contains(item) ? Colors.white : Colors.green[300],
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            Icon(
                              item.prefixIcon,
                              color: Colors.white,
                            ),
                            Text(
                              item.title,
                              style: TextStyle(color: Colors.white),
                            )
                          ],
                        )),
                  ),
                  SizedBox(
                    width: 16.0,
                  )
                ],
              ),
            )
            .toList(),
      ),
    );
  );
  }