如何在颤振中使用 bloc 的无限负载?

时间:2021-04-11 12:44:38

标签: flutter dart flutter-layout bloc rxdart

我在使用 bloc 执行无限加载数据时遇到问题,我在检索分类数据时使用无限加载。情况是在访问一个类别时,上一个类别的数据会进入另一个类别,这是因为转到另一个类别时数据没有重置,问题是移动到另一个类别时如何重置以前的数据?< /p>

ma​​in.dart

class MyApp extends StatelessWidget {
@override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
            create: (context) =>
                ProductByCategoryBloc()..add(ProductByCategoryEvent())),
      ],
      child: route.GetMaterialApp(
        defaultTransition: route.Transition.cupertino,
        debugShowCheckedModeBanner: false,
        home: MainPage(),
      ),
    );
  }
}

bloc.dart

class ProductByCategoryEvent {
  final int idCategory;

  ProductByCategoryEvent({this.idCategory});
}

abstract class ProductByCategoryStateBloc {}

class ProductByCategoryUnitialized extends ProductByCategoryStateBloc {}

class ProductByCategoryLoadedBloc extends ProductByCategoryStateBloc {
  List<Product> products;
  bool max;
  ProductByCategoryLoadedBloc({this.products, this.max});
  ProductByCategoryLoadedBloc copyWith({List<Product> products, bool max}) {
    return ProductByCategoryLoadedBloc(
      products: products ?? this.products,
      max: max ?? this.max,
    );
  }
}

class ProductByCategoryBloc
    extends Bloc<ProductByCategoryEvent, ProductByCategoryStateBloc> {
  ProductByCategoryBloc({ProductByCategoryStateBloc initialState})
      : super(ProductByCategoryUnitialized());

  reloadData() async* {
    ApiReturnValue<List<Product>> products;

    products = await ProductServices.getProductCategory(skip: 0, idCategory: 1);
    yield ProductByCategoryLoadedBloc(products: products.value, max: false);
  }

  @override
  Stream<ProductByCategoryStateBloc> mapEventToState(
      ProductByCategoryEvent event) async* {
    ApiReturnValue<List<Product>> products;
    if (state is ProductByCategoryUnitialized) {
      products =
          await ProductServices.getProductCategory(skip: 0, idCategory: 1);
      yield ProductByCategoryLoadedBloc(products: products.value, max: false);
    } else {
      ProductByCategoryLoadedBloc productLoadedBloc =
          state as ProductByCategoryLoadedBloc;
      products = await ProductServices.getProductCategory(
          skip: productLoadedBloc.products.length,
          idCategory: event.idCategory);
      yield (products.value.isEmpty)
          ? productLoadedBloc.copyWith(max: true)
          : ProductByCategoryLoadedBloc(
              products: productLoadedBloc.products + products.value,
              max: false);
    }
  }
}


ui_kategori.dart

class CategoryProductPage extends StatefulWidget {
  final CategoryProduct category;

  CategoryProductPage({this.category});

  @override
  _CategoryProductPageState createState() => _CategoryProductPageState();
}

class _CategoryProductPageState extends State<CategoryProductPage> {
  int selectedIndex = 0;
  ScrollController controller = ScrollController();
  ProductByCategoryBloc productBloc;

  void onScroll() {
    double maxScroll = controller.position.maxScrollExtent;
    double currentScroll = controller.position.pixels;

    if (currentScroll == maxScroll) {
      productBloc.add(ProductByCategoryEvent(idCategory: widget.category.id));
    }
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    productBloc = BlocProvider.of<ProductByCategoryBloc>(context);
    controller.addListener(onScroll);

    final double itemWidth = (size.width) / 2;
    return Scaffold(
      body: Column(
        children: [
          Container(margin: EdgeInsets.only(top: 24), child: Navbar()),
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height - 110,
            child: CustomScrollView(
              controller: controller,
              slivers: <Widget>[
                SliverList(
                  delegate: SliverChildListDelegate(
                    [
                      Container(
                          margin: EdgeInsets.only(bottom: 35, top: 20),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: BlocBuilder<SliderBloc, SliderStateBloc>(
                              builder: (_, state) => (state is SliderLoadedBloc)
                                  ? BannerSection(state.sliders)
                                  : Center(child: loadingIndicator))),
                      Container(
                        margin: EdgeInsets.only(left: 10, bottom: 10, top: 20),
                        child: Text(widget.category.name, style: text17),
                      )
                    ],
                  ),
                ),
                BlocBuilder<ProductByCategoryBloc, ProductByCategoryStateBloc>(
                    builder: (_, state) {
                  if (state is ProductByCategoryUnitialized) {
                    return SliverList(
                      delegate: SliverChildListDelegate(
                        [
                          Center(child: loadingIndicator),
                        ],
                      ),
                    );
                  } else {
                    ProductByCategoryLoadedBloc productLoaded =
                        state as ProductByCategoryLoadedBloc;

                    return SliverGrid(
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        childAspectRatio: (itemWidth + 10) / (200),
                        mainAxisSpacing: 8,
                      ),
                      delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                        if (index < productLoaded.products.length) {
                          return Container(
                              margin: EdgeInsets.only(
                                  left: (index % 2 == 0) ? 10 : 0,
                                  right: (index % 2 == 0) ? 0 : 10),
                              child: GestureDetector(
                                  onTap: () {
                                    Get.to(ProductDetailsPage(
                                      product: productLoaded.products[index],
                                      onBackButtonPressed: () {
                                        Get.back();
                                      },
                                    ));
                                  },
                                  child: ProductCard(
                                      productLoaded.products[index])));
                        } else {
                          return Container(
                              child: Center(child: loadingIndicator));
                        }
                      },
                          childCount: (productLoaded.max)
                              ? productLoaded.products.length
                              : productLoaded.products.length + 1),
                    );
                  }
                }),
                SliverList(
                  delegate: SliverChildListDelegate(
                    [
                      Container(height: 100),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

你能帮我解决这里的问题吗?

0 个答案:

没有答案