gpt4 book ai didi

flutter - Flutter服务器端事件,响应式(Reactive)UI

转载 作者:行者123 更新时间:2023-12-03 04:50:47 25 4
gpt4 key购买 nike

我正在尝试让我的应用程序响应SSE服务器发送事件流。流中出现了许多类型的事件,并且仅当我收到的事件类型与该UI元素相关联时,应用程序的某些部分才会更新。

样本json流响应(例如,在这里,如果我心跳了,我就不想更改UI):

event:heartbeat
data:{"type":"heartbeat"}

event:gwy
data:{"a":532289,"lastUpdatedDateInMilliseconds":1587490669503,"t":1587490669503,"g":12479,"api":0,"cellSignalStrength":15}

event:gwy
data:{"a":532289,"lastUpdatedDateInMilliseconds":1587490694685,"t":1587490694685,"g":12479,"api":0,"cellSignalStrength":15}


此数据的格式是Global数据变量的子集(该事件应替换Global变量的那一部分)。

任何指针或资源,不胜感激。

最佳答案

我知道您已经找到答案了,但是如果要解析流的值,这是我使用的代码,它将提取事件和实际数据

import "package:http/http.dart";

http.Client client = http.Client();

http.Request request = http.Request("GET", Uri.parse('your url'));
request.headers["Accept"] = "text/event-stream";
request.headers["Cache-Control"] = "no-cache";

Future<http.StreamedResponse> response = client.send(request);
print("Subscribed!");
response.then((streamedResponse) => streamedResponse.stream.listen((value) {
final parsedData = utf8.decode(value);
print(parsedData);

//event:heartbeat
//data:{"type":"heartbeat"}

final eventType = parsedData.split("\n")[0].split(":")[1];
print(eventType);
//heartbeat
final realParsedData = json.decode(parsedData.split("data:")[1]) as Map<String, dynamic>;
if (realParsedData != null) {
// do something
}
}, onDone: () => print("The streamresponse is ended"),),);

关于flutter - Flutter服务器端事件,响应式(Reactive)UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61398414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com