# Flutter recipe

Register a Flutter app's APNs and FCM tokens with Native Notify using firebase_messaging, show Android pushes, and show images.

## 1. Set up your Flutter project

```bash
flutter pub add firebase_core firebase_messaging flutter_local_notifications http
flutterfire configure
```

`flutterfire configure` generates `firebase_options.dart`. On iOS, enable the **Push Notifications** capability in Xcode — Native Notify sends straight to APNs with your `.p8` key, so Firebase needs no APNs key.

On Android, `flutter_local_notifications` needs core library desugaring, or the build stops at `checkDebugAarMetadata`. Add it to the app's Gradle file, and keep the lines you already have:

<!-- tabs -->

#### build.gradle.kts

```kotlin title="android/app/build.gradle.kts"
android {
    compileOptions {
        isCoreLibraryDesugaringEnabled = true
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}
```

#### build.gradle

```gradle title="android/app/build.gradle"
android {
    compileOptions {
        coreLibraryDesugaringEnabled true
    }
}

dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.4'
}
```

<!-- /tabs -->

## 2. Register the device and show pushes

```dart title="lib/native_notify_push.dart"
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:http/http.dart' as http;

const _registerUrl = 'https://app.nativenotify.com/api/universal/device/register';

/// Registers this device's native token: APNs on iOS, FCM on Android.
/// Returns false when the token is not ready yet or the server refused it.
Future<bool> registerUniversalDevice({
  required int appId,
  required String appToken,
  required String deviceId,
  String? subscriberId,
}) async {
  final messaging = FirebaseMessaging.instance;
  // Nothing is shown without permission (tokens are issued either way).
  await messaging.requestPermission();

  // iOS: the raw APNs token (null until APNs has delivered it). Android: the FCM token.
  final String? token = Platform.isIOS ? await messaging.getAPNSToken() : await messaging.getToken();
  if (token == null) return false; // not ready yet — the next launch registers
  return _post(appId: appId, appToken: appToken, deviceId: deviceId, subscriberId: subscriberId, token: token);
}

/// Android rotates FCM tokens: register the new one under the same device.
StreamSubscription<String> watchUniversalToken({
  required int appId,
  required String appToken,
  required String deviceId,
  String? subscriberId,
}) {
  return FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
    if (!Platform.isAndroid) return; // iOS registers its APNs token, not an FCM token
    _post(appId: appId, appToken: appToken, deviceId: deviceId, subscriberId: subscriberId, token: fcmToken);
  });
}

Future<bool> _post({
  required int appId,
  required String appToken,
  required String deviceId,
  required String token,
  String? subscriberId,
}) async {
  final res = await http.post(
    Uri.parse(_registerUrl),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      'appId': appId,
      'appToken': appToken,
      'deviceId': deviceId, // one stable id per install
      'platform': Platform.isIOS ? 'ios' : 'android',
      if (subscriberId != null) 'subscriberId': subscriberId,
      'tokens': Platform.isIOS ? {'apnsToken': token} : {'fcmToken': token},
    }),
  );
  if (res.statusCode != 201) {
    // 400/403 answer {"error":{"code","message"}}; a wrong appId/appToken answers 401 as plain text.
    debugPrint('Native Notify register failed (${res.statusCode}): ${res.body}');
    return false;
  }
  return true;
}

final _localNotifications = FlutterLocalNotificationsPlugin();

Future<void> _initLocalNotifications() => _localNotifications.initialize(
      settings: const InitializationSettings(android: AndroidInitializationSettings('@mipmap/ic_launcher')),
    );

/// Android 8+ shows nothing without a channel. Firebase draws a closed-app push on `default`, so create it at launch.
Future<void> createDefaultNotificationChannel() async {
  await _initLocalNotifications();
  await _localNotifications
      .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(const AndroidNotificationChannel('default', 'Notifications', importance: Importance.high));
}

/// Android pushes are FCM *data* messages — show them yourself.
Future<void> showNativeNotifyMessage(RemoteMessage message) async {
  final data = message.data; // every value is a String
  final title = data['title'];
  if (title == null) return;
  await _initLocalNotifications();
  // A send with bigPictureURL also carries a notification block with the image URL.
  final picture = await _downloadPicture(message.notification?.android?.imageUrl);
  await _localNotifications.show(
    id: DateTime.now().millisecondsSinceEpoch & 0x7fffffff,
    title: title,
    body: data['message'],
    notificationDetails: NotificationDetails(
      android: AndroidNotificationDetails(
        data['channelId'] ?? 'default',
        'Notifications',
        importance: Importance.high,
        priority: Priority.high,
        largeIcon: picture, // the thumbnail while the notification is collapsed
        styleInformation: picture == null ? null : BigPictureStyleInformation(picture, hideExpandedLargeIcon: true),
      ),
    ),
    payload: data['body'], // your pushData JSON (+ nn_notification_id / nn_source)
  );
}

/// https only, a picture under 5 MB, 8 seconds; anything else shows the text alone.
Future<ByteArrayAndroidBitmap?> _downloadPicture(String? url) async {
  if (url == null || !url.startsWith('https://')) return null;
  try {
    final response = await http.get(Uri.parse(url)).timeout(const Duration(seconds: 8));
    final isImage = (response.headers['content-type'] ?? '').startsWith('image/');
    if (response.statusCode != 200 || !isImage || response.bodyBytes.length > 5 * 1024 * 1024) return null;
    return ByteArrayAndroidBitmap(response.bodyBytes);
  } catch (_) {
    return null;
  }
}
```

