notificationapi_flutter_sdk 1.0.2 copy "notificationapi_flutter_sdk: ^1.0.2" to clipboard
notificationapi_flutter_sdk: ^1.0.2 copied to clipboard

A Flutter plugin for integrating NotificationAPI push notifications into your mobile app.

NotificationAPI Flutter SDK #

A Flutter plugin for integrating NotificationAPI push notifications into your mobile app.

πŸš€ Quick Start #

1. Installation #

Add to your pubspec.yaml:

dependencies:
  notificationapi_flutter_sdk: ^1.0.0

2. Setup (One Line!) #

import 'package:notificationapi_flutter_sdk/notificationapi_flutter_sdk.dart';

// That's it! This handles initialization, user identification, and permission requests
await NotificationAPI.setup(
  clientId: 'your_client_id_here',
  userId: 'user123',
  email: 'user@example.com', // optional
  autoRequestPermission: true, // automatically request push permissions
  showForegroundNotifications: true, // show native notifications when app is open
);

3. Listen to Notifications (Optional) #

// Listen to notifications received while app is open
// Note: These are automatically shown as native notifications by default
NotificationAPI.onMessage.listen((notification) {
  print('Received: ${notification.title}');
  // Optional: Handle notification data or custom actions
});

// Listen to notifications that opened the app
NotificationAPI.onMessageOpenedApp.listen((notification) {
  print('App opened from: ${notification.title}');
  // Handle deep linking or navigation
});

4. Check Status #

// Check if everything is ready
if (NotificationAPI.isReady) {
  print('NotificationAPI is ready to receive notifications!');
}

// Get the FCM token
String? token = await NotificationAPI.getToken();

πŸ“± Complete Example #

