Skip to content

Instantly share code, notes, and snippets.

@AdnanKhan45
Created January 24, 2024 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdnanKhan45/cfd83e7a51a74d5895505ffbbbaaf66b to your computer and use it in GitHub Desktop.
Save AdnanKhan45/cfd83e7a51a74d5895505ffbbbaaf66b to your computer and use it in GitHub Desktop.

WhatsApp Clone (Push Notifications)

For more very small changes, you'll found them in the video.

import 'package:firebase_messaging/firebase_messaging.dart';
class GetDeviceTokenUseCase{
final FirebaseMessaging firebaseMessaging;
GetDeviceTokenUseCase({required this.firebaseMessaging});
Future<String?> call() async {
return await firebaseMessaging.getToken();
}
}
di.sl<GetDeviceTokenUseCase>().call().then((deviceTokenValue) {
print("deviceToken $deviceTokenValue");
BlocProvider.of<UserCubit>(context)
.updateUser(
user: UserEntity(
uid: widget.uid,
token: deviceTokenValue,
))
.then((value) {
print("update user completed");
});
});
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
exports.sendUserNotification = functions.firestore
.document('users/{userId}/notifications/{notificationId}').onCreate(
async (snapshot: functions.firestore.QueryDocumentSnapshot, context: functions.EventContext) => {
// Extracting information from the newly created notification
const notificationData = snapshot.data();
const recipientUid = context.params.userId;
// Fetch recipient's device token from Firestore
const recipientDoc = await admin.firestore().doc(`users/${recipientUid}`).get();
const recipientData = recipientDoc.data();
// Check if the recipient has a device token
if (recipientData && recipientData.token) {
const token = recipientData.token;
// Define your notification payload
const payload = {
notification: {
title:notificationData.username,
body:notificationData.description,
clickAction:"FLUTTER_NOTIFICATION_CLICK"
},
data: {
uid: notificationData.uid,
notificationId: context.params.notificationId
}
}
const message = {
token: token,
notification: {
title: payload.notification.title,
body: payload.notification.body
},
data: payload.data,
};
// Send a message to the device corresponding to the provided registration token
try {
await admin.messaging().send(message);
console.log('Notification sent successfully');
} catch (error) {
console.error('Error sending notification', error);
}
} else {
console.log('No device token for recipient');
}
});
final sl = GetIt.instance;
Future<void> init() async {
final auth = FirebaseAuth.instance;
final fireStore = FirebaseFirestore.instance;
final firebaseMessaging = FirebaseMessaging.instance;
sl.registerLazySingleton(() => auth);
sl.registerLazySingleton(() => fireStore);
sl.registerLazySingleton(() => firebaseMessaging);
sl.registerLazySingleton<GetDeviceTokenUseCase>(() => GetDeviceTokenUseCase(firebaseMessaging: firebaseMessaging));
sl.registerLazySingleton<NotificationRepository>(() => NotificationRepository(fireStore: fireStore));
await userInjectionContainer();
await chatInjectionContainer();
await statusInjectionContainer();
await callInjectionContainer();
}
import 'package:cloud_firestore/cloud_firestore.dart';
class NotificationEntity {
final String? notificationId;
final String? uid;
final String? otherUid;
final String? username;
final String? userProfile;
final Timestamp? createdAt;
final String? description;
NotificationEntity(
{this.notificationId,
this.uid,
this.otherUid,
this.username,
this.userProfile,
this.createdAt,
this.description,
});
factory NotificationEntity.fromSnapshot(DocumentSnapshot snapshot) {
var snapshotMap = snapshot.data() as Map<String, dynamic>;
return NotificationEntity(
notificationId: snapshot.get('notificationId'),
uid: snapshot.get('uid'),
otherUid: snapshot.get('otherUid'),
username: snapshot.get('username'),
userProfile: snapshot.get('userProfile'),
description: snapshot.get('description'),
createdAt: snapshot.get("createdAt"),
);
}
Map<String, dynamic> toDocument() {
return {
"uid": uid,
"otherUid": otherUid,
"username": username,
"notificationId": notificationId,
"userProfile": userProfile,
"description": description,
"createdAt": createdAt,
};
}
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:whatsapp_clone_app/features/app/const/firebase_collection_const.dart';
import 'package:whatsapp_clone_app/features/notifications/entities/notification_entity.dart';
class NotificationRepository {
final FirebaseFirestore fireStore;
NotificationRepository({required this.fireStore});
Future<void> generateNotification(NotificationEntity notification) async {
final notificationCollection =
fireStore.collection(FirebaseCollectionConst.users)
.doc(notification.otherUid)
.collection(FirebaseCollectionConst.notifications);
final String notificationId = notificationCollection.doc().id;
final notificationData = NotificationEntity(
notificationId: notificationId,
uid: notification.uid,
otherUid: notification.otherUid,
username: notification.username,
userProfile: notification.userProfile,
createdAt: Timestamp.now(),
description: notification.description
).toDocument();
try {
await notificationCollection.doc(notificationId).set(notificationData);
} catch (e) {
print("error occur while generating notification $e");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment