我正在尝试在Flutter应用程序中发布发布/订阅消息,如下所示:
import 'package:flutter/material.dart';
import 'package:googleapis/pubsub//v1.dart';
import 'package:googleapis_auth/auth_io.dart';
const _SCOPES = const [PubsubApi.PubsubScope];
class Activities extends StatefulWidget {
Activities();
@override
_Activities createState() => _Activities();
}
final _credentials = new ServiceAccountCredentials.fromJson(r'''
{
"type": "service_account",
...
}
''');
class _Activities extends State<Activities> with SingleTickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return new Scaffold(
body: Center(
child: Container(
child: new MaterialButton(
onPressed: () {
debugPrint("trying to publish a message...");
clientViaServiceAccount(_credentials, _SCOPES)
.then((http_client) {
var pubSubClient = new PubsubApi(http_client);
Map<String, dynamic> message = new Map<String, dynamic>();
message["data"] = Map<String, dynamic>();
message["data"]["type"] = "foo";
message["data"]["senderId"] = "bar";
pubSubClient.projects.topics
.publish(new PublishRequest.fromJson(message), "projects/myProject/topics/events")
.then((publishResponse) {
debugPrint(publishResponse.toString());
}).catchError((e,m){
debugPrint(e.toString());
});
})
.catchError((e,m) {
debugPrint(e.toString());
});
},
child: new Text("Publish message"),
),
),
)
);
}
}
但是在日志中,我收到以下错误消息:
I/flutter ( 5281): DetailedApiRequestError(status: 400, message: The value for 0 is too small. You passed message_count in the request, but the minimum value is 1.)
我搜索了此消息,但未找到任何内容。我认为我的消息结构可能是错误的,但是可能还有其他问题吗?不想浪费太多时间...
答案 0 :(得分:1)
好吧,对于那些想知道的人,这是我想出的:
var messages = {
'messages': [
{
'data': base64Encode(utf8.encode('{"foo": "bar"}')),
},
]
};
pubSubClient.projects.topics
.publish(new PublishRequest.fromJson(messages), "your topic")
.then((publishResponse) {
debugPrint(publishResponse.toString());
}).catchError((e,m){
debugPrint(e.toString());
});
也许有人应该在上面写一篇文章,这不是很清楚,我不得不尝试不同的方法,并且还要阅读pubsub客户端库中的源代码...
答案 1 :(得分:0)
使用 gcloud: ^0.7.3 包。
使用以下代码建立连接。
import 'package:gcloud/pubsub.dart';
import 'package:googleapis/pubsub/v1.dart';
import 'package:googleapis_auth/auth_io.dart';
// Read the service account credentials from the file.
var jsonCredentials = new File('my-project.json').readAsStringSync();
var credentials = new auth.ServiceAccountCredentials.fromJson(jsonCredentials);
var client = await auth.clientViaServiceAccount(credentials, scopes);
var pubsub = new PubSub(client, 'my-project');
有关发布和订阅,请参阅自述文件的 this 部分。