Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - 'parent != 'null' is not true' error for Navigator

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:

enter image description here

please how do i fix?

like image 234
Kingsley CA Avatar asked Sep 28 '18 16:09

Kingsley CA


3 Answers

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)
            )
        );
      });
    }
  }
like image 164
chemamolins Avatar answered Oct 31 '22 10:10

chemamolins


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)
    )
  );
}
like image 33
Jacob Phillips Avatar answered Oct 31 '22 10:10

Jacob Phillips


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 
  });
 }
}
like image 43
AlexPad Avatar answered Oct 31 '22 12:10

AlexPad