I wrote a checks for something and then navigates to the next page if the condition is true. However i keep getting an error whenever that condition returns true and i'm meant to navigate
class BuyTickets extends StatefulWidget {
@override
_BuyTicketsState createState() => new _BuyTicketsState();
}
class _BuyTicketsState extends State<BuyTickets> {
@override
void initState(){
...
if(condition){
//Skip to next page
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SelectSeat(data: widget.data)
)
);
}
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
...
)
}
Error:
please how do i fix?
It complains that it can't find the parent because the render object associated to the widget is not fully created and mounted.
In all these cases you need to delay the calls to the moment the render object is mounted. One way is executing it after the first frame.
@override
void initState() {
super.initState();
if(condition){
WidgetsBinding.instance.addPostFrameCallback((_) async {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SelectSeat(data: widget.data)
)
);
});
}
}
You cannot navigate during lifecycle functions like initState()
or build()
. You could put your login in an async
function or use Future.delayed
or something similar.
@override
void initState(){
super.initState();
...
if(condition){
skipToNextPage();
}
}
void skipToNextPage() async {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SelectSeat(data: widget.data)
)
);
}
I had written a comment long ago in which I recommended a delay of one second to start operations, it's actually wrong. What we need to do is initialize the variables and for any operation dependent on another, we must wait for the graphics to be created by simply entering:
@override
void initState() {
super.initState();
//here you can init your variables
WidgetsBinding.instance.addPostFrameCallback((_) async {
//All dynamic operations that will impact on graphics
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With