如何在后台函数中初始化 Firebase

问题描述 投票:0回答:1

我正在尝试使用 Workmanager 和 flutter_local_notifications 制作后台通知系统,当我尝试运行该应用程序时,出现 Firebase 未初始化的错误。

我尝试在函数中初始化firebase,但仍然遇到同样的问题。

有谁知道如何修复吗

这是

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(),
          },
        );
      },
    );
  }
}
flutter firebase google-cloud-firestore
1个回答
0
投票

该问题可能与 Firebase 初始化有关。在您的代码中,您将初始化 Firebase 两次 - 一次在

main()
函数中,一次在
callbackdispatch()
函数中。

另外,看看

FirebaseAuth
。 我认为您正在尝试使用它,但它尚未初始化。

尝试做这样的事情:

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

然后你可以像这样检查当前用户:

auth.currentUser != null? "/home":"/";
© www.soinside.com 2019 - 2024. All rights reserved.