skip to Main Content

i am using firebase cloud messaging to send a push notification.I want to schedule the notification using workmanager package.I have also tried with zoneschedule method of flutter local notification package ,but it gives the notification when the app run in first time.
But it gives following errors:

D/EGL_emulation( 6738): eglCreateContext: 0xe91a9600: maj 2 min 0 rcv 2
D/EGL_emulation( 6738): eglCreateContext: 0xe91a9a60: maj 2 min 0 rcv 2
D/HostConnection( 6738): HostConnection::get() New Host Connection established 0xe919c6a0, tid 6952
D/HostConnection( 6738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_YUV_Cache ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
D/EGL_emulation( 6738): eglMakeCurrent: 0xe91a9a60: ver 2 0 (tinfo 0xcad2bc10) (first time)
E/BackgroundWorker( 6738): errorCode: error, errorMessage: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
I/WM-WorkerWrapper( 6738): Worker result FAILURE for Work [ id=0099bb1f-670e-4711-9fc2-7b95f118ca6e, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]

main .dart

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      await FlutterDownloader.initialize(debug: true);
      tz.initializeTimeZones();
      await Workmanager().initialize(callbackDispatcher,isInDebugMode: true);
      await GetStorage.init();
      runApp(const MyApp());
    }
@pragma('vm:entry-point')
Future<void> backgroundMessageHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("backgroundMessageHandler");
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      locale: HandleLocale().getLocale(),
      translations: LocaleString(),
      showSemanticsDebugger: false,
      debugShowCheckedModeBanner: false,
      theme: Themes().lightTheme,
      darkTheme: Themes().darkTheme,
      themeMode: ThemeServices().getThemeMode(),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  myController controller = Get.put(myController());

  @override
  void initState() {
    super.initState();

    // Initialize Firebase and local notifications

    // Schedule the background task to run at a specific time
    NotificationHandler().getToken().then((value){
      print(value);
    });
    Workmanager().registerOneOffTask(
      '1',
      'simpleTask',
      initialDelay:
          const Duration(seconds: 10), // Delay before running the task
    );

    NotificationHandler().initMessage(context);
    NotificationHandler().interactMessage(context);
    isAlreadyLoggedIn();
  }

  Future<void> isAlreadyLoggedIn() async {
    final value = await controller.getUserInfo();
    print(value.toList()); // Use the safe navigation operator "?"
    if (value.isEmpty) {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => const LoginPage()));
    }
  }

  @override
  Widget build(BuildContext context) {
    return const PageHandler();
  }
}

callbackdispatcher.dart

void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) async {
    // This is where you can schedule your notifications at the desired time
    final token = await NotificationHandler().getToken();
    NotificationHandler().scheduleNotification(token);
    return Future.value(true);
  });
}

root level build.gradle:

buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        
        classpath 'com.android.tools.build:gradle:7.3.0'
        classpath"com.google.gms:google-services:4.3.15"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

tasks.register("clean", Delete) {
    delete rootProject.buildDir
}

android/build.gradle

plugins {
    id "com.android.application"
    id "kotlin-android"
    id "dev.flutter.flutter-gradle-plugin"
}

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

android {
    namespace "com.example.income_and_expenditure_app"
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.income_and_expenditure_app"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}
apply plugin:"com.google.gms.google-services"
apply plugin:'com.android.application'
// apply plugin:'com.google.gms.google-services'
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
  implementation("com.google.firebase:firebase-analytics-ktx")
  
  implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
   implementation 'com.google.firebase:firebase-auth'
}

2

Answers


  1. The error message you provided indicates that there’s an issue related to Firebase initialization and Firebase Cloud Messaging (FCM) within your Flutter application when you’re trying to schedule push notifications using the Workmanager package. Specifically, the error message "No Firebase App ‘[DEFAULT]’ has been created – call Firebase.initializeApp()" suggests that Firebase hasn’t been properly initialized in your app.

    Here are some steps you can take to resolve this issue:

    1. Initialize Firebase: Make sure that you have properly initialized Firebase in your Flutter app. To do this, you should have a call to Firebase.initializeApp() in your app’s main function or at the start of your app before any Firebase-related functionality is used.

      Example:

      void main() async {
        WidgetsFlutterBinding.ensureInitialized();
        await Firebase.initializeApp();
        runApp(MyApp());
      }
      

      Ensure that you have the necessary Firebase configurations set up in your Flutter project, such as google-services.json for Android or GoogleService-Info.plist for iOS.

    2. Check Firebase Configuration: Verify that your Firebase project is correctly set up in the Firebase Console, and ensure that your project has been linked to your Flutter app.

    3. Check Dependencies: Confirm that you have the necessary dependencies and versions of the Firebase and Flutter packages in your pubspec.yaml file. Ensure they are up to date.

    4. Check AndroidManifest.xml: In the case of Android, make sure you have included the necessary Firebase-related configurations in your AndroidManifest.xml file.

    5. Check Firebase Messaging Setup: Ensure that you have set up Firebase Cloud Messaging correctly in your Flutter app. You should have the necessary initialization code and FCM token retrieval code.

    6. Testing on Real Devices: Sometimes, Firebase and FCM features may not work correctly in emulator/simulator environments. Try testing your push notifications on real Android and iOS devices.

    7. Plugin Compatibility: Ensure that the Workmanager package, Firebase packages, and Flutter Local Notifications package (if used) are compatible and updated to the latest versions.

    8. Clean and Rebuild: Try cleaning and rebuilding your Flutter project to ensure that there are no caching issues.

    If you have already addressed these steps and are still encountering the issue, it’s possible that there may be a specific issue with how your Flutter project is configured or how you are using these packages. In that case, you may need to provide more details about your code and configurations for further assistance.

    Remember to thoroughly test your app on both Android and iOS devices to ensure that push notifications are functioning as expected.

    Login or Signup to reply.
  2. You are getting the error No Firebase App '[DEFAULT]' has been created which means you haven’t configured your Firebase App properly.
    Please make sure that you signed into your Firebase project using your Google account. Your also need to install the Firebase CLI to run the flutterfire configure command in terminal to generate firebase_options.dart configuration file.
    For more information about Firebase for Flutter (iOS & Android) please see this source

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search