skip to Main Content

I am struggling with this error message: (setState() or markNeedsBuild() called during build

I am trying to continue with a Navigator.pushNamed(..) after a first async Navigation had happened.

In my code below, I do return without crash for the first Navigator.pushNamed.

But then when I do another Navigator.pushNamed(..) right after it, the app crashes!

To make it more clear: The first navigation (i.e. to payment_checkout_mobile) opens a flutter_webview. Then some payment information can be given. The webview eventually closes by Navigator.of(context).pop(). Then I land inbetween the two Navigation-calls as can be seen in the code below.

But the big question: Why is the second Navigation crashing ????

onPressed: () async {
  String checkoutSessionUrl = await saveForm();
  if (!mounted) return;
  await Navigator.pushNamed(
    context,
    '/payment_checkout_mobile',
    arguments: PaymentCheckoutArguments(checkoutSessionUrl),
  );
  if (!mounted) return;
  // The code returns here without error !!!!!
  // But the next Navigation crashes - why ?????????????
  Navigator.pushNamed(context, '/payment_success_page');
},

The error message is:

FlutterError (setState() or markNeedsBuild() called during build.
This GetBuilder<ProductController> widget cannot be marked as needing to build because the framework is already in the process of building widgets.

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution:

    You can place the follwong:

    Navigator.popUntil(context, ModalRoute.withName('/some_page_up_the_widget_hierarchy));
    

    Just make sure that /some_page_up_the_widget_hierarchy corresponds to a page that you had already rendered in your widget-tree! (otherwise the pop will not go until the widget-hierarchy-location you intend)

    Another solution that also works:

    Navigator.pushNamedAndRemoveUntil(context, '/some_page', (route) => true);
    

    This will pop all widgets in the tree and render the new /some_page.

    About the reason why the Navigator.pushNamed(context, '/payment_success_page') did not work in the first place, I still have no clue. Maybe flutter has a limit of widgets you can push ??? Or maybe somebody knows why popUntil or pushNamedAndRemoveUntil did work - but not pushNamed ??


  2. can you try this.

     Future.microtask(() => Navigator.pushNamed(context, '/payment_success_page'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search