Hello Developers,
I will cover a very important topic today which is Firebase Push Notification in the Flutter application using Laravel. In the first part, we will create a Laravel project to build an API. In the Second part, we will create a Flutter project to get Push Notification. Let's Begin.
We will follow the steps below:
Install Laravel Project For Creating the API
First, you need to go to your development workspace. My workspace is situated in D:/
drive. Open a command prompt and write the below code to install Laravel.
laravel new example-app
Let's create a controller. In the command prompt type the below command:
php artisan make:controller NotificationController
In this controller paste the below function:
/app/Http/Controller/NotificationController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class NotificationController extends Controller
{
public function sendNotification(Request $request)
{
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$notification = [
"to" => '/topics/topic',
"notification" => [
"title" => $request->title,
"body" => $request->body
]
];
$headers = [
'Authorization: key=[XXXX]',
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
$result = curl_exec($ch);
print_r($result);
//exit();
curl_close($ch);
return true;
}
}
In the [XXXX] marked position, you need to paste the server key. The way of getting the server key will show later in this tutorial.
If we run php artisan server
, the API will be ready for execution. Now we will create a Flutter app for configuring the notification part.
Flutter App Installation
Open the android studio and create a fresh Flutter project like below:
Give a name like test_app in the android studio.
Firebase Integration
First, create a project in the Firebase console. It is the main thing for getting the Push Notification in the mobile application as we are using Firebase Push Notification. Open the panel and type the project name.
After finishing, open the Firebase console. You need to set the package name as the name given in the flutter application. You can also find the package name in the AndroidMenifest.xml file. This file location exists in [project_directory]/android/app/src/main/AndroidMenifest.xml
The console looks like this:
From here, you will get the google-services.json file. Put the file in the projects [project_directory]/
android/app/
directory.
We need three package add the three package in the pubspec.yaml
file.
firebase_messaging
firebase_core
firebase_analytics
Then modify two files. One is android/app/build.gradle
and another in android/build.gradle
. It is mandatory for implementing firebase push notifications.
In the android/app/build.gradle
add the below line:
apply plugin: 'com.google.gms.google-services'
The file looks like below:
/android/app/build.gradle
In the android/build.gradle
add the below line:
classpath 'com.google.gms:google-services:4.3.13'
The file looks like below:
android/build.gradle
After that add these lines in the main.dart
file main()
function.
/lib/main.dart
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
After adding the lines, the main function needs to change to async
. The function should be like this:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
For the notification configuration and to get the notification on the mobile screen, the below lines should be added to the main.dart
file
@override
initState() {
super.initState();
FirebaseMessaging.instance.getInitialMessage();
//FirebaseMessaging.instance.subscribeToTopic('topic');
FirebaseMessaging.instance.subscribeToTopic('test');
//app is foreground state
FirebaseMessaging.onMessage.listen((message) {
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
}
});
// app is close but not terminate
FirebaseMessaging.onMessageOpenedApp.listen((message) {
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
}
});
// when app is terminate
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) {
print(message.notification!.title);
print(message.notification!.title);
}
});
}
The complete code of the main.dart
file is given below:
/lib/main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
initState() {
super.initState();
FirebaseMessaging.instance.getInitialMessage();
//FirebaseMessaging.instance.subscribeToTopic('topic');
FirebaseMessaging.instance.subscribeToTopic('test');
//app is foreground state
FirebaseMessaging.onMessage.listen((message) {
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
}
});
// app is close but not terminate
FirebaseMessaging.onMessageOpenedApp.listen((message) {
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
}
});
// when app is terminate
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) {
print(message.notification!.title);
print(message.notification!.title);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Here the installation is complete of the web and mobile application project. run the API in the postman like below:
Now run the app by the below command one by one:
flutter clean
flutter pub get
flutter run
Put the app in the background or terminate the application, then click send in the API. Then you will get the notification below:
That's all for today. Hope this might help you in the development journey.
Read More: How to add Foreign key in Laravel Migration