Skip to main content

awesome_notifications_onesignal 1.0.0-dev.10 copy "awesome_notifications_onesignal: ^1.0.0-dev.10" to clipboard
awesome_notifications_onesignal: ^1.0.0-dev.10 copied to clipboard

OneSignal pushes shown by awesome_notifications: layouts, channels, buttons and events of the core, with the official OneSignal plugin kept for everything else.

example/lib/main.dart

import 'dart:io';
import 'dart:math' show max;

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:awesome_notifications_onesignal/awesome_notifications_onesignal.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart' show SystemUiOverlayStyle;
import 'package:material_ui/material_ui.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

/// Your OneSignal app id:
/// `flutter run --dart-define=ONESIGNAL_APP_ID=<your app id>`.
const String oneSignalAppId = String.fromEnvironment('ONESIGNAL_APP_ID');

const String channelKey = 'push';
const Color mainColor = Color(0xFFE54B4D);

/// The events, for the page.
final ValueNotifier<List<String>> events = ValueNotifier([]);

void log(String event) => events.value = [event, ...events.value.take(19)];

/// Opens the details page of a tapped notification.
void openNotificationPage(ReceivedAction action) {
  OneSignalExampleApp.navigatorKey.currentState?.pushAndRemoveUntil(
    MaterialPageRoute(builder: (_) => NotificationPage(action: action)),
    (route) => route.isFirst,
  );
}

@pragma('vm:entry-point')
Future<void> onActionReceived(ReceivedAction action) async {
  log('Awesome action on #${action.id} ${action.buttonKeyPressed}');
  openNotificationPage(action);
}

@pragma('vm:entry-point')
Future<void> onNotificationDisplayed(
  ReceivedNotification notification,
) async => log(
  'Push shown: ${notification.title} '
  '(OneSignal id ${AwesomeNotificationsOneSignal.oneSignalIdOf(notification)})',
);

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await AwesomeNotifications()
      .initialize('resource://drawable/res_notification_icon', [
        NotificationChannel(
          channelKey: channelKey,
          channelName: 'Push notifications',
          channelDescription: 'Notifications delivered through OneSignal',
          importance: NotificationImportance.High,
        ),
      ]);
  await AwesomeNotifications().setListeners(
    onActionReceivedMethod: onActionReceived,
    onNotificationDisplayedMethod: onNotificationDisplayed,
  );
  if (oneSignalAppId.isEmpty) {
    log('Run with --dart-define=ONESIGNAL_APP_ID=<your app id>');
  } else {
    // The official plugin: the SDK, the user, the permission.
    await OneSignal.initialize(oneSignalAppId);
    await OneSignal.Notifications.requestPermission(true);
    await AwesomeNotificationsOneSignal().initialize(defaultChannelKey: channelKey);
    // OneSignal's own events keep working for the pushes the core shows.
    OneSignal.Notifications.addClickListener(
      (event) => log(
        'OneSignal click: ${event.notification.notificationId} '
        '${event.result.actionId ?? ''}',
      ),
    );
    OneSignal.Notifications.addForegroundWillDisplayListener(
      (event) => log('OneSignal will display: ${event.notification.title}'),
    );
    log('OneSignal started');
  }
  runApp(const OneSignalExampleApp());
}

/// 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 push channel. Tap it.',
      largeIcon: hasResources ? 'resource://drawable/res_app_icon' : null,
      payload: {'source': 'local test'},
    ),
  );
}

class OneSignalExampleApp extends StatelessWidget {
  const OneSignalExampleApp({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 OneSignal',
    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? _subscriptionId;
  bool _optedIn = false;
  bool _oneSignalPermission = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _handleInitialAction();
    _refresh();
    if (oneSignalAppId.isEmpty) return;
    OneSignal.User.pushSubscription.addObserver((state) {
      if (mounted) {
        setState(() {
          _subscriptionId = state.current.id;
          _optedIn = state.current.optedIn;
        });
      }
    });
    OneSignal.Notifications.addPermissionObserver((permission) {
      if (mounted) setState(() => _oneSignalPermission = permission);
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) _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();
    if (!mounted) return;
    setState(() {
      _allowed = allowed;
      if (oneSignalAppId.isEmpty) return;
      _subscriptionId = OneSignal.User.pushSubscription.id;
      _optedIn = OneSignal.User.pushSubscription.optedIn ?? false;
      _oneSignalPermission = OneSignal.Notifications.permission;
    });
  }

  Future<void> _requestPermission() async {
    await AwesomeNotifications().requestPermissionToSendNotifications();
    await _refresh();
  }

  Future<void> _requestOneSignalPermission() async {
    await OneSignal.Notifications.requestPermission(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('OneSignal'),
      ),
      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('OneSignal'),
          _StatusCard(
            title: oneSignalAppId.isEmpty
                ? 'Run with --dart-define=ONESIGNAL_APP_ID=<your app id>'
                : 'OneSignal started with your app id',
            chips: {
              'App id': oneSignalAppId.isNotEmpty,
              'Permission': _oneSignalPermission,
              'Subscribed': _subscriptionId != null,
              'Opted in': _optedIn,
            },
            children: [
              if (oneSignalAppId.isNotEmpty && !_oneSignalPermission) ...[
                const SizedBox(height: 12),
                FilledButton.tonal(
                  onPressed: _requestOneSignalPermission,
                  child: const Text('Allow OneSignal pushes'),
                ),
              ],
              const SizedBox(height: 12),
              SelectableText(
                'Push subscription: ${_subscriptionId ?? 'Not subscribed yet'}',
                style: white,
              ),
            ],
          ),
          const _SectionDivisor('Push'),
          Text(
            'Send a push from the OneSignal dashboard, or with awesome '
            'sections in its additional data:',
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.bodySmall,
          ),
          const SizedBox(height: 8),
          const SelectableText(
            '{"content": {"channelKey": "push", "title": "Hi", '
            '"body": "From OneSignal", "notificationLayout": "BigText"}, '
            '"actionButtons": [{"key": "REPLY", "label": "Reply", '
            '"requireInputText": true}]}',
            style: TextStyle(fontFamily: 'monospace', fontSize: 12),
          ),
          const _SectionDivisor('Local notifications'),
          const _WideButton(
            'Local test notification',
            onPressed: createTestNotification,
          ),
          _WideButton(
            'Dismiss all',
            onPressed: AwesomeNotifications().dismissAllNotifications,
          ),
          const _SectionDivisor('Events'),
          const _EventList(emptyText: 'None yet'),
          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),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
0
likes
150
points
--
downloads

Documentation

API reference

Publisher

unverified uploader

OneSignal pushes shown by awesome_notifications: layouts, channels, buttons and events of the core, with the official OneSignal plugin kept for everything else.

License

Apache-2.0 (license)

Dependencies

awesome_notifications, flutter, onesignal_flutter

More

Packages that depend on awesome_notifications_onesignal

Packages that implement awesome_notifications_onesignal