Reputation: 518
I have a Flutter package the shows a notification to the user pushing a new route on top of the stack. I would like to keep my notification's route on top if the user presses the back button on Android or uses a back gesture on IOS and pop the previous route instead.
Is there a way to do that?
Upvotes: 0
Views: 356
Reputation: 8427
Notification
:
class Notification {
static OverlayEntry _overlayEntry;
static void show({
@required NotificationWidget notification,
@required BuildContext context,
}) {
final OverlayState overlay =
context.rootAncestorStateOfType(const TypeMatcher<OverlayState>());
_overlayEntry = _buildOverlayEntry(notification);
overlay.insert(_overlayEntry);
}
static OverlayEntry _buildOverlayEntry(NotificationWidget notification) {
return OverlayEntry(
builder: (_) {
return Positioned(
left: 8,
top: 32,
right: 8,
child: notification,
);
},
);
}
static void hide() {
if (_overlayEntry != null) {
_overlayEntry.remove();
_overlayEntry = null;
}
}
}
NotificationWidget
:
class NotificationWidget extends StatelessWidget {
final String title;
final String description;
NotificationWidget({
Key key,
@required this.title,
@required this.description,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Card(
elevation: 4,
child: Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
Text(
title,
style: Theme.of(context).textTheme.title,
),
SizedBox(height: 4),
Text(
description,
style: Theme.of(context).textTheme.body1,
),
],
),
),
);
}
}
To show or hide, the user can write:
void showNotification() {
Notification.show(
context: context,
notification: NotificationWidget(
title: 'Notification title',
description: 'Notification description',
),
);
}
void hideNotification() => Notification.hide();
Notification
and NotificationWidget
could be a single class, but I think it's better this way. Also, the user can easily create his/hers custom notification by overriding NotificationWidget
.
Upvotes: 1