Home > Back-end >  The state of flutter bloc is not updating if called outside the bloc builder
The state of flutter bloc is not updating if called outside the bloc builder

Time:05-14

I initialised all necessary blocs in my main file. Even after this, the state of bloc is not updating if called from outside the bloc builder.

I am trying to implement lazy loading using bloc pattern.

Supposed action is when listview reaches end scroll listener calls a bloc function which will fetch the next items and pass the latest item along with previous items to ProductsLoadedState();

But, ProductsLoadedState is not getting trigged even after emitting the state from bloc.

Any help is really appreciated. Thank you.

My bloc code is :

void _onLoadProducts(
      LoadProductsPage event, Emitter<ProductsPageState> emit) async {
    print("getting products");
    page == 1
        ? emit(const ProductsPageLoadingState(isFirstFetch: true))
        : emit(ProductsPageLoadingState(
            oldProducts: this.products, isFirstFetch: false));
    final List<ProductModel> products =
        await productsRepository.handleGetSearchedProducts(
            event.title,
            event.category,
            event.brand,
            event.condition,
            event.productCode,
            page);
    page  ;
    print("page number $page");
    this.products.addAll(products);
    print(this.products.length);
    emit(ProductsPageLoadedState(searchedProducts: this.products));
  }

Main.dart file :

  final AppRouter _appRouter = AppRouter();

  MyApp({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
        providers: [
          BlocProvider<ProductsPageBloc>(
            create: (context) => ProductsPageBloc(),
          ),
        ],
        child: MultiRepositoryProvider(
          providers: [
            RepositoryProvider(create: (context) => ProductsRepository()),
            RepositoryProvider(create: (context) => AuthRepository()),
            RepositoryProvider(create: (context) => BrandRepository()),
          ],
          child: MaterialApp(
            title: 'title',
            theme: ThemeData(
                primarySwatch: Colors.blue,
                fontFamily: 'T MS',
                scaffoldBackgroundColor: const Color(0xffF6F6F9)),
            onGenerateRoute: _appRouter.onGenerateRoute,

            // home : AddressesPage(),
            home: BlocProvider(
              create: (context) => NetworkBloc(),
              child: BlocBuilder<NetworkBloc, NetworkState>(
                builder: (context, state) {
                  return UserMain();
                },
              ),
            ),
          ),
        ));
  }
}

Products.dart file :

class ProductsPage extends StatefulWidget {
  final String title;
  final String category;
  final String brand;
  final String condition;
  final int pageNumber;
  final String productCode;

  const ProductsPage(
      {Key key,
      this.title,
      this.category,
      this.brand,
      this.condition,
      this.pageNumber,
      this.productCode})
      : super(key: key);

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

class _ProductsPageState extends State<ProductsPage> {
  String appBarTitle;
  List<ProductModel> products = [];
  bool isLoading = false;

  final scrollController = ScrollController();

  void setupScrollController(context) {
    scrollController.addListener(() {
      if (scrollController.position.atEdge) {
        if (scrollController.position.pixels != 0) {
          BlocProvider.of<ProductsPageBloc>(context).add(LoadProductsPage(
              title: widget.title,
              category: widget.category,
              brand: widget.brand,
              condition: widget.condition,
              pageNumber: widget.pageNumber,
              productCode: widget.productCode));
        }
      }
    });
  }

  @override
  void initState() {
    setupScrollController(context);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(50),
        child: CustomAppBar(
          isSearchPage: true,
          title: "tilte",
          enableSearchBar: true,
        ),
      ),RepositoryProvider.of<ProductsRepository>(context)
      body: BlocProvider(
        create: (context) => ProductsPageBloc()
          ..add(
            LoadProductsPage(
                title: widget.title,
                category: widget.category,
                brand: widget.brand,
                condition: widget.condition,
                pageNumber: widget.pageNumber,
                productCode: widget.productCode),
          ),
        child: Scaffold(body: Center(
          child: BlocBuilder<ProductsPageBloc, ProductsPageState>(
            builder: (context, state) {
              if (state is ProductsPageLoadingState) {
                if (state.isFirstFetch) {
                  print("is first fetch");
                  return const LoadingSpinnerWidget();
                } else {
                  print("is not first fetch${state.oldProducts}");
                  products = state.oldProducts;
                }
              } else if (state is ProductsPageLoadedState) {
                isLoading = false;
                print("is loaded ${state.searchedProducts} $isLoading");
                products = state.searchedProducts;
                print("state${state.searchedProducts.length}");
                print("products${products.length}");
              }
              if (products.isNotEmpty) {
                return ListView.builder(
                    controller: scrollController,
                    itemCount: products.length   (isLoading ? 1 : 0),
                    itemBuilder: (context, index) {
                      if (index < products.length) {
                        return ProductHorizontal(product: products[index]);
                      } else {
                        Timer(const Duration(milliseconds: 30), () {
                          scrollController.jumpTo(
                              scrollController.position.maxScrollExtent);
                        });
                        return const LoadingSpinnerWidget();
                      }
                    });
              } else {
                return const ShowCustomPage(
                  icon: CupertinoIcons.bag,
                  title:
                      "Sorry, we couldn't find any similar products. Please try searching for other products",
                );
              }
            },
          ),
        )),
      ),
    );
  }
}

CodePudding user response:

It seems like you are using different instances of your ProductsPageBloc. Make sure you use the same object, by initializing it beforehand. For example:

final productsBloc = ProductsPageBloc();
...
void setupScrollController(context) {
    scrollController.addListener(() {
      if (scrollController.position.atEdge) {
        if (scrollController.position.pixels != 0) {
          productsBloc.add(LoadProductsPage(
              title: widget.title,
              category: widget.category,
              brand: widget.brand,
              condition: widget.condition,
              pageNumber: widget.pageNumber,
              productCode: widget.productCode));
        }
      }
    });
  }
...
body: BlocProvider(
        create: (context) => productsBloc..add
...

This is only an assumption, since I'm missing out crucial parts of the code to debug it myself. You could post the whole Bloc, so I could verify the functionality of the add method. Still, I hope it helps.

  • Related