skip to Main Content

I am trying to make a background notification system using Workmanager and flutter_local_notifications, when I tried to run the app, I got an error that firebase wasn’t initalized.

I’ve tried to initialized firebase in the function, but still getting the same problem.

does anyone know how to fix it

Here’s the main.dart

import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart' as firestore;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:foodwasteproject/AddScreens.dart';
import 'package:foodwasteproject/HomePager.dart';
import 'package:foodwasteproject/Loginandsignup.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
import 'package:openfoodfacts/openfoodfacts.dart';
import 'package:workmanager/workmanager.dart';

import 'coverpage.dart';
import 'firebase_options.dart';
import 'notifications.dart';

void callbackdispatch() {
  Workmanager().executeTask((task, inputData) async{
    Notifications Nservice = Notifications();
    int daysBetween(DateTime from, DateTime to) {
      from = DateTime(from.year, from.month, from.day);
      to = DateTime(to.year, to.month, to.day);
      return (to.difference(from).inHours / 24).round();
    }
    await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform
    );
    List x = [];
    await firestore.FirebaseFirestore.instance.collection("Users").doc("${FirebaseAuth.instance.currentUser?.uid}").get().then((value) {
      int? remindBefore = value.data()?["remindbefore"];
      print(remindBefore);
      if (remindBefore != null) {
        return firestore.FirebaseFirestore.instance.collection("Users").doc("${FirebaseAuth.instance.currentUser?.uid}").collection("Items").get().then((value) {
          for (var element in value.docs) {
            x.add(element.data()["Name"]);
            if (daysBetween(DateTime.now(), element.data()["Expiry"].toDate()) <= remindBefore) {
              print("Expired");
            }
          }
        });
      }
    });
    Nservice.sendNotifications("Food Expiry Alert", "The following food items are about to expire: ${x.join("n")}");
    // else if (task == "simpleTask2") {
    //   const apiKey = "AIzaSyD2f8buzXCPsv62E89LAL5JHmCkVgV86dk";
    //   Future<String?> geminiNotifications() async {
    //     final model = GenerativeModel(apiKey: apiKey, model: 'gemini-1.0-pro');
    //     final content = Content.text(
    //         "Imagine you're a food waste expert, give an advice on how to prevent food waste, make it short and sweet");
    //     final response = await model.generateContent(
    //         [content]
    //     );
    //     return response.text;
    //   }
    //   Notifications Nservice = Notifications();
    //   String? result = await geminiNotifications();
    //   Nservice.Initializenotifications();
    //   Nservice.sendNotifications("Here's a tip from the AI", result!);
    // }
    return Future.value(true);
  });
}

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform
  );
  OpenFoodAPIConfiguration.userAgent = UserAgent(
    name: 'CookingAgainstWaste',
    version: '3.0.0',
    system: 'Flutter',
    comment: 'IDK what to put here',
  );
  Workmanager().initialize(
    callbackdispatch,
    isInDebugMode: true,
  );
  Workmanager().registerPeriodicTask(
    "1",
    "simpleTask1",
    frequency: Duration(minutes: 15),
  );

  // Register the second periodic task
  Workmanager().registerPeriodicTask(
    "2",
    "simpleTask2",
    frequency: Duration(hours: 3),
  );
  runApp(const MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(430, 932),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (_, child){
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            elevatedButtonTheme: ElevatedButtonThemeData(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                foregroundColor: Colors.white
              )
            ),
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
            useMaterial3: true,
            textTheme: GoogleFonts.playfairDisplayTextTheme(
              Theme.of(context).textTheme
            ),
          ),
          initialRoute: FirebaseAuth.instance.currentUser != null? "/home":"/"
          ,
          routes: {
            "/": (context) => const Cover(),
            "/login": (context) => const Login(),
            "/signup": (context) => const Signup(),
            "/home": (context) => const Home(),
            "/options": (context) => const addOptions(),
            "/am": (context) => const addManualy(),
            "/ar": (context) => const AddRecipies(),
            "/makefood": (context) => const RecipeSteps(),
            "/settings": (context) => const Settings(),
            "/myrecipies": (context) => const MyRecipies(),
          },
        );
      },
    );
  }
}

2

Answers


  1. The issue might be related to the Firebase initialization. In your code, you’re initializing Firebase twice – once in the main() function and once in the callbackdispatch() function.

    Also, take a look at the FirebaseAuth.
    I think you are trying to use it, but it isn’t initialized.

    Try doing something like this:

     app = await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
      auth = FirebaseAuth.instanceFor(app: app);
    

    then you can just check the current user like this:

    auth.currentUser != null? "/home":"/";
    
    Login or Signup to reply.
  2. void main() {
     await Firebase.initializeApp(
     options: DefaultFirebaseOptions.currentPlatform,
     );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search