Local Notification

Resolved

I have tried the following code snippet to send local notification, but for some reason it is not working, can anyone tell me what is wrong here?

import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:awesome_notifications/awesome_notifications.dart';

Future<void> newNotification(DocumentReference? restaurantUid) async {
  // Get a reference to the Firestore collection "orders"
  CollectionReference ordersCollection =
      FirebaseFirestore.instance.collection('orders');

  // Query the orders collection for documents matching the conditions
  QuerySnapshot querySnapshot = await ordersCollection
      .where('restaurant', isEqualTo: restaurantUid)
      .where('order_received', isEqualTo: true)
      .where('delivered', isEqualTo: false)
      .get();

  // Check if there are any orders matching the conditions
  if (querySnapshot.size > 0) {
    for (QueryDocumentSnapshot ordersDoc in querySnapshot.docs) {
      // Extract the order ID from the document ID
      String orderId = ordersDoc.id;

      // Get the reference to the restaurant that received the order
      DocumentReference restaurantRef = ordersDoc.get('restaurant');

      // Get the restaurant data from the document
      DocumentSnapshot restaurantDoc = await restaurantRef.get();

      // Check if the restaurant document exists and has valid data
      if (restaurantDoc.exists) {
        // Customize the notification content based on the order data
        String title = "Order #$orderId Received!";
        String body = "Your restaurant has received a new order.";

        // Define the notification channel
        NotificationChannel channel = NotificationChannel(
          channelKey: 'order_notification',
          channelName: 'Order Notification',
          channelDescription: 'Notification for new order',
          importance: NotificationImportance.High,
          channelShowBadge: true,
          locked: false,
        );

        // Initialize the AwesomeNotifications plugin with the defined channel
        AwesomeNotifications().initialize(null, [channel]);

        // Schedule the notification to be sent after 5 seconds of order creation
        int notificationId =
            orderId.hashCode; // Use the order ID as the notification ID

        // Get the 'created_at' timestamp from the order document
        Timestamp createdAtTimestamp = ordersDoc.get('created_at');

        // Convert the timestamp to a DateTime object
        DateTime createdAtDateTime = createdAtTimestamp.toDate();

        // Add a delay of 5 seconds to the 'created_at' time
        DateTime scheduledTime = createdAtDateTime.add(Duration(seconds: 5));

        // Schedule the notification using the Awesome Notifications plugin
        await AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: notificationId,
            channelKey: 'order_notification',
            title: title,
            body: body,
          ),
          schedule: NotificationCalendar.fromDate(
            date: scheduledTime,
            allowWhileIdle: true,
            repeats: true,
          ), // Set to false to send the notification only once
        );
      }
    }
  }
}
1
7 replies