我想每 x 秒从 api 获取数据以在小部件中实时显示数据,我还想在数据更改时为小部件设置动画。我尝试使用 Stream 和 Stream Builder。这是实时获取数据的最佳方式。请帮忙我。
这是我的代码。
class Post{
final String title;
Post({this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
no: json['title']
);
}
}
Run Code Online (Sandbox Code Playgroud)
class PostData {
static String _url="https://jsonplaceholder.typicode.com/posts/1";
static Future browse () async {
http.Response response = await http.get(_url);
Post post= Post.fromJson(json.decode(response.body));
return post;
}
Run Code Online (Sandbox Code Playgroud)
Stream<int> get getLiveData async* {
yield await PostData.browse();
}
StreamBuilder<Post>(
stream: getLiveData,
builder: (context, snapshot) {
return Text(snapshot.data.title)
},
)
Run Code Online (Sandbox Code Playgroud)