我正在尝试从Node.js API向Flutter应用程序发送通知。首先,我想让我的应用程序能够接收来自Firebase的通知。
但是,当我初始化App时,我遇到了一个问题:
PlatformException(空错误,主机平台为非空返回值返回空值。,null,null))
在控制台中
E/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)
E/flutter (25357): #0 FirebaseCoreHostApi.optionsFromResource (package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart:250)
package:firebase_core_platform_interface/…/pigeon/messages.pigeon.dart:1
E/flutter (25357): <asynchronous suspension>
E/flutter (25357): #1 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:89)
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:1
E/flutter (25357): <asynchronous suspension>
E/flutter (25357): #2 Firebase.initializeApp (package:firebase_core/src/firebase.dart:40)
package:firebase_core/src/firebase.dart:1
E/flutter (25357): <asynchronous suspension>
E/flutter (25357): #3 main (package:notifappfcm/main.dart:13)
package:notifappfcm/main.dart:1
我一直在寻找解决这个问题的方法,但我真的找不到。
这是我的申请代码:
main.dart
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'mainscreen.dart';
Future<void> _firebadeMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(); // options: DefaultFirebaseConfig.platformOptions
print('Handling a background message ${message.messageId}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebadeMessagingBackgroundHandler);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MainScreen(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
mainscreen.dart
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class MainScreen extends StatefulWidget {
const MainScreen({Key? key}) : super(key: key);
@override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
late AndroidNotificationChannel channel;
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
@override
void initState() {
super.initState();
requestPermission();
loadFCM();
listenFCM();
// Get device's notification token
getToken();
}
void getToken() async {
await FirebaseMessaging.instance.getToken().then((token) => print(token));
}
void requestPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
} else if (settings.authorizationStatus ==
AuthorizationStatus.provisional) {
print('User granted provisional permission');
} else {
print('User declined or has not accepted permission');
}
}
void listenFCM() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
// ignore: todo
// TODO add a proper drawable resource to android (now using one that already exists)
icon: 'launch_background')));
}
});
}
void loadFCM() async {
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.high,
enableVibration: true,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 40,
width: 200,
color: Colors.red,
),
));
}
}
7条答案
按热度按时间f1tvaqid1#
确保已在项目级别build.gradle文件和应用程序级别build.gradle文件中添加Firebase SDK依赖项
要添加到项目级别build.gradle中的依赖项:
要添加到应用程序级别build.gradle中的依赖项:
sc4hvdpw2#
确保您的
android/build.gradle
中有这些设置然后在
android/app/build.gradle
中:您可以按照以下步骤操作
别忘了从firebase项目控制台下载google-service.json,并将其放入android/app文件夹。
zujrkrfu3#
有时FlutterFire cli无法更新build.gradle文件,因此您会收到上述错误
在项目级别build.gradle中,将firebase依赖项添加为
在应用级build.gradle文件中,将firebase插件应用为
ca1c2owp4#
被接受的答案仍然肯定有效,但它需要手动操作,加上添加哪个Google服务版本和Firebase BOM的不确定性。
我建议使用FlutterFire CLI配置项目并自动设置所有这些build. gradle依赖项。
Official configuration setup can be found here.
qrjkbowd5#
注意。如上所述手动更改build.gradle文件不是一个解决方案。它要么不起作用,要么每个构建都将生成大量警告,因为使用了过时的依赖项。正确的解决方案如下:Firebase应按如下方式初始化:
为此,您需要从命令行/终端运行一些命令:
详情请参阅此处。
2uluyalo6#
如果你在ios中配置flutter,请确保在swift文件FirebaseApp.configure()中初始化它
import FirebaseCore //在顶部导入
nzrxty8p7#
看起来您需要在
await Firebase.initializeApp();
行中设置DefaultFirebaseOptions。根据这份文件,你需要把选项。
按此步骤操作
1.运行
flutter pub add firebase_core
1.运行
flutterfire configure
。如果您已经配置了项目,请跳过此步骤。1.在您的
main.dart
中,在代码中更新它。从
至
1.尝试运行应用程序
我希望这有助于解决这个问题。
感谢您的阅读!