如何每隔X秒钟从api获取api中的数据? [英] How to get data from api every x seconds in flutter?

查看:94
本文介绍了如何每隔X秒钟从api获取api中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每隔x秒从api获取数据以将数据实时显示在窗口小部件中,并且我还想在数据更改时为窗口小部件动画.我尝试使用Stream和Stream Builder,这是实时获取数据的最佳方法请帮助我.

I want to fetch data from api every x seconds to display data as live in widget and I also want to animate widget when data is change.I tried with Stream and Stream Builder.Which is the best way to fetch data as live.Please help me.

这是我的代码.

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

You should take a look at Timer.Periodic https://api.flutter.dev/flutter/dart-async/Timer/Timer.periodic.html I am using it with setState, but I'm sure it's also possible with a Stream.

使用Stream.periodic这样的事情:

Something like this, using Stream.periodic:

Stream <int> getPeriodicStream() async* {
  yield* Stream.periodic(Duration(seconds: 30), (_) {
    return PostData.browse();
  }).asyncMap((value) async => await value,
  );
}

这篇关于如何每隔X秒钟从api获取api中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