Как отправить уведомление во флаттере с помощью FCM
Я пытаюсь отправить уведомление от firebase с помощью FCM, следуя коду на YouTube. При запуске системы обнаружил такую ошибку:
[ОШИБКА: flutter / lib / ui / ui_dart_state.cc(199)] Необработанное исключение: PlatformException (ошибка, NotificationChannelGroup не существует, значение null, java.lang.IllegalArgumentException: NotificationChannelGroup не существует
В консоли firebase статус завершен, но в эмулятор не отправлено. Кто-нибудь может мне помочь, в чем проблема?
код main.dart
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 код
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 файл
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>
3 ответа
Ошибка возникает из-за того, что вы передаете идентификатор группы в канал уведомлений, но не создали группу каналов уведомлений.
Решение:
Если вам не нужна группа каналов уведомлений:
Избавиться от ошибки можно, убрав необязательный
groupId
из вашего объекта AndroidNotificationChannel .Обновите свой
channel
к этому:const AndroidNotificationChannel channel = AndroidNotificationChannel( 'high_importance_channel', "High Importance Notifcations", "This channel is used important notification");
Если вам нужна группа каналов уведомлений:
Создайте группу каналов уведомлений и назначьте ей тот же идентификатор группы, который вы добавили в канал уведомлений.
Вот фрагмент кода из
flutter_local_notifications
пример пакета , показывающий это.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));
если вам это не нужно, вы можете удалить "groupId:" Notification_group "" в puchNotification.dart. моя проблема решается этим методом.
«high_importance_channel» я только что добавил эту строку в канал уведомлений Android, у меня это сработало