Skip to main content

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

Braze pushes built and shown by awesome_notifications on Android and iOS, next to the official braze_plugin: the core's layouts, channels, buttons and events.

example/lib/main.dart

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

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

/// Your Braze app's API key and SDK endpoint:
/// `flutter run --dart-define=BRAZE_API_KEY=<key> --dart-define=BRAZE_ENDPOINT=<endpoint>`.
const String brazeApiKey = String.fromEnvironment('BRAZE_API_KEY');
const String brazeEndpoint = String.fromEnvironment('BRAZE_ENDPOINT');

const String channelKey = 'braze';
const Color mainColor = Color(0xFF9D50DD);

/// Whether Braze was started (both dart-defines set).
bool get brazeConfigured => brazeApiKey.isNotEmpty && brazeEndpoint.isNotEmpty;

/// What both plugins report, newest first, for the page.
final ValueNotifier<List<String>> events = ValueNotifier([]);

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

String origin(ReceivedNotification notification) =>
    AwesomeNotificationsBraze.isBrazeNotification(notification)
    ? 'Braze push'
    : 'notification';

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

@pragma('vm:entry-point')
Future<void> onActionReceived(ReceivedAction action) async {
  final button = action.buttonKeyPressed;
  log(
    'Core: action on ${origin(action)} #${action.id}'
    '${button.isEmpty ? '' : ' (button $button)'}',
  );
  openNotificationPage(action);
}

@pragma('vm:entry-point')
Future<void> onNotificationDisplayed(ReceivedNotification notification) async =>
    log('Core: ${origin(notification)} shown: ${notification.title}');

@pragma('vm:entry-point')
Future<void> onDismissActionReceived(ReceivedAction action) async =>
    log('Core: ${origin(action)} #${action.id} dismissed');

late final BrazePlugin braze;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await AwesomeNotifications()
      .initialize('resource://drawable/res_notification_icon', [
        NotificationChannel(
          channelKey: channelKey,
          channelName: 'Braze campaigns',
          channelDescription: 'Notifications sent by Braze',
          importance: NotificationImportance.High,
        ),
      ]);
  await AwesomeNotifications().setListeners(
    onActionReceivedMethod: onActionReceived,
    onNotificationDisplayedMethod: onNotificationDisplayed,
    onDismissActionReceivedMethod: onDismissActionReceived,
  );

  // After the core: the pushes without a channel of their own use 'braze'.
  await AwesomeNotificationsBraze().initialize(defaultChannelKey: channelKey);

  // braze_plugin keeps its own events for the same pushes.
  braze = BrazePlugin(
    pushEventHandler: (event) => log(
      'Braze: ${event.payloadType} '
      '${event.title ?? ''}${event.url == null ? '' : ' → ${event.url}'}',
    ),
  );
  if (!brazeConfigured) {
    log('Run with --dart-define=BRAZE_API_KEY=… and BRAZE_ENDPOINT=…');
  } else {
    braze.initialize(brazeApiKey, brazeEndpoint);
    log('Braze started');
  }

  runApp(const BrazeExampleApp());
}

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

class BrazeExampleApp extends StatelessWidget {
  const BrazeExampleApp({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 Braze',
    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 {
  final _user = TextEditingController();
  bool _allowed = false;
  String? _userId;
  String? _deviceId;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _handleInitialAction();
    _refresh();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _user.dispose();
    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 initial = await AwesomeNotifications().getInitialNotificationAction(
      removeFromActionEvents: true,
    );
    if (initial == null) return;
    log('Core: the app was opened by #${initial.id}');
    openNotificationPage(initial);
  }

  Future<void> _refresh() async {
    final allowed = await AwesomeNotifications().isNotificationAllowed();
    // braze_plugin answers these only once Braze was started.
    final userId = brazeConfigured ? await braze.getUserId() : null;
    final deviceId = brazeConfigured ? await braze.getDeviceId() : null;
    if (mounted) {
      setState(() {
        _allowed = allowed;
        _userId = userId;
        _deviceId = deviceId;
      });
    }
  }

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

  Future<void> _changeUser() async {
    final id = _user.text.trim();
    if (id.isEmpty) return;
    braze.changeUser(id);
    log('Braze: user $id');
    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('Braze pushes'),
      ),
      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('Braze'),
          _StatusCard(
            title: brazeConfigured
                ? 'Braze started with your API key and endpoint'
                : 'Run with --dart-define=BRAZE_API_KEY=… and BRAZE_ENDPOINT=…',
            chips: {
              'API key': brazeApiKey.isNotEmpty,
              'Endpoint': brazeEndpoint.isNotEmpty,
              'User': _userId?.isNotEmpty ?? false,
            },
            children: [
              if (_deviceId != null) ...[
                const SizedBox(height: 12),
                SelectableText('Device id: $_deviceId', style: white),
              ],
              if (_userId?.isNotEmpty ?? false) ...[
                const SizedBox(height: 4),
                SelectableText('User id: $_userId', style: white),
              ],
            ],
          ),
          const _SectionDivisor('Braze user'),
          TextField(
            controller: _user,
            decoration: const InputDecoration(
              labelText: 'External user id',
              border: OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 8),
          _WideButton('Change user', onPressed: _changeUser),
          const _SectionDivisor('Local notifications'),
          const _WideButton(
            'Local test notification',
            onPressed: createTestNotification,
          ),
          _WideButton(
            'Dismiss all',
            onPressed: AwesomeNotifications().dismissAllNotifications,
          ),
          const _SectionDivisor('Events'),
          Text(
            'Send a push campaign from the Braze dashboard: the core '
            'shows it, and both plugins report it.',
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.bodySmall,
          ),
          const SizedBox(height: 8),
          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

Braze pushes built and shown by awesome_notifications on Android and iOS, next to the official braze_plugin: the core's layouts, channels, buttons and events.

License

Apache-2.0 (license)

Dependencies

awesome_notifications, braze_plugin, flutter

More

Packages that depend on awesome_notifications_braze

Packages that implement awesome_notifications_braze