import 'package:flutter/material.dart';
import 'package:notificationapi_flutter_sdk/notificationapi_flutter_sdk.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _setupNotifications();
  }

  Future<void> _setupNotifications() async {
    try {
      await NotificationAPI.setup(
        clientId: 'your_client_id',
        userId: 'user123',
        email: 'user@example.com',
        showForegroundNotifications: true, // Auto-show native notifications
      );

      // Optional: Listen for custom handling
      NotificationAPI.onMessage.listen((notification) {
        print('Foreground notification: ${notification.title}');
        // Notification is automatically displayed as native notification
      });

      NotificationAPI.onMessageOpenedApp.listen((notification) {
        print('App opened from notification: ${notification.title}');
        // Handle navigation or deep linking
        if (notification.deepLink != null) {
          // Navigate to specific screen
        }
      });
    } catch (e) {
      print('Error setting up notifications: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('NotificationAPI Example')),
        body: Center(
          child: Column(
            children: [
              Text('Ready: ${NotificationAPI.isReady}'),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  bool granted = await NotificationAPI.requestPermission();
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Permission: ${granted ? "Granted" : "Denied"}')),
                  );
                },
                child: Text('Request Permission'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  // Toggle foreground notification display
                  NotificationAPI.setShowForegroundNotifications(false);
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Foreground notifications disabled')),
                  );
                },
                child: Text('Disable Foreground Notifications'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

πŸŒ™ Background Notifications (App Closed) #

To handle notifications when your app is completely closed or terminated, you need to set up a background message handler. This handler runs in a separate isolate and has limited capabilities.

1. Create a Background Handler #

Add this top-level function (outside any class) in your main.dart:

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:notificationapi_flutter_sdk/notificationapi_flutter_sdk.dart';

// This must be a top-level function (not inside a class)
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // Initialize Firebase if needed
  await Firebase.initializeApp();

  print('Handling background message: ${message.messageId}');
  print('Title: ${message.notification?.title}');
  print('Body: ${message.notification?.body}');

  // You can perform lightweight tasks here:
  // - Save data to local storage
  // - Show local notifications
  // - Update app badge
  // - Send analytics events

  // Note: You cannot update UI or navigate to screens from here
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Register the background message handler
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  runApp(MyApp());
}

2. Handle Initial Message (App Opened from Notification) #

When users tap a notification while the app is terminated, handle it in your app startup:

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _setupNotifications();
    _handleInitialMessage(); // Add this
  }

  Future<void> _setupNotifications() async {
    await NotificationAPI.setup(
      clientId: 'your_client_id',
      userId: 'user123',
    );

    // Handle notifications when app is running
    NotificationAPI.onMessageOpenedApp.listen((notification) {
      _handleNotificationTap(notification);
    });
  }

  // Handle notification that opened the app from terminated state
  Future<void> _handleInitialMessage() async {
    final initialMessage = await FirebaseMessaging.instance.getInitialMessage();
    if (initialMessage != null) {
      final notification = PushNotification.fromRemoteMessage(initialMessage);
      _handleNotificationTap(notification);
    }
  }

  void _handleNotificationTap(PushNotification notification) {
    print('Notification tapped: ${notification.title}');

    // Handle deep linking or navigation
    if (notification.deepLink != null) {
      // Navigate to specific screen
      Navigator.pushNamed(context, notification.deepLink!);
    }
  }
}

3. Background Handler Limitations #

βœ… What you CAN do in background handler:

  • Process notification data
  • Save to local storage (SharedPreferences, SQLite)
  • Show local notifications
  • Send HTTP requests
  • Update app badge
  • Perform lightweight computations

❌ What you CANNOT do in background handler:

  • Update UI or widgets
  • Navigate to screens
  • Access Flutter widgets or context
  • Perform heavy/long-running tasks
  • Access platform channels

4. Testing Background Notifications #

To test background notifications:

  1. Terminate your app (don't just minimize it)
  2. Send a push notification from NotificationAPI dashboard
  3. Check device logs to see if background handler executes
  4. Tap the notification to see if app opens with initial message

5. Platform-Specific Setup #

Android

Background notifications work out of the box on Android with Firebase messaging.

iOS

For iOS, ensure you have:

  • Background App Refresh enabled
  • Push Notifications capability in Xcode
  • Proper APNs configuration in Firebase Console

πŸ”” Native Notification Display #

Automatic Foreground Notifications #

By default, when showForegroundNotifications: true is set in setup(), the SDK automatically displays received notifications as native push notifications even when your app is in the foreground. This provides a consistent user experience.

Notification Behavior #

App State Notification Display
Foreground Native notification banner/alert (automatic)
Background System notification (handled by OS)
Terminated System notification (handled by OS)

Customization Options #

await NotificationAPI.setup(
  // ... other parameters
  showForegroundNotifications: true,  // Enable native notifications in foreground
);

// You can also toggle this later
NotificationAPI.setShowForegroundNotifications(false); // Disable
NotificationAPI.setShowForegroundNotifications(true);  // Re-enable

πŸ”§ API Reference #

NotificationAPI #

Method Description Returns
setup() One-call setup with initialization, identification, and optional permission request Future<void>
requestPermission() Request push notification permission Future<bool>
getToken() Get the current FCM token Future<String?>
onMessage Stream of foreground notifications (auto-displayed as native notifications) Stream<PushNotification>
onMessageOpenedApp Stream of notifications that opened the app Stream<PushNotification>
currentUser Get current user info NotificationUser?
isReady Check if SDK is ready bool
setShowForegroundNotifications() Enable/disable automatic native notification display void

Setup Parameters #

await NotificationAPI.setup({
  required String clientId,           // Your NotificationAPI client ID
  required String userId,             // User's unique identifier
  String? email,                      // User's email (optional)
  String? hashedUserId,              // Hashed user ID for privacy (optional)
  Map<String, dynamic>? customProperties, // Additional user data (optional)
  bool autoRequestPermission = true, // Auto-request push permission (optional)
  bool showForegroundNotifications = true, // Auto-show native notifications (optional)
  FirebaseApp? firebaseApp,          // Custom Firebase app (optional)
});

πŸ”’ Privacy & Security #

  • User IDs can be hashed for additional privacy
  • All communication uses HTTPS
  • FCM tokens are securely stored in NotificationAPI backend

πŸ› οΈ Firebase Setup #

  1. Create a Firebase project at Firebase Console
  2. Add your iOS/Android apps to the project
  3. Download google-services.json (Android) and GoogleService-Info.plist (iOS)
  4. Follow the FlutterFire setup guide

πŸ› Troubleshooting #

Common Issues #

  1. Notifications not received

    • Verify Firebase setup is correct
    • Check if permission was granted: await NotificationAPI.requestPermission()
    • Ensure your NotificationAPI client ID is correct
  2. Foreground notifications not showing

    • Make sure showForegroundNotifications: true in setup
    • Check that notification permissions are granted
    • Verify app is actually in foreground
  3. Token is null

    • Firebase may not be properly initialized
    • Check device/simulator supports FCM

πŸ“ž Support #

πŸ“„ License #

This project is licensed under the MIT License - see the LICENSE file for details.