Mudassir
Mudassir

Reputation: 806

Using Navigator.pushReplacement with variable result property

I am trying to pass a value to a Widget down the Navigator stack. Sample code:

class FirstPage extends StatefulWidget{
//...

receivedValue = await Navigator.push<String>(context, CupertinoPageRoute(
  (ctx) => SecondPage(),
));

}


class SecondPage extends StatefulWidget{
//...

receivedValue = await Navigator.pushReplacement<String,String>(context, CupertinoPageRoute(
  (ctx) => ThirdPage(),
));

}



class ThirdPage extends StatefulWidget{
//...
Navigator.pop<String>(context, outputString);
}

However the value is not passed to the first screen unless I keep the SecondPage in the stack. Reading the docs, there is a result property in pushReplacement that passes back to the previous screen in the navigator stack. In case of the replacing screen is popped.

However, the value I want to pass depends on user input in ThirdScreen. Is there a way to do it?

Upvotes: 3

Views: 704

Answers (1)

Mahdi Dahouei
Mahdi Dahouei

Reputation: 1951

Instead of pushReplacement, you can just push the third page and pop the second page after the third page is popped!

class FirstPage extends StatefulWidget{
//...

receivedValue = await Navigator.push<String>(context, CupertinoPageRoute(
  (ctx) => SecondPage(),
));

}


class SecondPage extends StatefulWidget{
//...

receivedValue = await Navigator.push<String,String>(context, CupertinoPageRoute(
  (ctx) => ThirdPage(),
));

Navigator.pop(context, receivedValue);
}



class ThirdPage extends StatefulWidget{
//...
Navigator.pop<String>(context, outputString);
}

Upvotes: 2

Related Questions