Kuldeep
Kuldeep

Reputation: 141

Another exception was thrown: setState() or markNeedsBuild() called during build Error in flutter

Im new to flutter and working on an ecommerce flutter app. When im trying to navigate to search screen its giving some error. Please find the below codes for your reference and help to resolve.

Error : The following assertion was thrown while dispatching notifications for SearchProvider: setState() or markNeedsBuild() called during build. This _InheritedProviderScope<SearchProvider?> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase. The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<SearchProvider?> The widget which was currently being built when the offending call was made was: SearchScreen

Codes Search Screen

    class SearchScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    
    Provider.of<SearchProvider>(context, listen: false).cleanSearchProduct();
    Provider.of<SearchProvider>(context, listen: false).initHistoryList();

    return Scaffold(
      backgroundColor: ColorResources.getIconBg(context),
      resizeToAvoidBottomInset: true,
      body: Column(
        children: [
          // for tool bar
          SearchWidget(
            hintText: getTranslated('SEARCH_HINT', context),
            onSubmit: (String text) {
              Provider.of<SearchProvider>(context, listen: false)
                  .searchProduct(text, context);
              Provider.of<SearchProvider>(context, listen: false)
                  .saveSearchAddress(text);
            },
            onClearPressed: () {
              Provider.of<SearchProvider>(context, listen: false)
                  .cleanSearchProduct();
            },
          ),

          Consumer<SearchProvider>(
            builder: (context, searchProvider, child) {
              return !searchProvider.isClear
                  ? searchProvider.searchProductList != null
                      ? searchProvider.searchProductList.length > 0
                          ? Expanded(
                              child: SearchProductWidget(
                                  products: searchProvider.searchProductList,
                                  isViewScrollable: true))
                          : Expanded(
                              child:
                                  NoInternetOrDataScreen(isNoInternet: false))
                      : Expanded(
                          child: ProductShimmer(
                              isHomePage: false,
                              isEnabled: Provider.of<SearchProvider>(context)
                                      .searchProductList ==
                                  null))
                  : Expanded(
                      flex: 4,
                      child: Container(
                        padding:
                            EdgeInsets.all(Dimensions.PADDING_SIZE_DEFAULT),
                        child: Stack(
                          clipBehavior: Clip.none,
                          children: [
                            Consumer<SearchProvider>(
                              builder: (context, searchProvider, child) =>
                                  StaggeredGridView.countBuilder(
                                crossAxisCount: 3,
                                physics: NeverScrollableScrollPhysics(),
                                itemCount: searchProvider.historyList.length,
                                itemBuilder: (context, index) => Container(
                                    alignment: Alignment.center,
                                    child: InkWell(
                                      onTap: () {
                                        Provider.of<SearchProvider>(context,
                                                listen: false)
                                            .searchProduct(
                                                searchProvider
                                                    .historyList[index],
                                                context);
                                      },
                                      borderRadius: BorderRadius.circular(20),
                                      child: Container(
                                        padding: EdgeInsets.only(
                                            left: 10,
                                            right: 10,
                                            top: 2,
                                            bottom: 2),
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(16),
                                            color: ColorResources.getGrey(
                                                context)),
                                        width: double.infinity,
                                        child: Center(
                                          child: Text(
                                            Provider.of<SearchProvider>(context,
                                                        listen: false)
                                                    .historyList[index] ??
                                                "",
                                            style: titilliumItalic.copyWith(
                                                fontSize:
                                                    Dimensions.FONT_SIZE_SMALL),
                                          ),
                                        ),
                                      ),
                                    )),
                                staggeredTileBuilder: (int index) =>
                                    new StaggeredTile.fit(1),
                                mainAxisSpacing: 4.0,
                                crossAxisSpacing: 4.0,
                              ),
                            ),
                            Positioned(
                              top: -5,
                              left: 0,
                              right: 0,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(getTranslated('SEARCH_HISTORY', context),
                                      style: robotoBold),
                                  InkWell(
                                      borderRadius: BorderRadius.circular(10),
                                      onTap: () {
                                        Provider.of<SearchProvider>(context,
                                                listen: false)
                                            .clearSearchAddress();
                                      },
                                      child: Container(
                                          padding: EdgeInsets.all(5),
                                          child: Text(
                                            getTranslated('REMOVE', context),
                                            style: titilliumRegular.copyWith(
                                                fontSize:
                                                    Dimensions.FONT_SIZE_SMALL,
                                                color: Theme.of(context)
                                                    .primaryColor),
                                          )))
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
            },
          ),
        ],
        ),
        );
       }
     }

Providers

     void initHistoryList() {
    _historyList = [];
    _historyList.addAll(searchRepo.getSearchAddress());
    notifyListeners();
     }

    void cleanSearchProduct() {
    _searchProductList = [];
    _isClear = true;
    _searchText = '';
    notifyListeners();
     }

Upvotes: 0

Views: 2629

Answers (1)

Masum Billah Sanjid
Masum Billah Sanjid

Reputation: 1189

Try to use initial function calling in initState instead of build function

@override
  void initState() {
    WidgetsBinding.instance!.addPostFrameCallback((_) {
    Provider.of<SearchProvider>(context, listen: false).cleanSearchProduct();
    Provider.of<SearchProvider>(context, listen: false).initHistoryList();
    });
    super.initState();
  }

Upvotes: 6

Related Questions