DEV3 Technologies home

DEV3 Developer Forum

How do I set up Firebase push notifications (FCM) in Flutter for Android and iOS?

Flutter helpSolved0 views
dev3 ·

I want to send a push notification to a specific user and open a screen when it is tapped, even if the app was closed. What are the minimum steps with firebase_messaging, and what are the iOS gotchas?

#flutter#firebase#push#fcm

0

1 reply

dev3 · Accepted answer

Setup

  1. Create a Firebase project and run flutterfire configure (FlutterFire CLI). It generates firebase_options.dart and adds the platform config files.
  2. Add firebase_core and firebase_messaging to pubspec.yaml.
  3. Initialise before runApp:
@pragma('vm:entry-point')
Future<void> _bgHandler(RemoteMessage m) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  FirebaseMessaging.onBackgroundMessage(_bgHandler); // top-level function
  runApp(const MyApp());
}

Permission and token

final fm = FirebaseMessaging.instance;
await fm.requestPermission();            // required on iOS and Android 13+
final token = await fm.getToken();       // send this to your backend
fm.onTokenRefresh.listen(sendTokenToBackend);

Handling the three app states

FirebaseMessaging.onMessage.listen((m) { /* foreground: show in-app UI */ });
FirebaseMessaging.onMessageOpenedApp.listen((m) { /* tapped, app was in background */ });
final initial = await fm.getInitialMessage();  // tapped, app was terminated

Put an identifier in the data payload (for example {"screen":"order","id":"42"}) and route from it.

Android notes

  • Android 13+ requires the POST_NOTIFICATIONS runtime permission.
  • Foreground notifications are not shown by the system; use flutter_local_notifications if you want a banner.

iOS notes

  • Needs a paid Apple Developer account, the Push Notifications and Background Modes (Remote notifications) capabilities, and an APNs key (.p8) uploaded in Firebase project settings > Cloud Messaging.
  • It does not work on the simulator for real APNs delivery in older setups; test on a device.

Pitfalls

  • Use the data field for routing, since notification content is shown by the OS and not delivered to your handler when the app is in the background.
  • Tokens change; always refresh them on your server and delete invalid ones when FCM returns UNREGISTERED.

Related: the push permission flow snippet.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.