user1187968
user1187968

Reputation: 7996

Calling Provider custom method inside setState() caused error: or markNeedsBuild() called during build

I have a flutter widget state class as follow. I call Provider.of<AppData>(context, listen: false).recalculateCart(); inside initState().

When I run, I'm getting the error said setState() or markNeedsBuild() called during build.

How should I resolve those?

class CartPageState extends State<CartPage> {
  final TextEditingController _couponController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Provider.of<AppData>(context, listen: false).recalculateCart();
  }


  @override
  Widget build(BuildContext context) {

    if (Provider.of<AppData>(context, listen: false).selectedStoreId == null){
      Provider.of<AppData>(context, listen: false).setPageAfterStoreSelection('cart');
      return ChooseStorePage(title: 'Choose Store to Continue');
    }
    ...
}

Also, here is the recalculateCart() function:

  void recalculateCart() {
   notifyListeners();
  }

Upvotes: 0

Views: 180

Answers (1)

Luis Miguel Mantilla
Luis Miguel Mantilla

Reputation: 1748

The problem is that there is a re build when the actual build hasn't finished yet, so you can put you function inside a addPostFrameCallback method to execute the function after the first build has finished, try the next:

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
       Provider.of<AppData>(context, listen: false).recalculateCart();
    });
  }

Upvotes: 1

Related Questions