awesome_notifications_unifiedpush 1.0.0-dev.10
awesome_notifications_unifiedpush: ^1.0.0-dev.10 copied to clipboard
Android and Linux push notifications for awesome_notifications through UnifiedPush: the user's distributor, encrypted Web Push messages.
example/lib/main.dart
import 'dart:async';
import 'dart:convert';
import 'dart:math' show max;
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:awesome_notifications_unifiedpush/awesome_notifications_unifiedpush.dart';
import 'package:flutter/foundation.dart'
show TargetPlatform, defaultTargetPlatform, kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Your server's VAPID public key, when your distributor requires one:
/// `flutter run -d linux --dart-define=UNIFIEDPUSH_VAPID=<key>`.
const String vapid = String.fromEnvironment('UNIFIEDPUSH_VAPID');
const String channelKey = 'push';
const Color mainColor = Color(0xFF9D50DD);
/// Lets the (top-level) action listener open a page from anywhere.
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
/// The endpoint and the pushes, for the page.
final ValueNotifier<UnifiedPushEndpoint?> endpoint = ValueNotifier(null);
final ValueNotifier<List<String>> events = ValueNotifier([]);
void log(String event) => events.value = [event, ...events.value.take(19)];
@pragma('vm:entry-point')
Future<void> onNewEndpoint(UnifiedPushEndpoint newEndpoint) async {
endpoint.value = newEndpoint;
log('New endpoint');
}
@pragma('vm:entry-point')
Future<void> onMessage(UnifiedPushMessage message) async =>
log('Data: ${message.text}');
@pragma('vm:entry-point')
Future<void> onUnregistered() async {
endpoint.value = null;
log('Unregistered by the distributor');
}
@pragma('vm:entry-point')
Future<void> onActionReceived(ReceivedAction action) async {
log('Action on #${action.id} ${action.buttonKeyPressed}');
// Open the details page when the user taps the notification.
openDetails(action);
}
@pragma('vm:entry-point')
Future<void> onNotificationCreated(ReceivedNotification notification) async =>
log('Push shown: ${notification.title}');
/// If the app was launched by tapping a notification (killed state), the tap
/// is retrieved here, and opens the details page.
Future<void> handleInitialAction() async {
final action = await AwesomeNotifications()
.getInitialNotificationAction(removeFromActionEvents: true);
if (action != null) openDetails(action);
}
/// Opens the details page, unless the action runs without opening the app.
void openDetails(ReceivedAction action) {
switch (action.actionType) {
case ActionType.SilentAction:
case ActionType.SilentBackgroundAction:
case ActionType.DismissAction:
return;
default:
navigatorKey.currentState?.pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => NotificationPage(action: action)),
(route) => route.isFirst,
);
}
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await AwesomeNotifications()
.initialize('resource://drawable/res_notification_icon', [
NotificationChannel(
channelKey: channelKey,
channelName: 'Push notifications',
channelDescription: 'Notifications delivered through UnifiedPush',
importance: NotificationImportance.High,
),
]);
await AwesomeNotifications().setListeners(
onActionReceivedMethod: onActionReceived,
onNotificationCreatedMethod: onNotificationCreated,
);
final push = AwesomeNotificationsUnifiedPush();
final started = await push.initialize(
onNewEndpoint: onNewEndpoint,
onMessage: onMessage,
onUnregistered: onUnregistered,
vapid: vapid.isEmpty ? null : vapid,
description: 'Awesome UnifiedPush example',
);
endpoint.value = push.endpoint;
log(started ? 'Connector started' : 'UnifiedPush is not available here');
if (started) unawaited(register());
runApp(const UnifiedPushExampleApp());
}
/// Registers with the distributor already chosen, or the only one.
Future<void> register([String? distributor]) async {
final result = await AwesomeNotificationsUnifiedPush()
.register(distributor: distributor);
log(result.succeeded
? 'Registered with ${result.distributor}'
: 'Not registered: ${result.failure!.name}');
}
/// Only Android, iOS and macOS have resources (the app's icon).
bool get hasResources =>
!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS);
/// A local notification on the push channel: tap it to try the details page
/// without sending a push.
Future<void> createTestNotification() async {
if (!await AwesomeNotifications().isNotificationAllowed()) {
log('Allow notifications first');
return;
}
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: channelKey,
title: 'Local test',
body: 'Tap it to open the details page, as a push does.',
largeIcon: hasResources ? 'resource://drawable/res_app_icon' : null,
payload: {'uuid': 'uuid-test'},
),
);
}
class UnifiedPushExampleApp extends StatelessWidget {
const UnifiedPushExampleApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Awesome UnifiedPush',
navigatorKey: navigatorKey,
theme: ThemeData(colorSchemeSeed: mainColor, useMaterial3: true),
home: const HomePage(),
);
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
bool _allowed = false;
List<String> _distributors = const [];
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
// Handle a notification tap that launched the app from a killed state.
handleInitialAction();
_refreshPermission();
_refresh();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
// The user may allow notifications in the settings, outside of the app.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) _refreshPermission();
}
Future<void> _refreshPermission() async {
final allowed = await AwesomeNotifications().isNotificationAllowed();
if (mounted) setState(() => _allowed = allowed);
}
Future<void> _requestPermission() async {
final allowed =
await AwesomeNotifications().requestPermissionToSendNotifications();
if (mounted) setState(() => _allowed = allowed);
}
Future<void> _refresh() async {
final list = await AwesomeNotificationsUnifiedPush().distributors();
if (mounted) setState(() => _distributors = list);
}
@override
Widget build(BuildContext context) {
final push = AwesomeNotificationsUnifiedPush();
return Scaffold(
appBar: AppBar(
backgroundColor: mainColor,
foregroundColor: Colors.white,
title: const Text('Linux push (UnifiedPush)'),
),
body: ListView(
padding: const EdgeInsets.symmetric(horizontal: 24),
children: [
const _SectionDivisor('Permission'),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
_allowed ? Icons.notifications_active : Icons.notifications_off,
color: mainColor,
),
const SizedBox(width: 8),
Text(
_allowed
? 'Notifications are allowed.'
: 'Notifications are not allowed yet.',
),
],
),
const SizedBox(height: 8),
_WideButton(
'Allow notifications',
enabled: !_allowed,
backgroundColor: mainColor,
labelColor: Colors.white,
onPressed: _requestPermission,
),
const _SectionDivisor('UnifiedPush'),
ValueListenableBuilder<UnifiedPushEndpoint?>(
valueListenable: endpoint,
builder: (context, value, _) => _StatusCard(
title: !push.isInitialized
? 'UnifiedPush is not available here'
: value != null
? 'This app receives pushes through ${push.distributor ?? 'its distributor'}'
: _distributors.isEmpty
? 'Install a distributor to receive pushes'
: 'Choose a distributor to register with',
chips: {
'Connector': push.isInitialized,
'Distributor': push.distributor != null,
'Endpoint': value != null,
},
children: [
if (push.isInitialized && _distributors.isEmpty)
const _CardText(
'None installed: install one (KUnifiedPush on KDE '
'Plasma, ntfy on Android).',
),
if (_distributors.isNotEmpty)
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final name in _distributors)
FilledButton.tonalIcon(
icon: Icon(
name == push.distributor
? Icons.radio_button_checked
: Icons.radio_button_off,
),
label: Text(name),
onPressed: () async {
await register(name);
await _refresh();
},
),
],
),
if (value != null)
_CardText(
const JsonEncoder.withIndent(' ')
.convert(value.toSubscription()),
),
],
),
),
const _SectionDivisor('Subscription'),
_WideButton(
'Copy the subscription',
onPressed: () {
final value = endpoint.value;
if (value == null) return;
Clipboard.setData(
ClipboardData(text: jsonEncode(value.toSubscription())));
},
),
_WideButton(
'Start the app for pushes',
onPressed: () async => log(await push.enableAppActivation()
? 'D-Bus activation enabled'
: 'Could not write the D-Bus service file'),
),
_WideButton(
'Unregister',
onPressed: () async {
await push.unregister();
endpoint.value = null;
log('Unregistered');
await _refresh();
},
),
const _SectionDivisor('Local test'),
Text(
'A local notification on the push channel: tap it to see the '
'details page without sending a push.',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 8),
_WideButton('Test notification', onPressed: createTestNotification),
_WideButton(
'Dismiss all',
onPressed: AwesomeNotifications().dismissAllNotifications,
),
const _SectionDivisor('Events'),
ValueListenableBuilder<List<String>>(
valueListenable: events,
builder: (context, list, _) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final event in list)
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Text(event),
),
],
),
),
const SizedBox(height: 24),
],
),
);
}
}
/// The push state: a gradient card with a chip per state, the values to copy
/// and what can be requested.
class _StatusCard extends StatelessWidget {
final String title;
final Map<String, bool> chips;
final List<Widget> children;
const _StatusCard({
required this.title,
required this.chips,
this.children = const [],
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
Widget chip(String label, bool on) => Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: on ? 0.24 : 0.08),
borderRadius: BorderRadius.circular(16),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
on ? Icons.check_circle : Icons.remove_circle_outline,
size: 16,
color: Colors.white.withValues(alpha: on ? 1 : 0.6),
),
const SizedBox(width: 4),
Text(
label,
style: theme.textTheme.labelMedium?.copyWith(
color: Colors.white.withValues(alpha: on ? 1 : 0.6),
),
),
],
),
);
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
gradient: LinearGradient(
colors: [mainColor, Color.lerp(mainColor, Colors.black, 0.4)!],
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: theme.textTheme.titleSmall?.copyWith(color: Colors.white),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final entry in chips.entries) chip(entry.key, entry.value),
],
),
for (final child in children) ...[
const SizedBox(height: 12),
child,
],
],
),
);
}
}
/// A value of the status card the user can select and copy.
class _CardText extends StatelessWidget {
final String text;
const _CardText(this.text);
@override
Widget build(BuildContext context) {
return SelectableText(
text,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white,
),
);
}
}
/// A section title between two divider lines.
class _SectionDivisor extends StatelessWidget {
final String title;
const _SectionDivisor(this.title);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Row(
children: [
const Expanded(child: Divider(thickness: 1)),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
title,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
),
),
const Expanded(child: Divider(thickness: 1)),
],
),
);
}
}
/// A full-width button matching the example's style.
class _WideButton extends StatelessWidget {
final String label;
final Color? backgroundColor;
final Color? labelColor;
final bool enabled;
final VoidCallback? onPressed;
const _WideButton(
this.label, {
this.backgroundColor,
this.labelColor,
this.enabled = true,
this.onPressed,
});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 4),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor ?? Colors.grey.shade200,
padding: const EdgeInsets.symmetric(vertical: 16),
),
onPressed: enabled ? onPressed : null,
child: Text(
label,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
color: enabled
? (labelColor ?? Colors.black87)
: Colors.grey.shade500,
),
),
),
);
}
}
/// *********************************************
/// NOTIFICATION DETAILS PAGE
/// *********************************************
///
/// Opened when a notification is tapped, as in the original complete example: the
/// big picture faded at the top, the large icon in a yellow ring, the title with
/// the date, the body and, at the base, the payload and the received action.
class NotificationPage extends StatelessWidget {
final ReceivedAction action;
const NotificationPage({super.key, required this.action});
@override
Widget build(BuildContext context) {
final mediaQueryData = MediaQuery.of(context);
final themeData = Theme.of(context);
ImageProvider? largeIcon = action.largeIconImage;
final ImageProvider? bigPicture = action.bigPictureImage;
if (largeIcon == bigPicture) largeIcon = null;
final double maxSize = max(
mediaQueryData.size.width,
mediaQueryData.size.height,
);
final DateTime? date = action.displayedDate ?? action.createdDate;
final String? dateText = date == null
? null
: AwesomeDateUtils.parseDateToString(
// The plugin's dates hold UTC time.
AwesomeDateUtils.utcToLocal(date),
format: 'dd/MM/yyyy HH:mm',
);
final Map<String, String?> payload = action.payload ?? {};
final TextStyle? onSurface = themeData.textTheme.bodyMedium?.copyWith(
color: themeData.colorScheme.onSurface,
);
return Scaffold(
body: AnnotatedRegion<SystemUiOverlayStyle>(
value: bigPicture == null
? SystemUiOverlayStyle.dark
: SystemUiOverlayStyle.light,
child: Stack(
children: <Widget>[
ListView(
padding: EdgeInsets.zero,
children: <Widget>[
Stack(
children: <Widget>[
// The big picture fading out, or a soft shade.
if (bigPicture == null)
Container(
height: mediaQueryData.padding.top + 120,
width: mediaQueryData.size.width,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.black12, Colors.transparent],
),
),
)
else
SizedBox(
height: maxSize * 0.4 + mediaQueryData.padding.top,
width: mediaQueryData.size.width,
child: ShaderMask(
shaderCallback: (rect) =>
const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black,
Colors.black,
Colors.transparent,
],
stops: [0.0, 0.75, 0.98],
).createShader(
Rect.fromLTRB(0, 0, rect.width, rect.height),
),
blendMode: BlendMode.dstIn,
child: Image(
image: bigPicture,
width: mediaQueryData.size.width,
// 4 pixels short: no seam under the mask while
// the page slides.
height:
maxSize * 0.4 + mediaQueryData.padding.top - 4,
fit: BoxFit.cover,
errorBuilder: (context, error, stack) =>
const SizedBox(),
),
),
),
// The large icon in its yellow ring.
if (largeIcon != null)
Positioned(
left: bigPicture == null
? mediaQueryData.size.width / 2 - maxSize * 0.08
: 20,
top:
mediaQueryData.padding.top +
(bigPicture == null ? 32 : maxSize * 0.25),
child: CircleAvatar(
radius: maxSize * 0.08,
backgroundColor: const Color(0xffFDCF09),
child: CircleAvatar(
radius: maxSize * 0.075,
backgroundColor: Colors.white,
backgroundImage: largeIcon,
),
),
),
// The title and when it was shown.
Container(
width: mediaQueryData.size.width,
padding: EdgeInsets.only(
left: 20,
right: 20,
bottom: 12,
top: bigPicture == null
? (largeIcon == null
? mediaQueryData.padding.top + 72
: mediaQueryData.padding.top +
maxSize * 0.16 +
52)
: maxSize * 0.48,
),
child: RichText(
text: TextSpan(
children: [
TextSpan(
text:
action.titleWithoutHtml ??
(action.bodyWithoutHtml ?? ''),
style: TextStyle(
fontSize: (action.title?.isEmpty ?? true)
? 24
: 32,
height: 1.2,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
if (dateText != null)
TextSpan(
text: '\n$dateText',
style: themeData.textTheme.titleSmall?.copyWith(
color: Colors.black26,
),
),
],
),
),
),
],
),
// The body, when the title took the top.
if (!(action.title?.isEmpty ?? true) &&
!(action.body?.isEmpty ?? true))
Padding(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
child: Text(
action.bodyWithoutHtml ?? '',
style: themeData.textTheme.bodyMedium,
),
),
// The payload and everything the action received.
Container(
width: mediaQueryData.size.width,
color: themeData.disabledColor,
padding: const EdgeInsets.fromLTRB(20, 32, 20, 32),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
if (action.buttonKeyPressed.isNotEmpty) ...[
Text(
'Button pressed:',
style: themeData.textTheme.titleMedium?.copyWith(
color: themeData.colorScheme.onSurface,
),
),
const SizedBox(height: 12),
Text(
action.buttonKeyInput.isEmpty
? action.buttonKeyPressed
: '${action.buttonKeyPressed}: '
'${action.buttonKeyInput}',
style: onSurface,
),
const SizedBox(height: 24),
],
Text(
'Payload:',
style: themeData.textTheme.titleMedium?.copyWith(
color: themeData.colorScheme.onSurface,
),
),
const SizedBox(height: 12),
Text(
payload.isEmpty
? '(empty)'
: payload.entries
.map((e) => '${e.key}: ${e.value}')
.join('\n'),
style: onSurface,
),
const SizedBox(height: 24),
Text(
'ReceivedAction details:',
style: themeData.textTheme.titleMedium?.copyWith(
color: themeData.colorScheme.onSurface,
),
),
const SizedBox(height: 12),
Text(
action.toString(),
style: themeData.textTheme.bodySmall?.copyWith(
color: themeData.colorScheme.onSurface,
fontFamily: 'monospace',
),
),
],
),
),
],
),
// The rounded back button.
Positioned(
top: mediaQueryData.padding.top + 12,
left: 12,
child: Container(
height: 40,
alignment: Alignment.center,
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.black26,
spreadRadius: 4,
blurRadius: 8,
offset: Offset(0, 4),
),
],
),
child: IconButton(
alignment: Alignment.center,
icon: const Icon(Icons.chevron_left),
onPressed: () => Navigator.pop(context),
),
),
),
],
),
),
);
}
}