Jay Surya
Jay Surya

Reputation: 570

Flutter pushReplacementNamed().then() does not trigger

I am following this udemy course(https://www.udemy.com/learn-flutter-dart-to-build-ios-android-apps) on flutter, and using scoped_model for state management. I want to edit a product from list of products. For that I set the product id as a flag - selectedProductId in scoped model. When submitting, I want to navigate away and set this selectedProductId to null.

//method to edit product    
editProduct(productId, newValues);
Navigator.pushReplacementNamed(context, '/productsPage').then((_){
   debugger();
setSelectedProductId(null);
}).catchError((err){print(err);});

The debugger is never hit. and there is no error either.

I tried using async await and still no use.

editProduct(editableProductId, _formData);
await Navigator.pushReplacementNamed(context, '/productsPage').catchError((err){print(err);});
debugger();
setSelectedProductId(null);

the page is navigated to the given route, but the line after, is never executed. I even tried using pushNamed instead of pushReplacementNamed.

I know that pushReplacementNamed returns a future, so .then() must be called, but doesn't seem to happen, am I missing something? Are there any other factors or situations I should know?

Upvotes: 0

Views: 3931

Answers (3)

Mostafijur Rahman
Mostafijur Rahman

Reputation: 221

Just simply add the below code:

Navigator.of(context).pushNamedAndRemoveUntil('/productsPage', (route) => false);

Upvotes: -1

User
User

Reputation: 94

Create a Custom Future Object might solve the Problem

Navigator.pushReplacementNamed(context, '/product');
Future.delayed(Duration(milliseconds: 700)).then((_)=>resetSelectedProduct(null));

Upvotes: 0

Shababb Karim
Shababb Karim

Reputation: 3733

You have got the concept wrong. Suppose you have Activity A and Activity B. From Activity A you navigate from A to B. Now the then from A is called only if Navigator.pop(context) is called from B. If pop is not called from B then the then callback is never called.

In your case you are calling Navigator.pushReplacementNamed from A, so what you are doing is REPLACING A with B. So, even if you pop from B then Activity A is not available anymore, so the then callback will never be called.

You can refer to this section in the flutter cookbook for further info.

As for executing the code in then callback you should move it to dispose method of the Widget, you will see it getting called but I don't see the point in doing this because the Widget is getting destroyed and no point in setting its instance property as null.

Upvotes: 6

Related Questions