Flutter ve React Native'de Push Notification: Kurulum ve İlk Mesaj

Push notification göndermek için Firebase Cloud Messaging (FCM) kullanmak en yaygın yol. Her iki platformda da kurulum benzer adımlardan oluşur.

Önce Firebase projesini oluştur ve google-services.json dosyasını indir. Proje kök dizininde android/app klasörüne koy.

Pubspec.yaml dosyasına firebase_messaging paketini ekle:

1dependencies:
2flutter:
3sdk: flutter
4firebase_core: ^2.24.0
5firebase_messaging: ^14.6.0

Android için android/app/build.gradle dosyasında:

1android {
2compileSdk 34
3defaultConfig {
4minSdkVersion 21
5}
6}

Main.dart dosyasında Firebase'i başlat:

1import 'package:firebase_core/firebase_core.dart';
2import 'firebase_options.dart';
3
4void main() async {
5WidgetsFlutterBinding.ensureInitialized();
6await Firebase.initializeApp(
7options: DefaultFirebaseOptions.currentPlatform,
8);
9runApp(const MyApp());
10}

Npm veya yarn ile paketi yükle:

Reklam · TEST
AdSense Test ReklamıYazı arası (gönderi içi) · Yazı arası
1npm install @react-native-firebase/app @react-native-firebase/messaging

Android için google-services.json dosyasını android/app klasörüne koy ve android/build.gradle dosyasını güncelle:

1buildscript {
2dependencies {
3classpath 'com.google.gms:google-services:4.3.15'
4}
5}

android/app/build.gradle sonunda ekle:

1apply plugin: 'com.google.gms.google-services'

Flutter'da:

1import 'package:firebase_messaging/firebase_messaging.dart';
2
3class PushNotificationService {
4static final FirebaseMessaging _messaging = FirebaseMessaging.instance;
5
6static Future<void> initialize() async {
7// Token al
8String? token = await _messaging.getToken();
9print('FCM Token: $token');
10
11// Ön plan mesajlarını dinle
12FirebaseMessaging.onMessage.listen((RemoteMessage message) {
13print('Mesaj alındı: ${message.notification?.title}');
14print('İçerik: ${message.notification?.body}');
15});
16}
17}
18
19// main() içinde:
20await PushNotificationService.initialize();

React Native'de:

1import messaging from '@react-native-firebase/messaging';
2
3const initializeMessaging = async () => {
4// Token al
5const token = await messaging().getToken();
6console.log('FCM Token:', token);
7
8// Ön plan mesajlarını dinle
9const unsubscribe = messaging().onMessage(async (remoteMessage) => {
10console.log('Mesaj:', remoteMessage.notification?.title);
11console.log('İçerik:', remoteMessage.notification?.body);
12});
13
14return unsubscribe;
15};
16
17initializeMessaging();

FCM token'ı sunucuna kaydet. Firebase Console'dan test mesajı gönder: Engagement > Messaging > Yeni kampanya > Bildirim. Hedef olarak token seç ve gönder. Mesaj cihazda görünür.

Bu kurulum tamamlandığında, cihazınız push notification almaya hazır olur.

Reklam · TEST
AdSense Test ReklamıGönderi altı · Görüntülü
konu hakkında tepkinizi verebilirsiniz