Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
  },
 )
like image 513
ye yint Avatar asked Jun 04 '19 15:06

ye yint


People also ask

How do you call a function periodically in flutter?

Execute Periodically in Flutterperiodic(Duration(seconds: 1), (timer) { setState(() { greeting = "After Some time ${DateTime. now(). second}"; }); }); This will set the value to the greeting variable in every 1 second.

How do you use the timer flutter?

Creating a simple timer Now, to create a simple 3-second timer, add the following, which triggers a callback after it executes: final timer = Timer( const Duration(seconds: 3), () { // Navigate to your favorite place }, ); Once the callback triggers, we can navigate a user to a new screen, for example.


2 Answers

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 PostData.browse();
  }).asyncMap((value) async => await value,
  );
}
like image 191
Er1 Avatar answered Sep 30 '22 17:09

Er1


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

like image 21
josue.0 Avatar answered Sep 30 '22 18:09

josue.0