Flutter Dio helper post返回空值



我使用Fire Base消息向另一个设备发送消息。我得到了另一个设备的密钥和令牌,但邮政只是在邮差工作,我在我的设备上成功收到通知。但是当我使用下面的代码时,它返回空值,为什么在发送消息函数中从post请求返回的值是空的。post request在邮差中工作很好,我没有看到任何逻辑错误,希望有人能帮助我解决这个问题


import 'package:dio/dio.dart';
class DioHelper{
static Dio ?dio ;

static init(){

dio = Dio(
BaseOptions(
baseUrl: 'https://fcm.googleapis.com/fcm/',
receiveDataWhenStatusError: true,
) ,
) ;
}
static Future<Response?> getData({
required String url,
Map<String, dynamic> ?query,
String lang = 'en',
String ?token,
}) async
{
dio?.options.headers =
{
'Content-Type':'application/json',
'Authorization': 'key=key=${myapi}',
};
return await dio?.get(
url,
queryParameters: query??null,
);
}
static Future<Response?> postData({
required String url,
Map<String, dynamic> ?query,
required Map<String,dynamic> data ,
})async
{
dio?.options.headers={
'Content-Type':'application/json',
'Authorization': 'key=${myapi}',
};
return await dio?.post(url,data: data ,queryParameters: query) ;
}
static Future<Response?> putData({
required String url,
Map<String, dynamic> ?query,
required Map<String,dynamic> data ,
String lang='en' ,
String ?token ,
})async
{
dio?.options.headers={
'Content-Type':'application/json',
'Authorization': 'key=key=${myapi}',
};
return await dio?.put(url,data: data ,queryParameters: query) ;
}
}

使用Di-helper的函数

void sendMessageForOneUser(String tokens,String title,String body,String image){
print('sendmessages');
DioHelper.postData(url:'send',data:{
"to":tokens,
"notification":{
"title": title,
"body":body ,
"mutable_content": true,
"sound": "Tri-tone",
"image":image
}
}).then((value){
print(value);
}).catchError((onError){
print(onError.toString());
});
}

我不知道为什么不工作,以为邮差很好

使用"key=your_server_key"在客户端代码中是serious security risk,因为它允许恶意用户去传递他们想要的信息给你的用户。This is a bad practiceshould not be used在生产级应用程序。

您可以尝试此代码从客户端(应用端)发送推送通知,但我建议您避免这种方式,除非你的移动应用程序不使用服务器。尝试调用自己的服务器API从服务器端发送推送通知,而不是从客户端(移动应用端)发送推送通知。

Future<void> sendPushNotification(String receiverToken) async {
try {
const postUrl = 'https://fcm.googleapis.com/fcm/send';
final data = {
"registration_ids": [receiverToken], //CAN pass multiple tokens
"collapse_key": "type_a",
"notification": {
"title": 'NewTextTitle',
"body": 'NewTextBody',
}
};
final headers = {
'content-type': 'application/json',
'Authorization': 'FCM_API_SERVER_KEY' // 'key=YOUR_SERVER_KEY'
};
final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
debugPrint('test ok push FM');
} else {
debugPrint(' FCM not sent successfully');
}
} catch (ex) {
debugPrint('send push notification api error: $ex');
}
}

为更好的方法,请查看此链接

最新更新