Search code examples
flutterdart

How to pop a widget when the argument becomes null in a stateful widget?


Let's say the ManageBookingPage widget requires an object called trip as an argument. But this widget has the ability to modify the received argument such that it becomes null (trip = null).

I want this widget to pop out of the tree automatically when trip becomes null. What would be the best approach in achieving this?

class ManageBookingPage extends StatefulWidget {
  const ManageBookingPage({
    super.key,
    required this.trip,
  });

  final BusTrip trip;

  @override
  State<ManageBookingPage> createState() => _ManageBookingPageState();
}

class _ManageBookingPageState extends State<ManageBookingPage> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: Text(widget.trip.date.toString()),
    );
}

Solution

  • Solution

    The solution I settled on:

    • Make the parameter trip nullable.
    • Add a null check in a conditional statement inside the build method and pop the widget out of tree if the argument becomes null.

    class ManageBookingPage extends StatefulWidget {
      const ManageBookingPage({
        super.key,
        required this.trip,
      });
    
      final BusTrip? trip;
    
      @override
      State<ManageBookingPage> createState() => _ManageBookingPageState();
    }
    
    class _ManageBookingPageState extends State<ManageBookingPage> {
      @override
      Widget build(BuildContext context) {
        BusTrip? widgetTrip = widget.trip;
    
        if (widgetTrip != null) {
          String date = widget.trip.date.toString(); 
          return SizedBox(
           child: Text(date),
          );
        } else {
          return Builder(
            builder: (context) {
              Navigator.pop(context);
              return const SizedBox();
            },
          );
        }
      }
    }