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?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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?
Setup
flutterfire configure (FlutterFire CLI). It generates firebase_options.dart and adds the platform config files.firebase_core and firebase_messaging to pubspec.yaml.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
POST_NOTIFICATIONS runtime permission.flutter_local_notifications if you want a banner.iOS notes
Pitfalls
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.UNREGISTERED.Related: the push permission flow snippet.