Skip to content

Instantly share code, notes, and snippets.

@Amir-P
Created April 20, 2022 13:37
Show Gist options
  • Save Amir-P/25d762735296077aca481209f586ed4d to your computer and use it in GitHub Desktop.
Save Amir-P/25d762735296077aca481209f586ed4d to your computer and use it in GitHub Desktop.
A `BlocConsumer` like widget for notifications (uses `NotificationBuilder` from `flutter/widgets`)
import 'package:flutter/widgets.dart';
typedef NotificationBuilderCallback<T extends Notification> = Widget Function(
BuildContext context, T? notification);
typedef NotificationCondition<T extends Notification> = bool Function(
T notification);
class NotificationConsumer<T extends Notification> extends StatefulWidget {
final NotificationBuilderCallback<T> builder;
final NotificationListenerCallback<T>? onNotification;
final NotificationCondition? when;
const NotificationConsumer({
Key? key,
required this.builder,
this.onNotification,
this.when,
}) : super(key: key);
@override
_NotificationConsumerState createState() => _NotificationConsumerState<T>();
}
class _NotificationConsumerState<T extends Notification>
extends State<NotificationConsumer<T>> {
T? _notification;
@override
Widget build(BuildContext context) => NotificationListener(
child: widget.builder(context, _notification),
onNotification: _onNotification,
);
bool _onNotification(T notification) {
if (widget.when?.call(notification) ?? true) {
setState(() => _notification = notification);
return widget.onNotification?.call(notification) == true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment