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.
Prerequisites
Before we begin, make sure you have the following:
- A Flutter project
- A Firebase project with FCM enabled
- Basic knowledge of PHP
- A Firebase server key
Step 1: Setup Firebase in Flutter
- Create a Firebase Project
- Go to Firebase Console
- Click on “Add project” and follow the setup instructions
- Add Firebase to Your Flutter App
- Register your app (Android and/or iOS) in Firebase
- Download the
google-services.json
(for Android) orGoogleService-Info.plist
(for iOS) - Place the files in the appropriate directories (
android/app
andios/Runner
)
- Install Firebase Packages Add the following dependencies to your
pubspec.yaml
file:dependencies: flutter: sdk: flutter firebase_core: latest_version firebase_messaging: latest_version
- Initialize Firebase Modify your
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()); }
Step 2: Configure Firebase Cloud Messaging
- Request Notification Permissions (iOS & Android)
FirebaseMessaging messaging = FirebaseMessaging.instance; NotificationSettings settings = await messaging.requestPermission( alert: true, badge: true, sound: true, );
- Listen for Incoming Messages
FirebaseMessaging.onMessage.listen((RemoteMessage message) { print("Message received: ${message.notification?.title}"); });
- Get Device Token
FirebaseMessaging.instance.getToken().then((token) { print("Device Token: $token"); });
Step 3: Create PHP Script to Send Notifications
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);
?>
Step 4: Send Notification from Flutter
To trigger the PHP script from Flutter, use the http
package:
- Add Dependency
dependencies: http: latest_version
- Send Notification Request
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}"); }
Conclusion
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.
Next Steps
- Store device tokens in a database to send notifications to multiple users.
- Customize notifications with additional data.
- Implement background notification handling.
Let us know if you have any questions in the comments below!