flutter (dart) 是否能够在单独的 isolate 中发出 api 请求?
is flutter (dart) able to make an api request in separate isolate?
我制作了一个功能来 post 通知一个主题。它在正常情况下很好用,然后我把它放在 compute 函数中,希望它能在后台发出 post 的通知。但它不起作用。
这是我的代码:
void onSendMessageInBackGround(String message) {
Future.delayed(Duration(milliseconds: 3000)).then((_) async{
Client client = Client();
final requestHeader = {'Authorization': 'key=my_server_key', 'Content-Type': 'application/json'};
var data = json.encode({
'notification': {
'body': 'tester',
'title': '$message',
},
'priority': 'high',
'data': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'dataMessage': 'test',
'time': "${DateTime.now()}",
},
'to': '/topics/uat'
});
await client.post('https://fcm.googleapis.com/fcm/send', headers: requestHeader, body: data);
});
}
调用计算:
compute(onSendMessageInBackGround, 'abc');
注意:我已经将 onSendMessageInBackGround 函数放在我的应用程序的顶层,正如库所说
是不是漏了什么?或者我们不能那样做?
从计算调用的函数必须是静态的或全局的。
要么我同意pskink,这里的计算没有用。
您可能需要添加 return
或 await
void onSendMessageInBackGround(String message) {
return /* await (with async above) */ Future.delayed(Duration(milliseconds: 3000)).then((_) async{
可能是因为您没有等待 Future
,所以 isolate 在发出请求之前关闭了
Isolates 通过来回传递消息进行通信。这些消息可以是原始值,例如 null、num、bool、double 或 String,也可以是简单的对象,例如本例中的 List。
如果您尝试在隔离之间传递更复杂的对象,例如 Future 或 http.Response,您可能会遇到错误。
从文档中得到这个here
我制作了一个功能来 post 通知一个主题。它在正常情况下很好用,然后我把它放在 compute 函数中,希望它能在后台发出 post 的通知。但它不起作用。 这是我的代码:
void onSendMessageInBackGround(String message) {
Future.delayed(Duration(milliseconds: 3000)).then((_) async{
Client client = Client();
final requestHeader = {'Authorization': 'key=my_server_key', 'Content-Type': 'application/json'};
var data = json.encode({
'notification': {
'body': 'tester',
'title': '$message',
},
'priority': 'high',
'data': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'dataMessage': 'test',
'time': "${DateTime.now()}",
},
'to': '/topics/uat'
});
await client.post('https://fcm.googleapis.com/fcm/send', headers: requestHeader, body: data);
});
}
调用计算:
compute(onSendMessageInBackGround, 'abc');
注意:我已经将 onSendMessageInBackGround 函数放在我的应用程序的顶层,正如库所说
是不是漏了什么?或者我们不能那样做?
从计算调用的函数必须是静态的或全局的。
要么我同意pskink,这里的计算没有用。
您可能需要添加 return
或 await
void onSendMessageInBackGround(String message) {
return /* await (with async above) */ Future.delayed(Duration(milliseconds: 3000)).then((_) async{
可能是因为您没有等待 Future
Isolates 通过来回传递消息进行通信。这些消息可以是原始值,例如 null、num、bool、double 或 String,也可以是简单的对象,例如本例中的 List。
如果您尝试在隔离之间传递更复杂的对象,例如 Future 或 http.Response,您可能会遇到错误。
从文档中得到这个here