这是我完成的代码。而且效果非常好。我试过调试,post方法正确地发布了所有内容。但是没有接收到该通知。这是的全部代码
import 'dart:convert';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
import 'package:http/http.dart' as http;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
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 MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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;
Future<bool> callOnFcmApiSendPushNotifications(
{required String title, required String body}) async {
const postUrl = 'https://fcm.googleapis.com/fcm/send';
final data = {
"to": "/topics/myTopic",
"notification": {
"title": title,
"body": body,
},
"data": {
"type": '0rder',
"id": '28',
"click_action": 'FLUTTER_NOTIFICATION_CLICK',
}
};
final headers = {
'content-type': 'application/json',
'Authorization':
'key=AAAAMKtOtwQ:APA91bFCCEwWKU75EVeyc912ghzS0Yon8dlfjiFEiw9nfdtfrq0BCBWS3x_ioTqX1l2MUDO_Wb-c2PbRl66Z_2mvFEsPRbDEAPTSCEb7SVFykecC_BWGR5P2La8T47eIfCiMvU9oJDJd'
};
final response = await http.post(Uri.parse(postUrl),
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
print('test ok push CFM');
return true;
} else {
print(' CFM error');
return false;
}
}
void _incrementCounter() {
setState(() {
callOnFcmApiSendPushNotifications(
title: 'fcm by api2', body: 'its working fine2');
_counter++;
});
}
@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),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
我需要从firebase中修复什么吗?或者代码有任何问题。我想不通,请帮我
我试着调试并打印代码文件中的所有位置。一切都很好。我让我能从firebase做任何事情。仍未收到通知
我还在安卓中测试这个
订阅/topics/myTopic
主题。
await FirebaseMessaging.instance.subscribeToTopic("/topics/myTopic");
有关详细信息,请参阅Flutter上的主题消息。
请记住,当应用程序处于前台时收到的消息不会显示可见的通知。
获取消息时,您需要一种处理这些消息的方法,这将取决于消息是在应用程序处于前台、后台还是关闭时接收的。
本文档展示了如何为前台接收的消息设置侦听器:
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
}
});
本文档展示了如何对在后台接收的消息执行此操作:
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
}
void main() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
您可以看到这些方法是如何在这个示例中实现的。
然后,要接收邮件,您需要订阅主题。在我提到的例子中,你可以在方法中看到这一点:
Future<void> subscribeToTopic(String topic) async {
await firebaseMessaging.subscribeToTopic(topic);
}
尝试在页眉中包含此行'origin': 'http://localhost',
,使其看起来像是在使用浏览器。。。所以,你的标题应该是这样的:
final headers = {
'origin': 'http://localhost',
'content-type': 'application/json',
'Authorization':
'key=AAAAMKtOtwQ:APA91bFCCEwWKU75EVeyc912ghzS0Yon8dlfjiFEiw9nfdtfrq0BCBWS3x_ioTqX1l2MUDO_Wb-c2PbRl66Z_2mvFEsPRbDEAPTSCEb7SVFykecC_BWGR5P2La8T47eIfCiMvU9oJDJd'
};