awesome_notifications_schedules 1.0.0-dev
awesome_notifications_schedules: ^1.0.0-dev copied to clipboard
Notification scheduling (interval/calendar) decorator for awesome_notifications.
example/lib/main.dart
// Minimal, self-contained Awesome Notifications *scheduling* example.
//
// Copy this file into your app's `lib/main.dart`, add `awesome_notifications`
// and `awesome_notifications_schedules` to your pubspec.yaml and run. It covers
// the essentials: initialize, request permission, schedule a notification (by
// time interval or calendar date, one-shot or repeating), preview the next fire
// date, list/cancel schedules, and open a details page when the user taps a
// delivered notification.
//
// Scheduling is attached to a normal `createNotification` call through the
// `extensions:` slot — there is no separate scheduling entry point. The native
// scheduling decorator (installed automatically by this package) intercepts the
// build and registers the delayed delivery; the core stays scheduling-agnostic.
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:awesome_notifications_schedules/awesome_notifications_schedules.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show SystemUiOverlayStyle;
const String channelKey = 'scheduled_channel';
const Color mainColor = Color(0xFF9D50DD);
void main() {
WidgetsFlutterBinding.ensureInitialized();
// 1. Initialize with at least one channel. Keep the Future so the UI can wait
// for it: creating a notification before initialize completes can fail.
final Future<bool> awesomeNotificationsInitialization =
NotificationController.initializeLocalNotifications();
runApp(
MyApp(
awesomeNotificationsInitialization: awesomeNotificationsInitialization,
),
);
}
/// *********************************************
/// NOTIFICATION CONTROLLER
/// *********************************************
///
/// Keeps all the Awesome Notifications calls in one place so the widgets stay
/// focused on the UI.
class NotificationController {
// The scheduling decorator's management API (list / cancel / next-date).
static final AwesomeNotificationsSchedules _schedules =
AwesomeNotificationsSchedules();
// Lets the (static) action listener open a page from anywhere.
static final GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>();
// Lets the (static) event listeners show snackbars from anywhere.
static final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
/// *********************************************
/// INITIALIZATION
/// *********************************************
static Future<bool> initializeLocalNotifications() {
return AwesomeNotifications().initialize(
// The status bar icon: a white glyph on transparent (Android draws only
// its alpha). Without it, the full-color app icon shows as a square.
'resource://drawable/res_notification_icon',
[
NotificationChannel(
channelKey: channelKey,
channelName: 'Scheduled notifications',
channelDescription: 'Notifications delivered on a schedule',
defaultColor: mainColor,
ledColor: mainColor,
importance: NotificationImportance.High,
),
],
debug: true,
);
}
/// *********************************************
/// EVENT LISTENERS
/// *********************************************
/// Notification events are only delivered after this is called.
static Future<void> startListeningNotificationEvents() {
return AwesomeNotifications().setListeners(
onActionReceivedMethod: onActionReceivedMethod,
onNotificationCreatedMethod: onNotificationCreatedMethod,
onNotificationDisplayedMethod: onNotificationDisplayedMethod,
onDismissActionReceivedMethod: onDismissActionReceivedMethod,
);
}
/// If the app was launched by tapping a notification (killed state), the tap
/// is not delivered to [onActionReceivedMethod] (no listener existed yet):
/// it is retrieved here instead, and opens the details page.
static Future<void> handleInitialAction() async {
final ReceivedAction? action = await AwesomeNotifications()
.getInitialNotificationAction(removeFromActionEvents: true);
debugPrint('getInitialNotificationAction -> '
'${action == null ? 'null (no launch action)' : 'id=${action.id} '
'channelKey=${action.channelKey} '
'buttonKeyPressed=${action.buttonKeyPressed}'}');
if (action == null) return;
navigatorKey.currentState?.pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => NotificationPage(action: action)),
(route) => route.isFirst,
);
}
// Listeners must be static / top-level and annotated with vm:entry-point.
@pragma('vm:entry-point')
static Future<void> onNotificationCreatedMethod(
ReceivedNotification received) async {
_showEventSnackBar('Created #${received.id}', Colors.green);
}
@pragma('vm:entry-point')
static Future<void> onNotificationDisplayedMethod(
ReceivedNotification received) async {
_showEventSnackBar('Displayed #${received.id}', Colors.blue);
}
@pragma('vm:entry-point')
static Future<void> onActionReceivedMethod(ReceivedAction action) async {
_showEventSnackBar('Action #${action.id}', Colors.orange);
// Open the details page when the user taps the notification.
navigatorKey.currentState?.pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => NotificationPage(action: action)),
(route) => route.isFirst,
);
}
@pragma('vm:entry-point')
static Future<void> onDismissActionReceivedMethod(
ReceivedAction action) async {
_showEventSnackBar('Dismissed #${action.id}', Colors.red);
}
// Shows a notification event as a colored snackbar.
static void _showEventSnackBar(String message, Color color) {
scaffoldMessengerKey.currentState
?..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: color,
behavior: SnackBarBehavior.floating,
duration: const Duration(seconds: 2),
),
);
}
/// *********************************************
/// REQUESTING PERMISSIONS
/// *********************************************
///
/// Shows a short rationale before the system permission prompt.
static Future<bool> requestPermission(BuildContext context) async {
final userAuthorized = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Get Notified!'),
content: const Text(
'Allow Awesome Notifications to send you beautiful notifications!',
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('Deny', style: TextStyle(color: Colors.red)),
),
TextButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('Allow', style: TextStyle(color: mainColor)),
),
],
),
);
if (userAuthorized != true) return false;
return AwesomeNotifications().requestPermissionToSendNotifications();
}
/// *********************************************
/// SCHEDULE — TIME INTERVAL
/// *********************************************
// Fires once, a fixed number of seconds after being scheduled.
static Future<void> scheduleInterval() {
return AwesomeNotifications().createNotification(
content: NotificationContent(
id: 101,
channelKey: channelKey,
title: 'Interval schedule',
body: 'Delivered ~10 seconds after scheduling.',
payload: {'uuid': 'interval-once'},
),
extensions: [
NotificationInterval(
interval: const Duration(seconds: 10),
allowWhileIdle: true,
),
],
);
}
// Repeats every minute (60s is the platform minimum for a repeating interval).
static Future<void> scheduleIntervalRepeating() {
return AwesomeNotifications().createNotification(
content: NotificationContent(
id: 102,
channelKey: channelKey,
title: 'Repeating interval',
body: 'Repeats every 60 seconds.',
payload: {'uuid': 'interval-repeat'},
),
extensions: [
NotificationInterval(
interval: const Duration(seconds: 60),
repeats: true,
allowWhileIdle: true,
),
],
);
}
/// *********************************************
/// SCHEDULE — CALENDAR DATE
/// *********************************************
// Fires once at a specific clock time (here, 15 seconds from now).
static Future<void> scheduleCalendarOnce() {
final DateTime when = DateTime.now().add(const Duration(seconds: 15));
return AwesomeNotifications().createNotification(
content: NotificationContent(
id: 111,
channelKey: channelKey,
title: 'Calendar schedule',
body: 'Delivered at '
'${_two(when.hour)}:${_two(when.minute)}:${_two(when.second)}.',
payload: {'uuid': 'calendar-once'},
),
extensions: [
NotificationCalendar(
hour: when.hour,
minute: when.minute,
second: when.second,
allowWhileIdle: true,
),
],
);
}
// Repeats every day at 09:00:00.
static Future<void> scheduleCalendarDaily() {
return AwesomeNotifications().createNotification(
content: NotificationContent(
id: 112,
channelKey: channelKey,
title: 'Daily reminder',
body: 'Repeats every day at 09:00.',
payload: {'uuid': 'calendar-daily'},
),
extensions: [
NotificationCalendar(
hour: 9,
minute: 0,
second: 0,
repeats: true,
allowWhileIdle: true,
),
],
);
}
/// *********************************************
/// SCHEDULE — WITH BIG PICTURE
/// *********************************************
// A scheduled notification carrying a big picture + large icon, so tapping the
// delivered notification opens the styled details page.
static const String _networkImage =
'https://media.wired.com/photos/598e35994ab8482c0d6946e0/master/w_2560%2Cc_limit/phonepicutres-TA.jpg';
static const String _largeIcon =
'https://image.freepik.com/vetores-gratis/modelo-de-logotipo-de-restaurante-retro_23-2148451519.jpg';
static Future<void> scheduleWithBigPicture() {
return AwesomeNotifications().createNotification(
content: NotificationContent(
id: 121,
channelKey: channelKey,
title: 'Scheduled big picture',
body: 'Delivered in 10 seconds — tap it to open the details page.',
notificationLayout: NotificationLayout.BigPicture,
bigPicture: _networkImage,
largeIcon: _largeIcon,
roundedLargeIcon: true,
payload: {'uuid': 'calendar-bigpicture'},
),
extensions: [
NotificationInterval(
interval: const Duration(seconds: 10),
allowWhileIdle: true,
),
],
);
}
/// *********************************************
/// INSPECT SCHEDULES
/// *********************************************
// Previews the next fire date of a schedule without creating a notification.
static Future<void> previewNextDate() async {
final DateTime? next = await _schedules.getNextDate(
NotificationCalendar(hour: 9, minute: 0, second: 0, repeats: true),
);
_showEventSnackBar(
next == null ? 'No upcoming date' : 'Next fire date: $next',
mainColor,
);
}
// Lists the currently pending scheduled notifications.
static Future<void> listScheduled() async {
final List<NotificationModel> scheduled =
await _schedules.listScheduledNotifications();
_showEventSnackBar('${scheduled.length} scheduled notification(s)', mainColor);
}
/// *********************************************
/// DISMISS / CANCEL
/// *********************************************
// Dismiss removes the notifications from the status bar (keeps any schedule).
static Future<void> dismissNotifications() {
return AwesomeNotifications().dismissAllNotifications();
}
// Cancels every pending schedule (leaves any already-displayed notification).
static Future<void> cancelAllSchedules() {
return _schedules.cancelAllSchedules();
}
// Cancel removes the notifications AND cancels their schedule.
static Future<void> cancelNotifications() {
return AwesomeNotifications().cancelAll();
}
// Zero-pads a clock component for display.
static String _two(int value) => value.toString().padLeft(2, '0');
}
/// *********************************************
/// MAIN WIDGET
/// *********************************************
///
class MyApp extends StatelessWidget {
final Future<bool> awesomeNotificationsInitialization;
const MyApp({super.key, required this.awesomeNotificationsInitialization});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Awesome Notifications - Schedules Example',
navigatorKey: NotificationController.navigatorKey,
scaffoldMessengerKey: NotificationController.scaffoldMessengerKey,
theme: ThemeData(
colorSchemeSeed: mainColor,
useMaterial3: true,
),
// Show a simple splash until the plugin finished initializing.
home: FutureBuilder<bool>(
future: awesomeNotificationsInitialization,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const _SplashScreen();
}
return const HomePage();
},
),
);
}
}
class _SplashScreen extends StatelessWidget {
const _SplashScreen();
@override
Widget build(BuildContext context) {
return const Scaffold(
backgroundColor: mainColor,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.schedule, size: 72, color: Colors.white),
SizedBox(height: 24),
CircularProgressIndicator(color: Colors.white),
],
),
),
);
}
}
/// *********************************************
/// HOME PAGE
/// *********************************************
///
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _allowed = false;
@override
void initState() {
super.initState();
NotificationController.startListeningNotificationEvents();
// Handle a notification tap that launched the app from a killed state.
NotificationController.handleInitialAction();
AwesomeNotifications().isNotificationAllowed().then(
(allowed) => setState(() => _allowed = allowed),
);
}
Future<void> _requestPermission() async {
final allowed = await NotificationController.requestPermission(context);
setState(() => _allowed = allowed);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: mainColor,
foregroundColor: Colors.white,
title: const Text('Awesome Schedules Example'),
),
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('Time interval'),
_WideButton(
'Schedule in 10 seconds',
onPressed: NotificationController.scheduleInterval,
),
_WideButton(
'Repeat every 60 seconds',
onPressed: NotificationController.scheduleIntervalRepeating,
),
const _SectionDivisor('Calendar date'),
_WideButton(
'Schedule in 15 seconds',
onPressed: NotificationController.scheduleCalendarOnce,
),
_WideButton(
'Daily at 09:00',
onPressed: NotificationController.scheduleCalendarDaily,
),
const _SectionDivisor('With big picture'),
_WideButton(
'Scheduled big picture (10s)',
onPressed: NotificationController.scheduleWithBigPicture,
),
const _SectionDivisor('Inspect schedules'),
_WideButton(
'Preview next fire date',
onPressed: NotificationController.previewNextDate,
),
_WideButton(
'List scheduled notifications',
onPressed: NotificationController.listScheduled,
),
const _SectionDivisor('Dismiss vs Cancel'),
Text(
'Dismiss only removes notifications from the status bar. '
'Cancel schedules removes pending schedules. '
'Cancel does both.',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 8),
_WideButton(
'Dismiss notifications',
onPressed: NotificationController.dismissNotifications,
),
_WideButton(
'Cancel all schedules',
onPressed: NotificationController.cancelAllSchedules,
),
_WideButton(
'Cancel notifications',
onPressed: NotificationController.cancelNotifications,
),
const SizedBox(height: 24),
],
),
);
}
}
/// *********************************************
/// REUSABLE WIDGETS (inlined to keep this a single-file example)
/// *********************************************
///
/// 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. Mirrors the base example's page: a
/// stretchy, collapsing big-picture header with the large icon overlaid, the
/// title/body, and the raw received action at the bottom.
class NotificationPage extends StatefulWidget {
final ReceivedAction action;
const NotificationPage({super.key, required this.action});
@override
State<NotificationPage> createState() => _NotificationPageState();
}
class _NotificationPageState extends State<NotificationPage> {
static const String _placeholder =
'https://cdn.syncfusion.com/content/images/common/placeholder.gif';
final ScrollController _scrollController = ScrollController();
bool _isCollapsed = false;
ReceivedAction get action => widget.action;
bool get hasTitle => action.title?.isNotEmpty ?? false;
bool get hasBody => action.body?.isNotEmpty ?? false;
bool get hasLargeIcon => action.largeIconImage != null;
bool get hasBigPicture => action.bigPictureImage != null;
@override
void initState() {
super.initState();
_scrollController.addListener(_scrollListener);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _scrollListener() {
final pastLimit = _scrollController.position.pixels >=
_scrollController.position.maxScrollExtent - 240;
if (!hasBigPicture) return;
if (_isCollapsed != pastLimit) {
setState(() => _isCollapsed = pastLimit);
}
}
@override
Widget build(BuildContext context) {
final double bigPictureSize = MediaQuery.of(context).size.height * 0.4;
final double largeIconSize =
MediaQuery.of(context).size.height * (hasBigPicture ? 0.16 : 0.2);
final bool overImage = hasBigPicture && !_isCollapsed;
return Scaffold(
body: CustomScrollView(
controller: _scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
SliverAppBar(
elevation: 0,
pinned: true,
stretch: true,
centerTitle: true,
backgroundColor: Colors.transparent,
systemOverlayStyle:
overImage ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark,
leading: IconButton(
onPressed: () => Navigator.pop(context),
icon: Icon(
Icons.arrow_back_ios_rounded,
color: overImage ? Colors.white : Colors.black,
),
),
expandedHeight: hasBigPicture
? bigPictureSize + (hasLargeIcon ? 40 : 0)
: (hasLargeIcon
? largeIconSize + 10
: MediaQuery.of(context).padding.top + 28),
flexibleSpace: FlexibleSpaceBar(
stretchModes: const [StretchMode.zoomBackground],
centerTitle: true,
expandedTitleScale: 1,
collapseMode: CollapseMode.pin,
title: !hasLargeIcon
? null
: Stack(
children: [
Positioned(
bottom: 0,
left: 16,
right: 16,
child: Row(
mainAxisAlignment: hasBigPicture
? MainAxisAlignment.start
: MainAxisAlignment.center,
children: [
SizedBox(
height: largeIconSize,
width: largeIconSize,
child: ClipRRect(
borderRadius:
BorderRadius.circular(largeIconSize),
child: FadeInImage(
placeholder:
const NetworkImage(_placeholder),
image: action.largeIconImage!,
fit: BoxFit.cover,
),
),
),
],
),
),
],
),
background: !hasBigPicture
? null
: Padding(
padding:
EdgeInsets.only(bottom: hasLargeIcon ? 60 : 20),
child: FadeInImage(
placeholder: const NetworkImage(_placeholder),
image: action.bigPictureImage!,
height: bigPictureSize,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
),
),
),
SliverList(
delegate: SliverChildListDelegate([
Padding(
padding:
const EdgeInsets.only(bottom: 20, left: 20, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (hasTitle)
Text(
action.title!,
style: Theme.of(context).textTheme.titleLarge,
),
if (hasBody) ...[
const SizedBox(height: 16),
Text(
action.bodyWithoutHtml ?? '',
style: Theme.of(context).textTheme.bodyMedium,
),
],
],
),
),
Container(
width: double.infinity,
color: Colors.black12,
padding: const EdgeInsets.all(20),
child: Text(action.toString()),
),
]),
),
],
),
);
}
}