我在main内部初始化了Firebase,需要在workmanager内部访问用户数据,为用户提供个性化通知,但workmanager由于某种原因与Firebase初始化同时同步工作,所以导致了这个问题。
我尝试添加一个像这样的简单if语句来解决问题,并添加两次初始化,一次用于main,一次用于工作管理器,但并没有解决问题。
输出启动 firebase 初始化打印了两次并且出现此错误: lStateException:FirebaseApp 名称 [DEFAULT] 已存在!,IllegalStateException,原因:null,Stacktrace:java.lang.IllegalStateException:FirebaseApp 名称 [DEFAULT] 已存在!
// AuthService code
// initialize firebase
static Future initializeFirebase() async {
if (!isInitialized && Firebase.apps.isEmpty) {
print('start firebase initializion');
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
isInitialized = true;
} else {
print('firebase is already initialized');
}
}
...
/////////////////////////////////////////////////////////////
//here is main code:
Future<void> main() async {
// initialize firebase
WidgetsFlutterBinding.ensureInitialized();
await AuthService.initializeFirebase();
// preferred screen orientations
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
// initialize notifications
NotificationService().initNotification();
//initialize workmanager
Workmanager().initialize(callbackDispatcher);
...
void callbackDispatcher() async {
print('entered...');
// initialize firebase
WidgetsFlutterBinding.ensureInitialized();
await AuthService.initializeFirebase();
//////////// access data for notification ////////////////
final user = FirebaseAuth.instance.currentUser;
String uid = user!.uid;
//child collection
final CollectionReference childCollection =
FirebaseFirestore.instance.collection('child');
//morning collection
CollectionReference schedule_morning =
childCollection.doc(uid).collection('schedule_morning');
final QuerySnapshot morning_tasks = await schedule_morning.get();
//noon collection
CollectionReference schedule_noon =
childCollection.doc(uid).collection('schedule_noon');
final QuerySnapshot noon_tasks = await schedule_noon.get();
//night collection
CollectionReference schedule_night =
childCollection.doc(uid).collection('schedule_night');
final QuerySnapshot night_tasks = await schedule_night.get();
//to get user name
final DocumentSnapshot userDoc = await childCollection.doc(uid).get();
if (userDoc.exists) {
Map<String, dynamic> userData = userDoc.data() as Map<String, dynamic>;
final String userName = userData['name'];
// notify the user
if (DateTime.now().hour == 06 && morning_tasks.size > 0) {
Workmanager().executeTask((taskName, inputData) {
NotificationService().showNotification(
title: 'todays tasks',
body: '$userName do not forget your morning tasks',
);
return Future.value(true);
});
}
...
首先,您不必手动检查 firebase 是否已初始化。所以只需调用该函数一次即可。
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
要解决您的问题,请从项目根文件夹运行这些命令,
flutter pub add firebase_core firebase_messaging
# Install the CLI if not already done so
dart pub global activate flutterfire_cli
# Run the `configure` command, select a Firebase project and platforms
flutterfire configure
欲了解更多信息,请访问此链接。