Schedule local notifications and receive push with FCM.
Notifications Overview
flutter pub add flutter_local_notifications
flutter pub add firebase_messaging
flutter pub add firebase_core<!-- android/app/src/main/AndroidManifest.xml -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- For Android 13+ -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<!-- ios/Runner/Info.plist -->
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>Local Notifications
// lib/services/local_notifications.dart
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
class LocalNotificationService {
static final FlutterLocalNotificationsPlugin _notifications =
FlutterLocalNotificationsPlugin();
static bool _initialized = false;
static Future<void> initialize() async {
if (_initialized) return;
tz.initializeTimeZones();
const AndroidInitializationSettings androidSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
const DarwinInitializationSettings iosSettings =
DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
const InitializationSettings settings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
await _notifications.initialize(
settings,
onDidReceiveNotificationResponse: _onNotificationTapped,
onDidReceiveBackgroundNotificationResponse: _onNotificationTapped,
);
// Request permissions
await _requestPermissions();
_initialized = true;
}
static Future<void> _requestPermissions() async {
// Android 13+
final androidPlugin = _notifications.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
await androidPlugin?.requestNotificationsPermission();
// iOS
final iosPlugin = _notifications.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>();
await iosPlugin?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
static void _onNotificationTapped(NotificationResponse response) {
// Handle tap - navigate based on payload
final payload = response.payload;
if (payload != null) {
// Navigate to screen
print('Notification tapped: $payload');
}
}
// Show immediate notification
static Future<void> showNotification({
required int id,
required String title,
required String body,
String? payload,
NotificationDetails? details,
}) async {
await _notifications.show(
id,
title,
body,
details ?? _defaultDetails(),
payload: payload,
);
}
// Schedule notification
static Future<void> scheduleNotification({
required int id,
required String title,
required String body,
required DateTime scheduledDate,
String? payload,
NotificationDetails? details,
}) async {
await _notifications.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(scheduledDate, tz.local),
details ?? _defaultDetails(),
payload: payload,
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
// Periodic notification
static Future<void> schedulePeriodic({
required int id,
required String title,
required String body,
required RepeatInterval interval,
String? payload,
}) async {
await _notifications.periodicallyShow(
id,
title,
body,
interval,
_defaultDetails(),
payload: payload,
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
);
}
// Cancel notification
static Future<void> cancel(int id) async {
await _notifications.cancel(id);
}
// Cancel all
static Future<void> cancelAll() async {
await _notifications.cancelAll();
}
// Get pending notifications
static Future<List<PendingNotificationRequest>> getPending() async {
return await _notifications.pendingNotificationRequests();
}
static NotificationDetails _defaultDetails() {
return const NotificationDetails(
android: AndroidNotificationDetails(
'default_channel',
'Default',
channelDescription: 'Default notification channel',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
),
iOS: DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
),
);
}
// Rich notification with actions
static Future<void> showWithActions({
required int id,
required String title,
required String body,
required List<NotificationAction> actions,
}) async {
await _notifications.show(
id,
title,
body,
NotificationDetails(
android: AndroidNotificationDetails(
'actions_channel',
'Actions',
channelDescription: 'Notifications with actions',
importance: Importance.high,
priority: Priority.high,
actions: actions.map((a) => a.toAndroidAction()).toList(),
),
iOS: DarwinNotificationDetails(
presentAlert: true,
categoryIdentifier: 'actions_category',
),
),
);
}
}
// Notification action model
class NotificationAction {
final String id;
final String title;
final bool isDestructive;
NotificationAction({required this.id, required this.title, this.isDestructive = false});
AndroidNotificationAction toAndroidAction() {
return AndroidNotificationAction(
id,
title,
showsUserInterface: true,
cancelNotification: true,
isAuthenticationRequired: false,
);
}
}FCM (Firebase Cloud Messaging)
// lib/services/fcm_service.dart
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class FCMService {
static final FirebaseMessaging _messaging = FirebaseMessaging.instance;
static final FlutterLocalNotificationsPlugin _localNotifications =
FlutterLocalNotificationsPlugin();
static Future<void> initialize() async {
// Request permission
final settings = await _messaging.requestPermission(
alert: true,
badge: true,
sound: true,
provisional: false,
);
print('FCM Permission: ${settings.authorizationStatus}');
// Get token
final token = await _messaging.getToken();
print('FCM Token: $token');
// Send token to your server
// await ApiClient().registerDeviceToken(token!);
// Handle foreground messages
FirebaseMessaging.onMessage.listen(_handleForegroundMessage);
// Handle background messages (app in background but not terminated)
FirebaseMessaging.onMessageOpenedApp.listen(_handleBackgroundMessage);
// Handle terminated state (app opened from notification)
final initialMessage = await _messaging.getInitialMessage();
if (initialMessage != null) {
_handleBackgroundMessage(initialMessage);
}
// Token refresh
_messaging.onTokenRefresh.listen((newToken) {
print('FCM Token refreshed: $newToken');
// Send to server
});
}
static Future<void> _handleForegroundMessage(RemoteMessage message) async {
print('Foreground message: ${message.notification?.title}');
// Show local notification
await LocalNotificationService.showNotification(
id: message.hashCode,
title: message.notification?.title ?? 'New Message',
body: message.notification?.body ?? '',
payload: message.data['route'],
);
}
static void _handleBackgroundMessage(RemoteMessage message) {
print('Background message: ${message.notification?.title}');
final route = message.data['route'];
if (route != null) {
// Navigate when app opens
// navigatorKey.currentState?.pushNamed(route);
}
}
// Subscribe to topic
static Future<void> subscribeToTopic(String topic) async {
await _messaging.subscribeToTopic(topic);
}
// Unsubscribe from topic
static Future<void> unsubscribeFromTopic(String topic) async {
await _messaging.unsubscribeFromTopic(topic);
}
}
// Background handler (must be top-level function)
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('Background handler: ${message.messageId}');
}main.dart Setup
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Background handler
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
// Initialize notifications
await LocalNotificationService.initialize();
await FCMService.initialize();
runApp(MyApp());
}Notification Categories (iOS)
// iOS categories for actions
static Future<void> setupIOSCategories() async {
final iosPlugin = _notifications.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>();
await iosPlugin?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
// Define categories in AppDelegate.swift// ios/Runner/AppDelegate.swift
import UserNotifications
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let center = UNUserNotificationCenter.current()
// Define actions
let acceptAction = UNNotificationAction(
identifier: "ACCEPT",
title: "Accept",
options: [.foreground]
)
let declineAction = UNNotificationAction(
identifier: "DECLINE",
title: "Decline",
options: [.destructive]
)
// Define category
let inviteCategory = UNNotificationCategory(
identifier: "INVITE_CATEGORY",
actions: [acceptAction, declineAction],
intentIdentifiers: [],
options: []
)
center.setNotificationCategories([inviteCategory])
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}Notification Payload Handling
// Navigate based on notification payload
class NotificationRouter {
static void handlePayload(String? payload) {
if (payload == null) return;
final uri = Uri.parse(payload);
switch (uri.path) {
case '/movie':
final id = uri.queryParameters['id'];
if (id != null) {
navigatorKey.currentState?.pushNamed('/movie/$id');
}
case '/chat':
final conversationId = uri.queryParameters['conversationId'];
if (conversationId != null) {
navigatorKey.currentState?.pushNamed('/chat/$conversationId');
}
default:
break;
}
}
}
// Global navigator key
final navigatorKey = GlobalKey<NavigatorState>();
// In MaterialApp
MaterialApp(
navigatorKey: navigatorKey,
// ...
)Testing Notifications
// Test local notifications
testWidgets('Local notification shows', (tester) async {
await LocalNotificationService.initialize();
await LocalNotificationService.showNotification(
id: 1,
title: 'Test',
body: 'Test body',
);
// Verify notification was scheduled
final pending = await LocalNotificationService.getPending();
expect(pending.length, 1);
});Try It
Initialize local notifications. Show immediate notification. Schedule for 10 seconds later. Add action buttons.
flutter pub add flutter_local_notifications firebase_messaging firebase_core
flutter pub add timezoneBuild notification system
- Set up Firebase project and add google-services.json / GoogleService-Info.plist
- Initialize FCM and local notifications
- Handle foreground/background/terminated states
- Create notification channels for different types
- Add rich notifications with actions
- Implement topic subscriptions
- Test with Firebase Console
- Handle notification tap navigation
Use flutter_local_notifications for local/scheduled notifications. Use firebase_messaging for push notifications. Handle all three app states: foreground, background, terminated. Request permissions on both platforms. Use notification categories for actions on iOS.
Resources
- flutter_local_notifications: https://pub.dev/packages/flutter_local_notifications
- firebase_messaging: https://pub.dev/packages/firebase_messaging
- FCM Documentation: https://firebase.google.com/docs/cloud-messaging