12

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)
  },
 )
Ye Yint
  • 133
  • 1
  • 6
  • This refers to my solution here. https://stackoverflow.com/questions/57554659/stream-for-api-coming-from-php-in-flutter-not-firebase/58414791#58414791 – SilenceCodder Oct 16 '19 at 13:48

2 Answers2

21

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,
  );
}
Er1
  • 2,559
  • 1
  • 12
  • 24
  • While you're correct, rather than just putting a link in your answer it would be better if you write a small code example showing how you use timer. – rmtmckenzie Jun 05 '19 at 00:08
  • I know the Timer.periodic and setState but I want to use with Stream and StreamBuilder for batter purpose.thanks – Ye Yint Jun 05 '19 at 01:54
  • The handler function is not async but you are calling await. – Anthony O Sep 15 '20 at 20:51
  • 1
    @11010001101001 You're right, I've updated the example. – Er1 Sep 16 '20 at 09:24
  • How can I stop this stream? Isn't this stream running forever? – daniel vofchuk May 26 '21 at 21:55
  • @danielvofchuk When you listen to the stream you get the StreamSubscription, use that to cancel or pause it. https://api.dart.dev/stable/2.13.1/dart-async/StreamSubscription-class.html – Er1 May 27 '21 at 07:05
3

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

josue.0
  • 775
  • 1
  • 10
  • 23