How to get data from api every x seconds in flutter?

纵饮孤独 提交于 2020-07-20 09:57:09

问题


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.

Here is my code.

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)
  },
 )

回答1:


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.

EDIT: Something like this, using Stream.periodic:

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



回答2:


You probably also need to do this only while the app is in foreground (to prevent unnecessary battery usage). You can use my LifecycleAwareStreamBuilder, there is an example on how to use it here

Link directly to the gist



来源:https://stackoverflow.com/questions/56446763/how-to-get-data-from-api-every-x-seconds-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!