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()),
);
}
3
Answers
You can use the ternary operator to achieve it.
In this case if
trip
is not null it will render the widget :And if the
trip
is null it will displaySizedBox.shrink()
, and the previous widget won’t be rendered, removing it out of the tree.To automatically remove the
ManageBookingPage
widget from the navigation stack when thetrip
becomesnull
, you can use aValueNotifier
and listen for changes totrip
. Whentrip
becomesnull
, you can useNavigator.pop()
to remove the widget from the stack.Example code:
Explanation
ValueNotifier<BusTrip?> tripNotifier
: AValueNotifier
is used to observe changes intrip
.addListener(_checkTrip)
: Adds a listener totripNotifier
that triggers_checkTrip
whenevertrip
changes._checkTrip
: Checks iftrip
isnull
. If so, it callsNavigator.of(context).pop()
to remove the widget from the navigation stack.dispose()
: Removes the listener when the widget is disposed to prevent memory leaks.I tried to add
trip
management in this page and add a listener when thetrip
value has been change to null the page will be poped.