我需要一段代码,可以在特定主题上从一个设备向多个设备发送通知,并显示在已订阅该主题的设备上。我将使用Firestore存储数据和令牌,并使用Firebase消息传递通知。
希望这对新开发者有所帮助。
import 'package:http/http.dart' as http;
Future<void> sendNotification(subject,title) async{
final postUrl = 'https://fcm.googleapis.com/fcm/send';
String toParams = "/topics/"+'yourTopicName';
final data = {
"notification": {"body":subject, "title":title},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"sound": 'default',
"screen": "yourTopicName",
},
"to": "${toParams}"};
final headers = {
'content-type': 'application/json',
'Authorization': 'key=key'
};
final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
// on success do
print("true");
} else {
// on failure do
print("false");
}
}
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
_firebaseMessaging.subscribeToTopic("yourTopicName");
curl
命令或类似于此的命令,调用 旧版 FCM REST API。在此处查看一个示例:如何在不使用 Firebase 控制台的情况下发送 Firebase 云消息通知? 要发送到主题,请确保 to
值为类似于 "/topics/your_topic"
的内容。关于此示例,请参阅functions-samples
存储库中的文件夹。
另请参见:
您可以使用firebase_messaging
和FirebaseMessaging.subscribeToTopic
订阅主题:
FirebaseMessaging().subcribeToTopic('topic_name');
你可以使用 Firebase 控制台或后端代码(例如 Cloud Functions)向主题发送通知。
firebase_messaging
库发送云消息,请参阅发送消息。FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
_firebaseMessaging.subscribeToTopic("MyTopic");
MyTopic
”中。_firebaseMessaging.unsubscribeFromTopic("MyTopic");
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging fcmMessage = FirebaseMessaging.instance;
await fcmMessage.subscribeToTopic('testNotification');
runApp(const MyApp());
}
添加HTTP POST请求
final data = {
'to': '/topics/testNotification',
'notification': {
'body':'Simple Notification',
'title': 'Test Notification',
}
};
String url = 'https://fcm.googleapis.com/fcm/send';
try {
final result = await http.post(
Uri.parse(url),
body: jsonEncode(data),
headers: {
'Content-type': 'application/json',
'Authorization':
'key=AAAAm5+++++++++++++++Authorization Token+++++++++++++'
},
);
print(jsonDecode(result.body));
return jsonDecode(result.body);
} catch (e) {
print(e);
return {'error': e};
}