我想每隔 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']
);
}
}
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;
}
Stream<int> get getLiveData async* {
yield await PostData.browse();
}
StreamBuilder<Post>(
stream: getLiveData,
builder: (context, snapshot) {
return Text(snapshot.data.title)
},
)
最佳答案
你应该看看 Timer.Periodic https://api.flutter.dev/flutter/dart-async/Timer/Timer.periodic.html我将它与 setState 一起使用,但我确信它也可以与 Stream 一起使用。
编辑: 像这样,使用 Stream.periodic:
Stream <int> getPeriodicStream() async* {
yield* Stream.periodic(Duration(seconds: 30), (_) {
return PostData.browse();
}).asyncMap((value) async => await value,
);
}
关于flutter - 如何在 flutter 中每隔 x 秒从 api 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56446763/