New user
New user

Reputation: 147

How to push notification in flutter using FCM

I'm trying to push a notification from firebase using FCM by following the code in the youtube. When run the system, I found this error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(error, NotificationChannelGroup doesn't exist, null, java.lang.IllegalArgumentException: NotificationChannelGroup doesn't exist

In the firebase console, the status is complete, but it did not push to the emulator. Anyone can help me what is the problem?

main.dart code

import 'package:flutter/material.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:monger_app/WelcomeScreen/login.dart';
import 'package:monger_app/WelcomeScreen/signup.dart';
import 'package:monger_app/WelcomeScreen/welcome_screen.dart';
import 'package:monger_app/localization/demo_localization.dart';
import 'package:monger_app/page/pushNotification.dart';
import 'package:monger_app/page/root.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
import 'localization/localization_constants.dart';



void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  //FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  return runApp(ChangeNotifierProvider(
    child: MyApp(),
    create: (BuildContext context) => ThemeProvider(isDarkMode: true),
  ));
}

class MyApp extends StatefulWidget {

  static void setLocale(BuildContext context, Locale locale){
    _MyAppState state = context.findAncestorStateOfType<_MyAppState>();
    state.setLocale(locale);
  }
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  Locale _locale;

  void setLocale(Locale locale){
    setState(() {
      _locale = locale;
    });
  }

  FirebaseNotifcation firebase;

  handleAsync() async {
    await firebase.initialize();

    String token = await firebase.getToken();
    print("Firebase token : $token");
  }

  @override
  void initState() {
    super.initState();
    firebase = FirebaseNotifcation();
    handleAsync();
  }

 @override
  void didChangeDependencies() {
    getLocale().then((locale){
      setState(() {
        this._locale = locale;
      });
    });
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeProvider>(
      builder: (context, themeProvider, child){
        if (_locale == null) {
          return Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
        } else {
          return MaterialApp(
            theme: themeProvider.getTheme,
            locale: _locale,
            supportedLocales: [
              Locale('en', 'US'),
              Locale('id', 'ID'),
              Locale('zh', 'CN'),
            ],
            localizationsDelegates: [
              DemoLocalization.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            localeResolutionCallback: (deviceLocale, supportedLocales){
              for (var locale in supportedLocales) {
                if (locale.languageCode == deviceLocale.languageCode && locale.countryCode == deviceLocale.countryCode) {
                  return deviceLocale;
                }
              }
              return supportedLocales.first;
            },
            debugShowCheckedModeBanner: false,
            home:

            WelcomeScreen(),

            routes: <String,WidgetBuilder>{

              "SignIn" : (BuildContext context)=>LoginPage(),
              "SignUp":(BuildContext context)=>SignUpPage(),
              "start":(BuildContext context)=>Root(),
              "welcome":(BuildContext context)=>WelcomeScreen(),
            },

          );
        }
      }
    );
  }
}

puchNotification.dart code

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance_channel',
    "High Importance Notifcations",
    "This channel is used important notification",
    groupId: "Notification_group");

final FlutterLocalNotificationsPlugin flutterLocalNotificationplugin =
FlutterLocalNotificationsPlugin();

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Handling a background message : ${message.messageId}");
  print(message.data);
}

class FirebaseNotifcation {
  initialize() async {
    await Firebase.initializeApp();
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    await flutterLocalNotificationplugin
        .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
    var intializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettings =
    InitializationSettings(android: intializationSettingsAndroid);

    flutterLocalNotificationplugin.initialize(initializationSettings);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      if (notification != null && android != null) {
        AndroidNotificationDetails notificationDetails =
        AndroidNotificationDetails(
            channel.id, channel.name, channel.description,
            importance: Importance.max,
            priority: Priority.high,
            groupKey: channel.groupId);
        NotificationDetails notificationDetailsPlatformSpefics =
        NotificationDetails(android: notificationDetails);
        flutterLocalNotificationplugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            notificationDetailsPlatformSpefics);
      }

      List<ActiveNotification> activeNotifications =
      await flutterLocalNotificationplugin
          .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
          ?.getActiveNotifications();
      if (activeNotifications.length > 0) {
        List<String> lines =
        activeNotifications.map((e) => e.title.toString()).toList();
        InboxStyleInformation inboxStyleInformation = InboxStyleInformation(
            lines,
            contentTitle: "${activeNotifications.length - 1} messages",
            summaryText: "${activeNotifications.length - 1} messages");
        AndroidNotificationDetails groupNotificationDetails =
        AndroidNotificationDetails(
            channel.id, channel.name, channel.description,
            styleInformation: inboxStyleInformation,
            setAsGroupSummary: true,
            groupKey: channel.groupId);

        NotificationDetails groupNotificationDetailsPlatformSpefics =
        NotificationDetails(android: groupNotificationDetails);
        await flutterLocalNotificationplugin.show(
            0, '', '', groupNotificationDetailsPlatformSpefics);
      }
    });
  }

  Future<String> getToken() async {
    String token = await FirebaseMessaging.instance.getToken();
    print(token);
    return token;
  }

  subscribeToTopic(String topic) async {
    await FirebaseMessaging.instance.subscribeToTopic(topic);
  }
}

build.gradle file

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

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

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

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

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 30

    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.monger_app"
        minSdkVersion 21
        targetSdkVersion 30
        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 '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation "com.google.firebase:firebase-messaging:20.1.0"
}

apply plugin: 'com.google.gms.google-services'

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.monger_app">

   <application
       tools:replace="android:label"
        android:name=".Application"
        android:label="MONGE"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

Complete Status Firebase

Upvotes: 1

Views: 2459

Answers (3)

ahmar jani
ahmar jani

Reputation: 11

'high_importance_channel' i just added this line in Android Notification Channel it worked work me

Upvotes: 0

Ramazan Timur
Ramazan Timur

Reputation: 91

If you don't need it, you can delete groupId: "Notification_group" in pushNotification.dart. My problem is solved by this method.

Upvotes: 1

Victor Eronmosele
Victor Eronmosele

Reputation: 7686

The error is showing up because you're passing a group id to the notification channel but you did not create a notification channel group.

Solution:

  • If you don't need a notification channel group:

    You can get rid of the error by removing the optional groupId parameter from your AndroidNotificationChannel object.

    Update your channel to this:

    const AndroidNotificationChannel channel = AndroidNotificationChannel(
     'high_importance_channel',
     "High Importance Notifcations",
     "This channel is used important notification");
    
  • If you do need a notification channel group:

    Create a notification channel group and assign it the same group id you added to the notification channel.

    Here is a code snippet from the flutter_local_notifications package example, showing this.

    const String channelGroupId = 'your channel group id';
    // create the group first
    const AndroidNotificationChannelGroup androidNotificationChannelGroup =
     AndroidNotificationChannelGroup(
         channelGroupId, 'your channel group name',
         description: 'your channel group description');
    await flutterLocalNotificationsPlugin
     .resolvePlatformSpecificImplementation<
         AndroidFlutterLocalNotificationsPlugin>()!
     .createNotificationChannelGroup(androidNotificationChannelGroup);
    
    // create channels associated with the group
    await flutterLocalNotificationsPlugin
     .resolvePlatformSpecificImplementation<
         AndroidFlutterLocalNotificationsPlugin>()!
     .createNotificationChannel(const AndroidNotificationChannel(
         'grouped channel id 1',
         'grouped channel name 1',
         'grouped channel description 1',
         groupId: channelGroupId));
    

Upvotes: 3

Related Questions