【问题标题】:How to get data from api every x seconds in flutter?如何在颤动中每 x 秒从 api 获取数据?
【发布时间】:2019-10-20 03:41:39
【问题描述】:

我想每隔 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)
  },
 )

【问题讨论】:

标签: flutter flutter-animation


【解决方案1】:

你应该看看 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,
  );
}

【讨论】:

  • 虽然你是对的,但与其只是在答案中添加一个链接,不如编写一个小代码示例来展示你如何使用计时器。
  • 我知道 Timer.periodic 和 setState 但我想与 Stream 和 StreamBuilder 一起使用以达到连击目的。谢谢
  • 处理函数不是异步的,但是你正在调用await。
  • @11010001101001 你说得对,我已经更新了示例。
  • 我怎样才能停止这个流?这个流不是一直在运行吗?
【解决方案2】:

您可能还需要仅在应用处于前台时执行此操作(以防止不必要的电池使用)。你可以使用我的 LifecycleAwareStreamBuilder,有一个使用示例here

Link directly to the gist

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 2021-06-16
    • 2021-11-08
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多