Flutter - setState() or markNeedsBuild() called during build

3,457

As the error describes, setState is called even before the build function is completed.

You might not see any issue in you UI when this exception hits on debug or local release mode. But exceptions like these displays a grey screen or something instead of the desired widget on google play release etc.

It means you are try to refresh the page even while the initial widget is already loading.

To prevent calling setState during build method is already in progress, you can check whether your initial widget is mounted properly before calling setState. For doing that just wrap your setState by if statement like this :

if(mounted){
   setState((){

   });
}

There is also another method with is called after build method is completed. Follow this question to know more : Is there any callback to tell me when "build" function is done in Flutter?

Share:
3,457
Radiant Developers
Author by

Radiant Developers

Updated on December 28, 2022

Comments

  • Radiant Developers
    Radiant Developers over 1 year

    Showing Error While loading post from Firebase Cloud.. I am using provider in my Application

    setState() or markNeedsBuild() called during build.
    

    Detailed Error

    
    ════════ Exception caught by foundation library ════════════════════════════════
    The following assertion was thrown while dispatching notifications for PostFunctions:
    setState() or markNeedsBuild() called during build.
    
    This _InheritedProviderScope<PostFunctions> 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.
    

    My Code When I Load Post..

     Widget feedBody(BuildContext context) {
        return SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.only(top: 8.0),
            child: Container(
              child: StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance
                    .collection('posts')
                    .orderBy('time', descending: true)
                    .snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Center(
                      child: SizedBox(
                        height: 200.0,
                        width: 200.0,
                        child: Lottie.asset('assets/animations/loading.json'),
                      ),
                    );
                  } else {
                    return loadPosts(context, snapshot);
                  }
                },
              ),
              height: MediaQuery.of(context).size.height * 0.80,
              width: MediaQuery.of(context).size.width,
              decoration: BoxDecoration(
                color: constantColors.darkColor.withOpacity(0.6),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(18.0),
                  topRight: Radius.circular(18.0),
                ),
              ),
            ),
          ),
        );
      }
    

    My Load Post Code

    Widget loadPosts(
          BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        return ListView(
            children: snapshot.data.docs.map((DocumentSnapshot documentSnapshot) {
          Provider.of<PostFunctions>(context, listen: false)
              .showTimeAgo(documentSnapshot.data()['time']);
    
          return Container(
            height: MediaQuery.of(context).size.height * 0.62,
            width: MediaQuery.of(context).size.width,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(
                    top: 8.0,
                    left: 8.0,
                  ),
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          if (documentSnapshot.data()['useruid'] !=
                              Provider.of<Authenticationss>(context, listen: false)
                                  .getUserUid) {
                            Navigator.pushReplacement(
                              context,
                              PageTransition(
                                child: AltProfile(
                                  userUid: documentSnapshot.data()['useruid'],
                                ),
                                type: PageTransitionType.bottomToTop,
                              ),
                            );
                          }
                        },
                        child: CircleAvatar(
                          backgroundColor: constantColors.blueGreyColor,
                          radius: 20.0,
                          backgroundImage:
                              NetworkImage(documentSnapshot.data()['userimage']),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 8.0),
                        child: Container(
                          width: MediaQuery.of(context).size.width * 0.6,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                child: Text(
                                  documentSnapshot.data()['caption'],
                                  style: TextStyle(
                                      color: constantColors.greenColor,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16.0),
                                ),
                              ),
                              Container(
                                child: RichText(
                                  text: TextSpan(
                                    text: documentSnapshot.data()['username'],
                                    style: TextStyle(
                                      color: constantColors.blueColor,
                                      fontSize: 14.0,
                                      fontWeight: FontWeight.bold,
                                    ),
                                    children: <TextSpan>[
                                      TextSpan(
                                        text:
                                            ' , ${Provider.of<PostFunctions>(context, listen: false).getImageTimePosted.toString()}',
                                        style: TextStyle(
                                          color: constantColors.lightColor
                                              .withOpacity(0.8),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        width: MediaQuery.of(context).size.width * .2,
                        height: MediaQuery.of(context).size.height * 0.05,
                        child: StreamBuilder<QuerySnapshot>(
                          stream: FirebaseFirestore.instance
                              .collection('posts')
                              .doc(documentSnapshot.data()['caption'])
                              .collection('awards')
                              .snapshots(),
                          builder: (context, snapshot) {
                            if (snapshot.connectionState ==
                                ConnectionState.waiting) {
                              return Center(
                                child: CircularProgressIndicator(),
                              );
                            } else {
                              return ListView(
                                scrollDirection: Axis.horizontal,
                                children: snapshot.data.docs
                                    .map((DocumentSnapshot documentSnapshot) {
                                  return Container(
                                    height: 30.0,
                                    width: 30.0,
                                    child: Image.network(
                                        documentSnapshot.data()['award']),
                                  );
                                }).toList(),
                              );
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Container(
                    height: MediaQuery.of(context).size.height * 0.45,
                    width: MediaQuery.of(context).size.width,
                    child: FittedBox(
                      child: Image.network(
                        documentSnapshot.data()['postimage'],
                        scale: 2,
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Padding(
                    padding: const EdgeInsets.only(left: 21.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Container(
                          width: 80.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              GestureDetector(
                                onLongPress: () {
                                  Provider.of<PostFunctions>(context, listen: false)
                                      .showLikes(
                                    context,
                                    documentSnapshot.data()['caption'],
                                  );
                                },
                                onTap: () {
                                  print('adding like');
                                  Provider.of<PostFunctions>(context, listen: false)
                                      .addLike(
                                          context,
                                          documentSnapshot.data()['caption'],
                                          Provider.of<Authenticationss>(context,
                                                  listen: false)
                                              .userUid);
                                },
                                child: Icon(
                                  FontAwesomeIcons.heart,
                                  color: constantColors.redColor,
                                  size: 22.0,
                                ),
                              ),
                              StreamBuilder<QuerySnapshot>(
                                stream: FirebaseFirestore.instance
                                    .collection('posts')
                                    .doc(documentSnapshot.data()['caption'])
                                    .collection('likes')
                                    .snapshots(),
                                builder: (context, snapshot) {
                                  if (snapshot.connectionState ==
                                      ConnectionState.waiting) {
                                    return Center(
                                      child: CircularProgressIndicator(),
                                    );
                                  } else {
                                    return Padding(
                                      padding: const EdgeInsets.only(left: 8.0),
                                      child: Text(
                                        snapshot.data.docs.length.toString(),
                                        style: TextStyle(
                                          color: constantColors.whiteColor,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    );
                                  }
                                },
                              )
                            ],
                          ),
                        ),
                        Container(
                          width: 80.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  Provider.of<PostFunctions>(context, listen: false)
                                      .shotCommentSheets(context, documentSnapshot,
                                          documentSnapshot.data()['caption']);
                                },
                                child: Icon(
                                  FontAwesomeIcons.comment,
                                  color: constantColors.blueColor,
                                  size: 22.0,
                                ),
                              ),
                              StreamBuilder<QuerySnapshot>(
                                stream: FirebaseFirestore.instance
                                    .collection('posts')
                                    .doc(documentSnapshot.data()['caption'])
                                    .collection('comments')
                                    .snapshots(),
                                builder: (context, snapshot) {
                                  if (snapshot.connectionState ==
                                      ConnectionState.waiting) {
                                    return Center(
                                      child: CircularProgressIndicator(),
                                    );
                                  } else {
                                    return Padding(
                                      padding: const EdgeInsets.only(left: 8.0),
                                      child: Text(
                                        snapshot.data.docs.length.toString(),
                                        style: TextStyle(
                                          color: constantColors.whiteColor,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    );
                                  }
                                },
                              )
                            ],
                          ),
                        ),
                        Container(
                          width: 80.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              GestureDetector(
                                onLongPress: () {
                                  Provider.of<PostFunctions>(context, listen: false)
                                      .showAwardPresenter(context,
                                          documentSnapshot.data()['caption']);
                                },
                                onTap: () {
                                  Provider.of<PostFunctions>(context, listen: false)
                                      .showReward(context,
                                          documentSnapshot.data()['caption']);
                                },
                                child: Icon(
                                  FontAwesomeIcons.award,
                                  color: constantColors.yellowColor,
                                  size: 22.0,
                                ),
                              ),
                              StreamBuilder<QuerySnapshot>(
                                stream: FirebaseFirestore.instance
                                    .collection('posts')
                                    .doc(documentSnapshot.data()['caption'])
                                    .collection('awards')
                                    .snapshots(),
                                builder: (context, snapshot) {
                                  if (snapshot.connectionState ==
                                      ConnectionState.waiting) {
                                    return Center(
                                      child: CircularProgressIndicator(),
                                    );
                                  } else {
                                    return Padding(
                                      padding: const EdgeInsets.only(left: 8.0),
                                      child: Text(
                                        snapshot.data.docs.length.toString(),
                                        style: TextStyle(
                                          color: constantColors.whiteColor,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 18.0,
                                        ),
                                      ),
                                    );
                                  }
                                },
                              )
                            ],
                          ),
                        ),
                        Spacer(),
                        Provider.of<Authenticationss>(context, listen: false)
                                    .getUserUid ==
                                documentSnapshot.data()['useruid']
                            ? IconButton(
                                icon: Icon(
                                  EvaIcons.moreVertical,
                                  color: constantColors.whiteColor,
                                ),
                                onPressed: () {
                                  Provider.of<PostFunctions>(context, listen: false)
                                      .showPostOptions(context,
                                          documentSnapshot.data()['caption']);
                                },
                              )
                            : Container(
                                height: 0.0,
                                width: 0.0,
                              ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        }).toList());
      }
    }
    
    
  • Radiant Developers
    Radiant Developers about 3 years
    i am not using setState any Where