Skip to content

Instantly share code, notes, and snippets.

@Amir-P
Created November 21, 2021 12:20
Show Gist options
  • Save Amir-P/f1efd09767712c1a42b8cf45b96ee39a to your computer and use it in GitHub Desktop.
Save Amir-P/f1efd09767712c1a42b8cf45b96ee39a to your computer and use it in GitHub Desktop.
Build widgets in response to notifications (Flutter)
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