awesome_notifications_airship 1.0.0-dev.10
awesome_notifications_airship: ^1.0.0-dev.10 copied to clipboard
Airship pushes built and shown by awesome_notifications (layouts, channels, buttons, events), next to the official airship_flutter plugin.
example/lib/main.dart
import 'dart:async';
import 'dart:io';
import 'dart:math' show max;
import 'package:airship_flutter/airship_flutter.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:awesome_notifications_airship/awesome_notifications_airship.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart' show SystemUiOverlayStyle;
import 'package:material_ui/material_ui.dart';
/// Your Airship app's key and secret:
/// `flutter run --dart-define=AIRSHIP_APP_KEY=... --dart-define=AIRSHIP_APP_SECRET=...`
const String appKey = String.fromEnvironment('AIRSHIP_APP_KEY');
const String appSecret = String.fromEnvironment('AIRSHIP_APP_SECRET');
const String channelKey = 'airship';
const Color mainColor = Color(0xFF9D50DD);
/// Whether Airship took off, for the page.
bool airshipFlying = false;
/// The events of both plugins, newest first, for the page.
final ValueNotifier<List<String>> events = ValueNotifier([]);
void log(String event) => events.value = [event, ...events.value.take(39)];
/// Opens the details page of a tapped notification.
void openNotificationPage(ReceivedAction action) {
AirshipExampleApp.navigatorKey.currentState?.pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => NotificationPage(action: action)),
(route) => route.isFirst,
);
}
// The core's events: every Airship push shown by the core reports them, as a
// local notification does.
@pragma('vm:entry-point')
Future<void> onNotificationCreated(ReceivedNotification notification) async =>
log('Core: created #${notification.id} ${notification.title ?? ''}');
@pragma('vm:entry-point')
Future<void> onNotificationDisplayed(ReceivedNotification notification) async =>
log('Core: displayed #${notification.id}');
@pragma('vm:entry-point')
Future<void> onActionReceived(ReceivedAction action) async {
log(
'Core: action on #${action.id} ${action.buttonKeyPressed} '
'(Airship push: ${AwesomeNotificationsAirship.isAirshipNotification(action)})',
);
openNotificationPage(action);
}
@pragma('vm:entry-point')
Future<void> onDismissActionReceived(ReceivedAction action) async =>
log('Core: dismissed #${action.id}');
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await AwesomeNotifications()
.initialize('resource://drawable/res_notification_icon', [
NotificationChannel(
channelKey: channelKey,
channelName: 'Airship pushes',
channelDescription: 'Notifications sent through Airship',
importance: NotificationImportance.High,
defaultColor: mainColor,
),
]);
await AwesomeNotifications().setListeners(
onActionReceivedMethod: onActionReceived,
onNotificationCreatedMethod: onNotificationCreated,
onNotificationDisplayedMethod: onNotificationDisplayed,
onDismissActionReceivedMethod: onDismissActionReceived,
);
// Airship's own events keep firing for the pushes the core shows.
Airship.push.onPushReceived.listen(
(event) => log('Airship: push received ${event.pushPayload.alert ?? ''}'),
);
Airship.push.onNotificationResponse.listen(
(event) => log(
'Airship: response ${event.actionId ?? 'tap'} '
'(foreground: ${event.isForeground})',
),
);
Airship.onDeepLink.listen(
(event) => log('Airship: deep link ${event.deepLink}'),
);
if (appKey.isEmpty || appSecret.isEmpty) {
log('Pass AIRSHIP_APP_KEY and AIRSHIP_APP_SECRET with --dart-define');
} else {
final flying = await Airship.takeOff(
AirshipConfig(
defaultEnvironment: ConfigEnvironment(
appKey: appKey,
appSecret: appSecret,
),
),
);
airshipFlying = flying;
log(flying ? 'Airship took off' : 'Airship did not take off');
if (flying) await Airship.push.setUserNotificationsEnabled(true);
}
runApp(const AirshipExampleApp());
}
/// A local notification through the core, to try the details page without a
/// push. Only Android, iOS and macOS have the app icon as a resource.
Future<void> createTestNotification() async {
if (!await AwesomeNotifications().isNotificationAllowed() &&
!await AwesomeNotifications().requestPermissionToSendNotifications()) {
return;
}
final hasResources =
!kIsWeb && (Platform.isAndroid || Platform.isIOS || Platform.isMacOS);
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: channelKey,
title: 'Local test',
body: 'A local notification on the Airship channel. Tap it.',
largeIcon: hasResources ? 'resource://drawable/res_app_icon' : null,
payload: {'source': 'local test'},
),
);
}
class AirshipExampleApp extends StatelessWidget {
const AirshipExampleApp({super.key});
// Lets the (top-level) action listener open a page from anywhere.
static final GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>();
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Awesome Airship',
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;
String? _channelId;
bool _active = false;
bool _userNotificationsEnabled = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
unawaited(_handleInitialAction());
unawaited(_refresh());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) unawaited(_refresh());
}
/// If the app was launched by tapping a notification, opens its page.
Future<void> _handleInitialAction() async {
final action = await AwesomeNotifications().getInitialNotificationAction(
removeFromActionEvents: true,
);
if (action != null) openNotificationPage(action);
}
Future<void> _refresh() async {
final allowed = await AwesomeNotifications().isNotificationAllowed();
final channelId = await Airship.channel.identifier;
final active = await AwesomeNotificationsAirship().isActive();
final userNotificationsEnabled = airshipFlying
? await Airship.push.isUserNotificationsEnabled
: false;
if (mounted) {
setState(() {
_allowed = allowed;
_channelId = channelId;
_active = active;
_userNotificationsEnabled = userNotificationsEnabled;
});
}
}
Future<void> _requestPermission() async {
await AwesomeNotifications().requestPermissionToSendNotifications();
await _refresh();
}
Future<void> _enableUserNotifications() async {
await Airship.push.setUserNotificationsEnabled(true);
await _refresh();
}
@override
Widget build(BuildContext context) {
final white = Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: Colors.white);
return Scaffold(
appBar: AppBar(
backgroundColor: mainColor,
foregroundColor: Colors.white,
title: const Text('Airship'),
actions: [
IconButton(icon: const Icon(Icons.refresh), onPressed: _refresh),
],
),
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('Airship'),
_StatusCard(
title: _active
? 'Airship pushes are shown by awesome_notifications'
: 'Airship is not showing its pushes through the core yet',
chips: {
'App key': appKey.isNotEmpty && appSecret.isNotEmpty,
'Took off': airshipFlying,
'User notifications': _userNotificationsEnabled,
'Channel': _channelId != null,
'Shown by the core': _active,
},
children: [
if (airshipFlying && !_userNotificationsEnabled) ...[
const SizedBox(height: 12),
FilledButton.tonal(
onPressed: _enableUserNotifications,
child: const Text('Enable Airship notifications'),
),
],
const SizedBox(height: 12),
SelectableText(
'Channel: ${_channelId ?? 'No channel yet'}',
style: white?.copyWith(fontFamily: 'monospace'),
),
],
),
const _SectionDivisor('Local notifications'),
const _WideButton(
'Local test notification',
onPressed: createTestNotification,
),
_WideButton(
'Dismiss all',
onPressed: AwesomeNotifications().dismissAllNotifications,
),
const _SectionDivisor('Events'),
const _EventList(emptyText: 'Send a push from Airship.'),
const SizedBox(height: 24),
],
),
);
}
}
/// The state of the vendor SDK, as a gradient card with chips.
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),
],
),
...children,
],
),
);
}
}
/// The events of both plugins, newest first.
class _EventList extends StatelessWidget {
final String emptyText;
const _EventList({required this.emptyText});
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<List<String>>(
valueListenable: events,
builder: (context, list, _) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (list.isEmpty) Text(emptyText),
for (final event in list)
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Text(event),
),
],
),
);
}
}
/// 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),
),
),
),
],
),
),
);
}
}