Feature Guide
Firebase Setup

Firebase and Push Notifications Guide

This guide walks you through setting up Firebase services and integrating push notifications in your Flutter Bunny CLI-generated application. We'll cover Firebase initialization using FlutterFire CLI and configuring Flutter Local Notifications on both Android and iOS platforms.

Firebase Setup with FlutterFire CLI

Flutter Bunny CLI generates a project that's ready for Firebase integration when you select the "Push Notification" module. Here's how to complete the setup:

1. Install FlutterFire CLI

First, install the FlutterFire CLI tool:

dart pub global activate flutterfire_cli

2. Create a Firebase Project

If you haven't already, create a new Firebase project:

  1. Go to the Firebase Console (opens in a new tab)
  2. Click "Add project"
  3. Follow the setup wizard to create your project
  4. Add iOS and Android apps to your Firebase project with your bundle identifier

3. Configure Your Flutter Project

In your Flutter Bunny CLI-generated project, run:

flutterfire configure --project=your-firebase-project-id

This command will:

  • Identify your Flutter project's platforms (iOS, Android)
  • Download and add required configuration files
  • Create a firebase_options.dart file in your lib directory

4. Update Generated Code

The Flutter Bunny CLI already generates most of the notification-related code, but you need to update the Firebase initialization in your main.dart:

import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart'; // This is generated by FlutterFire CLI
 
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize Firebase with your configuration
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  
  // Initialize notification services (already generated by Flutter Bunny CLI)
  await notificationHandler.initialize();
  
  runApp(const App());
}

Understanding the Generated Notification Code

Flutter Bunny CLI creates a comprehensive notification system when you select the "Push Notification" module. Let's explore the key components:

Core Files Generated

  1. FCM Service (lib/core/notifications/services/fcm_service.dart)

    • Handles FCM token management
    • Processes incoming Firebase messages
    • Manages notification permissions
  2. Local Notification Service (lib/core/notifications/services/local_notification_service.dart)

    • Configures and displays local notifications
    • Manages notification channels
    • Handles notification responses
  3. Notification Handler (lib/core/notifications/notification_handler.dart)

    • Central manager for both FCM and local notifications
    • Provides a unified API for your app to interact with notifications
    • Manages listeners for notification events
  4. Notification Model (lib/core/notifications/models/push_notification_model.dart)

    • Data model for notification content

Notification Flow

Here's how the notification system works:

  1. Foreground notifications: When your app is open, FCM messages are intercepted and displayed as local notifications
  2. Background notifications: When your app is in the background, FCM displays notifications directly
  3. Notification taps: User taps are routed back to your app with the notification payload

iOS Configuration: AppDelegate Setup

The iOS AppDelegate configuration is critical for push notifications to work properly on iOS devices. Flutter Bunny CLI generates much of this for you, but understanding each component is important.

The Complete AppDelegate Code

import Flutter
import UIKit
import flutter_local_notifications
 
@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
        GeneratedPluginRegistrant.register(with: registry)
    }
 
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }
 
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Understanding Each Component

  1. Plugin Registration Callback:

    FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
      GeneratedPluginRegistrant.register(with: registry)
    }

    This ensures that when notifications launch your app from a terminated state, the Flutter plugin is properly registered with the Flutter engine.

  2. UNUserNotificationCenter Delegate:

    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }

    Setting the delegate enables your app to:

    • Show notifications while the app is in the foreground
    • Handle user interactions with notifications
    • Process notification delivery events
  3. Standard Flutter Setup:

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)

    This standard Flutter code registers all plugins with the main application.

Info.plist Configuration

Flutter Bunny CLI adds the necessary entries to your Info.plist for background notifications:

<key>UIBackgroundModes</key>
<array>
  <string>fetch</string>
  <string>processing</string>
  <string>remote-notification</string>
</array>

It also disables automatic Firebase initialization to ensure proper startup sequence:

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

Setting Up Apple Push Notification Service (APNs)

To send push notifications on iOS, you need to set up Apple Push Notification service (APNs):

1. Generate Push Certificate

  1. Log in to your Apple Developer account at developer.apple.com (opens in a new tab)
  2. Navigate to Certificates, IDs & Profiles
  3. Select "Identifiers" and locate your app ID
  4. Click on the app ID and enable Push Notifications
  5. In the "Certificates" section, click "+" to create a new certificate
  6. Select "Apple Push Notification service SSL (Sandbox & Production)"
  7. Follow the instructions to generate a CSR using Keychain Access
  8. Upload the CSR and download the certificate
  9. Double-click the downloaded certificate to install it in Keychain Access
  10. From Keychain Access, export the certificate and private key as a .p12 file (you'll need to set a password)

2. Upload Certificate to Firebase

  1. Go to Firebase Console > Project Settings > Cloud Messaging
  2. In the "Apple apps" section, upload the .p12 file you exported
  3. Enter the password you created when exporting the certificate

3. Enable Push Capabilities in Xcode

  1. Open your Xcode project (ios/Runner.xcworkspace)
  2. Select the Runner target
  3. Go to "Signing & Capabilities"
  4. Click "+ Capability" and add "Push Notifications"
  5. Also add "Background Modes" and check "Remote notifications"

Requesting Notification Permissions

The generated code already requests notification permissions at runtime:

NotificationSettings settings = await _firebaseMessaging.requestPermission(
  alert: true,
  announcement: false,
  badge: true,
  carPlay: false,
  criticalAlert: false,
  provisional: false,
  sound: true,
);

For iOS 10+ compatibility, the generated code also sets up presentation options:

if (Platform.isIOS) {
  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );
}

