Good day guys. I'm making a football score live data app in flutter. I don't know how to get around this, if I use http.get, I'll have to refresh Everytime to get the recent data. I don't know if a streamBuilder would work and how to go about it. Thanks in advance for your help.
Asked
Active
Viewed 6,303 times
2
-
please try this once :- https://stackoverflow.com/a/57565501/8388068 – hio Jul 20 '20 at 04:34
1 Answers
10
As explained in the docs, StreamBuilder is a:
Widget that builds itself based on the latest snapshot of interaction with a Stream.
So, to use it, first you need to create a Stream that provides your data, pass it to the stream prop of StreamBuilder, then in the builder prop you build your widget based on the snapshot data.
Here is a short example that uses Stream.periodic
to return the future every 5 seconds and yield the future call:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class PeriodicRequester extends StatelessWidget {
Stream<http.Response> getRandomNumberFact() async* {
yield* Stream.periodic(Duration(seconds: 5), (_) {
return http.get("http://numbersapi.com/random/");
}).asyncMap((event) async => await event);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<http.Response>(
stream: getRandomNumberFact(),
builder: (context, snapshot) => snapshot.hasData
? Center(child: Text(snapshot.data.body))
: CircularProgressIndicator(),
);
}
}

MDemetrio
- 396
- 2
- 9