Search code examples
flutterdartbloc

How to display items from API


I have success to display the items with ListView.builder, now I want to display the items based on their ACTIVE or INACTIVE status at API. So when I want to display ACTIVE, it only shows the active items, and goes the same with INACTIVE.

And my code is like this:

BlocBuilder<FoodBloc, FoodState>(
                    builder: (context, state) {
                      return ListView.builder(
                        itemCount: state.food.length,
                        itemBuilder: (context, index) {
                          return Row(
                            children: [
                              const SizedBox(
                                height: 10,
                                width: 10,
                                child: CircleAvatar(
                                  foregroundColor:
                                      ColorName.brandSecondaryGreen,
                                  backgroundColor:
                                      ColorName.brandSecondaryGreen,
                                ),
                              ),
                              const SizedBox(
                                width: 5,
                              ),
                              Text(
                                state.food[index].identity,
                                style: subtitle1(),
                              ),
                            ],
                          );
                        },
                      );
                    },
                  ),

Solution

  • I'd do it like this without having to create an extra counter for active devices:

    return ListView.builder(
      itemCount: state.food.length,
      itemBuilder: (context, index) {
        return Visibility(
          visible: state.food[index].status == "ACTIVE" ? true : false,
          child: Row(
            children: [
              const SizedBox(
                height: 10,
                width: 10,
                child: CircleAvatar(
                  foregroundColor: ColorName.brandSecondaryGreen,
                  backgroundColor: ColorName.brandSecondaryGreen,
                ),
              ),
              const SizedBox(
                width: 5,
              ),
              Text(
                state.food[index].identity,
                style: subtitle1(),
              ),
            ),
        ],
      );