Testing Push Notifications

To test your push notification setup:

1. Get FCM Token

Flutter Bunny CLI generates a FlutterBunnyScreen that displays your FCM token. Use this token for testing.

2. Send Test Notification

Use the Firebase Console or FCM API to send a test notification:

  1. Go to Firebase Console > Cloud Messaging
  2. Create a new notification
  3. Select "Send to specific devices" and enter your FCM token
  4. Fill in notification details and send

3. Use In-App Testing

The generated FlutterBunnyScreen also includes a "Send Test Notification" button that triggers a local notification for testing.

Advanced Features and Customization

Handling Notification Taps

The generated code sets up handlers for notification taps. To customize the behavior:

// Add this to your initialization code
notificationHandler.addOnNotificationTapListener((payload) {
  if (payload != null) {
    // Parse the payload and navigate accordingly
    final data = json.decode(payload);
    if (data['screen'] == 'chat') {
      // Navigate to chat screen
    }
  }
});

Subscribing to Topics

For topic-based notifications:

await notificationHandler.subscribeToTopic('news');

Customizing Notification Appearance

To customize notification appearance, modify the AndroidNotificationDetails in the local notification service:

const AndroidNotificationDetails androidPlatformChannelSpecifics =
    AndroidNotificationDetails(
  'high_importance_channel',
  'High Importance Notifications',
  importance: Importance.max,
  priority: Priority.high,
  color: Colors.blue,
  enableLights: true,
  enableVibration: true,
  // Add icon, sound, etc.
);

For iOS, you can customize the DarwinNotificationDetails:

const DarwinNotificationDetails iOSPlatformChannelSpecifics =
    DarwinNotificationDetails(
  presentAlert: true,
  presentBadge: true,
  presentSound: true,
  sound: 'notification_sound.aiff',  // Custom sound file in the app bundle
  badgeNumber: 1,
  categoryIdentifier: 'textCategory', // For actionable notifications
);

Troubleshooting

Common Issues on iOS

1. Notifications not showing

  • Verify APNs certificate is uploaded correctly to Firebase
  • Check that AppDelegate is configured properly
  • Ensure notification permissions were accepted by the user

2. Missing notification permissions

  • Confirm Push Notifications capability is added in Xcode
  • Verify Background Modes with Remote notifications is enabled

3. AppDelegate issues

Common error: "Unrecognized selector sent to instance"

  • Make sure the flutter_local_notifications import is correct
  • Verify the plugin is properly added to pubspec.yaml
  • Run pod install in the iOS directory

4. Certificate errors

  • Ensure your APNs certificate is not expired
  • Verify the bundle ID matches exactly between your app and certificate

Common Issues on Android

1. Missing notifications

  • Verify google-services.json is in the correct location
  • Check that Firebase configuration is properly initialized
  • Ensure device has Google Play Services installed

2. Channel issues

  • Verify notification channels are properly configured
  • For Android 8.0+, ensure channel ID is consistent

3. Icon problems

  • Make sure notification icons follow Android guidelines (transparent with a white fill)
  • Verify icons are added to the correct resource directories

Debugging Notifications

Add these lines to your initialization code to get detailed logs:

// Set FCM logging level
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('Got a message whilst in the foreground!');
  print('Message data: ${message.data}');
  print('Message notification: ${message.notification}');
});
 
// Debug APNs token for iOS
if (Platform.isIOS) {
  FirebaseMessaging.instance.getAPNSToken().then((token) {
    print('APNs token: $token');
  });
}

iOS-Specific Tip: Testing with Simulators

iOS simulators cannot receive push notifications. For testing:

  1. Use a physical iOS device for full push notification testing
  2. For simulator testing, use the local notification test button in the FlutterBunnyScreen
  3. The notification handler in Flutter Bunny CLI has code to detect simulator environments and provide fallback behavior

Next Steps

Now that you've set up Firebase and notifications in your Flutter Bunny CLI-generated project, consider these next steps:

  1. Set up Firebase Analytics to track notification engagement
  2. Implement deep linking to navigate to specific screens from notifications
  3. Add notification categories for more interactive notifications on iOS
  4. Create custom notification sounds by adding audio files to your project

By following this guide, you've successfully integrated a production-ready notification system into your Flutter application using Flutter Bunny CLI.