Push notifications are a great way to engage users by sending timely updates and alerts directly to their devices. In this guide, we will set up push notifications in a Flutter app using Firebase Cloud Messaging (FCM) and PHP as the server-side script.
Before we begin, make sure you have the following:
google-services.json
(for Android) or GoogleService-Info.plist
(for iOS)android/app
and ios/Runner
)pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
firebase_core: latest_version
firebase_messaging: latest_version
main.dart
file:
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print("Message received: ${message.notification?.title}");
});
FirebaseMessaging.instance.getToken().then((token) {
print("Device Token: $token");
});
Create a file send_notification.php
and add the following code:
<?php
function sendPushNotification($deviceToken, $title, $message) {
$serverKey = 'YOUR_FIREBASE_SERVER_KEY';
$url = 'https://fcm.googleapis.com/fcm/send';
$notification = [
'title' => $title,
'body' => $message,
'sound' => 'default'
];
$payload = [
'to' => $deviceToken,
'notification' => $notification,
'priority' => 'high'
];
$headers = [
'Authorization: key=' . $serverKey,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$deviceToken = $_POST['token'];
$title = $_POST['title'];
$message = $_POST['message'];
echo sendPushNotification($deviceToken, $title, $message);
?>
To trigger the PHP script from Flutter, use the http
package:
dependencies:
http: latest_version
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> sendNotification(String token, String title, String message) async {
final url = Uri.parse("YOUR_PHP_SCRIPT_URL");
final response = await http.post(
url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {
'token': token,
'title': title,
'message': message,
},
);
print("Response: ${response.body}");
}
By following these steps, you have successfully set up push notifications in Flutter using Firebase Cloud Messaging and PHP as the backend. You can now send notifications from your PHP script to your Flutter app users.
Let us know if you have any questions in the comments below!