Kingsley CA
Kingsley CA

Reputation: 11614

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?

Upvotes: 7

Views: 6446

Answers (3)

AlexPad
AlexPad

Reputation: 10879

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 
  });
 }
}

Upvotes: 1

chemamolins
chemamolins

Reputation: 20548

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)
            )
        );
      });
    }
  }

Upvotes: 7

Jacob Phillips
Jacob Phillips

Reputation: 9264

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)
    )
  );
}

Upvotes: 1

Related Questions