An iOS **FCM** token is rejected with `token_platform_mismatch`, so the code never sends one. `initialize` and `show` take named parameters from flutter\_local\_notifications 20; on 19 or older, pass them positionally.

## 3. Wire it up in `main()`

```dart title="lib/main.dart"
import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/widgets.dart';

import 'native_notify_push.dart';

// Runs in its own isolate when a data message arrives in the background.
@pragma('vm:entry-point')
Future<void> _onBackgroundMessage(RemoteMessage message) async {
  await Firebase.initializeApp(); // pass your DefaultFirebaseOptions.currentPlatform here
  await showNativeNotifyMessage(message);
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(); // pass your DefaultFirebaseOptions.currentPlatform here

  if (Platform.isAndroid) {
    await createDefaultNotificationChannel();
    FirebaseMessaging.onBackgroundMessage(_onBackgroundMessage);
    FirebaseMessaging.onMessage.listen(showNativeNotifyMessage);
  } else {
    // iOS shows the APNs alert itself — also while the app is open:
    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(alert: true, badge: true, sound: true);
  }

  const appId = 123; // your app id + token (e.g. from --dart-define)
  const appToken = 'yourAppToken';
  const deviceId = 'a-stable-per-install-id'; // e.g. a UUID saved with shared_preferences
  await registerUniversalDevice(appId: appId, appToken: appToken, deviceId: deviceId);
  watchUniversalToken(appId: appId, appToken: appToken, deviceId: deviceId);

  runApp(const SizedBox()); // your app
}
```

On iOS, firebase\_messaging forwards only FCM-originated notifications to `onMessage` and `onMessageOpenedApp`, so Native Notify's direct-APNs pushes never reach those handlers. Handle iOS taps in the AppDelegate's `UNUserNotificationCenter` delegate and pass them over a method channel, as in the [Swift recipe](/docs/push/recipes/swift).

## 4. Save credentials in Native Notify

In [Native Notify](https://dashboard.nativenotify.com), open your project's **Settings → Push credentials** and save the same Firebase project's service-account JSON and your Apple `.p8` key. See [Push credentials](/docs/push/credentials).

## 5. Send a push with the API

Check one device first with a [test send](/docs/push/verification). For other audiences, see [Send notifications](/docs/push/sending). This call reaches every registered device:

```bash
curl -X POST https://app.nativenotify.com/api/universal/notifications/send \
  -H "Content-Type: application/json" \
  -d '{"appId":123,"appToken":"yourAppToken","title":"Hello Flutter","message":"Sent through APNs/FCM.","audience":{"type":"all"}}'
```

## Show images

Firebase draws a push's picture itself while the app is closed or in the background. Name the channel it should use, inside `<application>`:

```xml title="android/app/src/main/AndroidManifest.xml"
<meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="default" />
```

`createDefaultNotificationChannel()` in `main()` creates that channel at launch, and `showNativeNotifyMessage` draws the picture while the app is open: a send with `bigPictureURL` carries a notification block, and `message.notification?.android?.imageUrl` holds the URL.

On iPhone, add a notification service extension to the Runner project: open `ios/Runner.xcworkspace` in Xcode, then follow [Show images in the Swift recipe](/docs/push/recipes/swift#show-images). The iPhone Simulator never runs it, so test on an iPhone. [Send a push with a `bigPictureURL`](/docs/push/sending#images): an `https` JPEG or PNG under 1 MB.

## Next steps

- [Device registration](/docs/push/registration) — fields, deregister and errors.
- [Groups](/docs/push/groups) — let users subscribe from the app with `POST /api/universal/groups/subscribe`, then send to the group.
