Home > Net >  Fetch API data using Stream builder flutter
Fetch API data using Stream builder flutter

Time:12-26

I am trying to fetch data from API and I am using Stream builder but I am unable to fetch data from API. Following are my code:

I initalize stream controller

final StreamController<APIModel> _streamController = StreamController();

Method for get data from API

Future<APIModel> getdatafromAPI() async {
    var url =
        "myapi";
    var response = await http.get(Uri.parse(url));
    var data = jsonDecode(response.body.toString());

    if (response.statusCode == 200) {
      //sink data for stream builder
      _streamController.sink.add(APIModel.fromJson(data));
      return MayyatNewsModel.fromJson(data);
    } else {
      return MayyatNewsModel.fromJson(data);
    }
  }

in response == 200 i used stream controller to sink all response data into the controller.

Following are ui part to show data but unable to load this data. What is the problem?? or what is the right way to use Streambuilder??

...
StreamBuilder<APIModel>(
                      stream: _streamController.stream,
                      builder: (context,AsyncSnapshot<MayyatNewsModel> snapshot) {
                        if (snapshot.hasData) {
                          return ListView.builder(
...

CodePudding user response:

If you want to call your getdatafromAPI for every specific duration you need to first define new stream variable like this:

late Stream<APIModel> stream = Stream.periodic(Duration(seconds: 5))
  .asyncMap((event) async => await getdatafromAPI());

then use it like this:

StreamBuilder<APIModel>(
    stream: stream,
    builder: ...
),
  • Related