Skip to main content

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

PlatformWindows

Windows push notifications for awesome_notifications through the Windows Push Notification Services (WNS).

example/lib/main.dart

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

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:awesome_notifications_wns/awesome_notifications_wns.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// The Application (client) ID of your app registration in Microsoft Entra
/// ID (Azure), given when running:
/// `flutter run -d windows --dart-define=WNS_AZURE_APP_ID=<GUID>`.
const String azureAppId = String.fromEnvironment('WNS_AZURE_APP_ID');

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 channel and the pushes, for the page.
final ValueNotifier<WnsChannel?> channel = 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> onChannel(WnsChannel newChannel) async {
  channel.value = newChannel;
  log('Channel until ${newChannel.expiration.toLocal()}');
}

@pragma('vm:entry-point')
Future<void> onRawData(WnsRawData data) async => log(
    'Raw data${data.launchedApp ? ' (started the app)' : ''}: ${data.payload}');

@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(null, [
    NotificationChannel(
      channelKey: channelKey,
      channelName: 'Push notifications',
      channelDescription: 'Notifications delivered through WNS',
      importance: NotificationImportance.High,
    ),
  ]);
  await AwesomeNotifications().setListeners(
    onActionReceivedMethod: onActionReceived,
    onNotificationCreatedMethod: onNotificationCreated,
  );
  if (azureAppId.isEmpty) {
    log('Run with --dart-define=WNS_AZURE_APP_ID=<your Azure app id>');
  } else {
    final started = await AwesomeNotificationsWns().initialize(
      azureAppId: azureAppId,
      onChannel: onChannel,
      onRawData: onRawData,
    );
    log(started ? 'WNS started' : 'WNS is not available here');
  }
  runApp(const WnsExampleApp());
}

/// A local notification on the push channel: tap it to try the details page
/// without sending a push. Windows has no resources: no large icon.
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.',
      payload: {'uuid': 'uuid-test'},
    ),
  );
}

class WnsExampleApp extends StatelessWidget {
  const WnsExampleApp({super.key});

  @override
  Widget build(BuildContext context) => MaterialApp(
        title: 'Awesome WNS',
        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;
  bool _available = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // Handle a notification tap that launched the app from a killed state.
    handleInitialAction();
    _refreshPermission();
    _refreshAvailability();
  }

  @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> _refreshAvailability() async {
    bool available;
    try {
      available = await AwesomeNotificationsWns().isAvailable;
    } catch (_) {
      available = false;
    }
    if (mounted) setState(() => _available = available);
  }

  Future<void> _requestChannel() async {
    final requested = await AwesomeNotificationsWns().requestChannel();
    if (requested == null) log('No channel');
  }

  @override
  Widget build(BuildContext context) {
    final wns = AwesomeNotificationsWns();
    return Scaffold(
      appBar: AppBar(
        backgroundColor: mainColor,
        foregroundColor: Colors.white,
        title: const Text('Windows push (WNS)'),
      ),
      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('Windows Push Notification Services'),
          ValueListenableBuilder<WnsChannel?>(
            valueListenable: channel,
            builder: (context, value, _) => _StatusCard(
              title: value != null
                  ? 'This app receives pushes through WNS'
                  : azureAppId.isEmpty
                      ? 'Run with --dart-define=WNS_AZURE_APP_ID=<GUID>'
                      : wns.isInitialized
                          ? 'Request a channel to receive pushes'
                          : 'WNS is not available here',
              chips: {
                'Runtime': _available,
                'Started': wns.isInitialized,
                'Channel': value != null,
              },
              children: [
                if (value != null) ...[
                  _CardText('Channel URI: ${value.uri}'),
                  _CardText('Expires: ${value.expiration.toLocal()}'),
                ],
                if (wns.isInitialized)
                  FilledButton.tonal(
                    onPressed: _requestChannel,
                    child: Text(
                        value == null ? 'Request a channel' : 'Request again'),
                  ),
              ],
            ),
          ),
          const _SectionDivisor('Channel'),
          _WideButton(
            'Copy the channel URI',
            onPressed: () {
              final uri = channel.value?.uri;
              if (uri != null) Clipboard.setData(ClipboardData(text: uri));
            },
          ),
          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),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
0
likes
150
points
--
downloads

Documentation

API reference

Publisher

unverified uploader

Windows push notifications for awesome_notifications through the Windows Push Notification Services (WNS).

License

Apache-2.0 (license)

Dependencies

awesome_notifications, flutter

More

Packages that depend on awesome_notifications_wns

Packages that implement awesome_notifications_wns