ye *_*int 10 flutter flutter-animation
我想每 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)
Er1*_*Er1 18
你应该看看 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,
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6186 次 |
| 最近记录: |