Shi*_*roe 47 node.js firebase flutter firebase-cloud-messaging
我正在尝试从 Node.js API 向 Flutter 应用程序发送通知。\n首先,我想让我的应用程序能够接收来自 Firebase 的通知。
\n但是,当我初始化App时,我遇到了一个问题:
\n\n\nPlatformException (PlatformException(null-error, 主机平台\n非空返回值返回空值。, null, null))
\n
在控制台中:
\nE/flutter (25357): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: PlatformException(null-error, Host platform returned null value for non-null return value., null, null)\nE/flutter (25357): #0 FirebaseCoreHostApi.optionsFromResource (package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart:250)\npackage:firebase_core_platform_interface/\xe2\x80\xa6/pigeon/messages.pigeon.dart:1\nE/flutter (25357): <asynchronous suspension>\nE/flutter (25357): #1 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:89)\npackage:firebase_core_platform_interface/\xe2\x80\xa6/method_channel/method_channel_firebase.dart:1\nE/flutter (25357): <asynchronous suspension>\nE/flutter (25357): #2 Firebase.initializeApp (package:firebase_core/src/firebase.dart:40)\npackage:firebase_core/src/firebase.dart:1\nE/flutter (25357): <asynchronous suspension>\nE/flutter (25357): #3 main (package:notifappfcm/main.dart:13)\npackage:notifappfcm/main.dart:1\nRun Code Online (Sandbox Code Playgroud)\n我一直在寻找解决这个问题的办法,但实在找不到。
\n这是我的应用程序代码:
\n主程序.dart
\nimport \'package:firebase_messaging/firebase_messaging.dart\';\nimport \'package:flutter/material.dart\';\nimport \'package:firebase_core/firebase_core.dart\';\nimport \'mainscreen.dart\';\n\nFuture<void> _firebadeMessagingBackgroundHandler(RemoteMessage message) async {\n await Firebase.initializeApp(); // options: DefaultFirebaseConfig.platformOptions\n print(\'Handling a background message ${message.messageId}\');\n}\n\nvoid main() async {\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n\n FirebaseMessaging.onBackgroundMessage(_firebadeMessagingBackgroundHandler);\n\n runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: \'Flutter Demo\',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: const MainScreen(),\n );\n }\n}\n\nclass MyHomePage extends StatefulWidget {\n const MyHomePage({Key? key, required this.title}) : super(key: key);\n\n final String title;\n\n @override\n State<MyHomePage> createState() => _MyHomePageState();\n}\n\nclass _MyHomePageState extends State<MyHomePage> {\n int _counter = 0;\n\n \n void _incrementCounter() {\n setState(() {\n _counter++;\n });\n }\n\n @override\n void initState() {\n super.initState();\n }\n\n \n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text(widget.title),\n ),\n body: Center(\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: <Widget>[\n const Text(\n \'You have pushed the button this many times:\',\n ),\n Text(\n \'$_counter\',\n style: Theme.of(context).textTheme.headline4,\n ),\n ],\n ),\n ),\n floatingActionButton: FloatingActionButton(\n onPressed: _incrementCounter,\n tooltip: \'Increment\',\n child: const Icon(Icons.add),\n ),\n );\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n主屏幕.dart
\nimport \'package:firebase_messaging/firebase_messaging.dart\';\nimport \'package:flutter/foundation.dart\';\nimport \'package:flutter/material.dart\';\nimport \'package:flutter_local_notifications/flutter_local_notifications.dart\';\n\nclass MainScreen extends StatefulWidget {\n const MainScreen({Key? key}) : super(key: key);\n\n @override\n State<MainScreen> createState() => _MainScreenState();\n}\n\nclass _MainScreenState extends State<MainScreen> {\n late AndroidNotificationChannel channel;\n late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;\n\n @override\n void initState() {\n super.initState();\n\n requestPermission();\n loadFCM();\n listenFCM();\n // Get device\'s notification token\n getToken();\n }\n\n\n void getToken() async {\n await FirebaseMessaging.instance.getToken().then((token) => print(token));\n }\n\n void requestPermission() async {\n FirebaseMessaging messaging = FirebaseMessaging.instance;\n\n NotificationSettings settings = await messaging.requestPermission(\n alert: true,\n announcement: false,\n badge: true,\n carPlay: false,\n criticalAlert: false,\n provisional: false,\n sound: true,\n );\n\n if (settings.authorizationStatus == AuthorizationStatus.authorized) {\n print(\'User granted permission\');\n } else if (settings.authorizationStatus ==\n AuthorizationStatus.provisional) {\n print(\'User granted provisional permission\');\n } else {\n print(\'User declined or has not accepted permission\');\n }\n }\n\n void listenFCM() async {\n FirebaseMessaging.onMessage.listen((RemoteMessage message) {\n RemoteNotification? notification = message.notification;\n AndroidNotification? android = message.notification?.android;\n if (notification != null && android != null && !kIsWeb) {\n flutterLocalNotificationsPlugin.show(\n notification.hashCode,\n notification.title,\n notification.body,\n NotificationDetails(\n android: AndroidNotificationDetails(channel.id, channel.name,\n // ignore: todo\n // TODO add a proper drawable resource to android (now using one that already exists)\n icon: \'launch_background\')));\n }\n });\n }\n\n void loadFCM() async {\n if (!kIsWeb) {\n channel = const AndroidNotificationChannel(\n \'high_importance_channel\', // id\n \'High Importance Notifications\', // title\n importance: Importance.high,\n enableVibration: true,\n );\n\n flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();\n\n /// Create an Android Notification Channel.\n ///\n /// We use this channel in the `AndroidManifest.xml` file to override the\n /// default FCM channel to enable heads up notifications.\n await flutterLocalNotificationsPlugin\n .resolvePlatformSpecificImplementation<\n AndroidFlutterLocalNotificationsPlugin>()\n ?.createNotificationChannel(channel);\n\n /// Update the iOS foreground notification presentation options to allow\n /// heads up notifications.\n await FirebaseMessaging.instance\n .setForegroundNotificationPresentationOptions(\n alert: true,\n badge: true,\n sound: true,\n );\n }\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: Container(\n height: 40,\n width: 200,\n color: Colors.red,\n ),\n ));\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
小智 77
确保您已在项目级build.gradle文件和应用程序级build.gradle文件中添加 Firebase SDK 依赖项
要在项目级别build.gradle中添加的依赖项:
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
...
// Add this line
classpath 'com.google.gms:google-services:4.3.13'
}
}
allprojects {
...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
...
}
}
Run Code Online (Sandbox Code Playgroud)
要在应用程序级别build.gradle中添加的依赖项:
apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'
dependencies {
// Import the Firebase BoM
implementation platform('com.google.firebase:firebase-bom:30.2.0')
// Add the dependency for the Firebase SDK for Google Analytics
// When using the BoM, don't specify versions in Firebase dependencies
implementation 'com.google.firebase:firebase-analytics'
// Add the dependencies for any other desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
}
Run Code Online (Sandbox Code Playgroud)
Elm*_*mar 42
注意力。如上所述手动更改 build.gradle 文件不是解决方案。它要么不起作用,要么每次构建都会在使用已弃用的依赖项时生成大量警告。正确的解决方案是这样的:Firebase 应该像下面这样初始化:
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
Run Code Online (Sandbox Code Playgroud)
为此,您需要从命令行/终端运行一些命令:
// Add firebase core into your project
flutter pub add firebase_core
// Generate firebase options file
flutterfire configure
Run Code Online (Sandbox Code Playgroud)
然后您需要将这些导入您的 .dart 文件中:
// Import firebase core and generated file
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Run Code Online (Sandbox Code Playgroud)
详细信息您可以参考这里。
Kur*_*urt 15
确保您的计算机中有这些设置android/build.gradle
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// ...
// Add the following line:
classpath 'com.google.gms:google-services:4.3.13' // Google Services plugin
}
}
allprojects {
// ...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的android/app/build.gradle:
apply plugin: 'com.android.application'
// Add the following line:
apply plugin: 'com.google.gms.google-services' // Google Services plugin
android {
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以按照此处的步骤操作
并且不要忘记从 firebase 项目控制台下载 google-service.json ,并将其放入 android/app 文件夹中。
小智 9
从:
await Firebase.initializeApp();
Run Code Online (Sandbox Code Playgroud)
到:
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
Run Code Online (Sandbox Code Playgroud)
对我有用!
有时 FlutterFire cli 无法更新 build.gradle 文件,因此您会收到上述错误
在项目级别 build.gradle 添加 firebase 依赖项
dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
}
Run Code Online (Sandbox Code Playgroud)
在应用程序级别 build.gradle 文件中应用 firebase 插件
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
Run Code Online (Sandbox Code Playgroud)
小智 5
我已将类路径从类路径更改com.google.gms:google-services:4.4.0为类路径com.google.gms:google-services:4.3.15并为我工作。
| 归档时间: |
|
| 查看次数: |
98489 次 |
| 最近记录: |