Home > Net >  Periodic fetch from API in Flutter
Periodic fetch from API in Flutter

Time:06-23

I'm trying to make my app fetch data from API every 5 seconds without refreshing the page every time.

How can I achieve it ?

CodePudding user response:

For whoever is facing this error , I fixed it like this.

    Timer? t;
  @override
  void initState() {
    super.initState();
    t = new Timer.periodic(timeDelay, (t) => fetchDocuments());
  }
    @override
  void dispose() {
    t?.cancel();
    super.dispose();
  }

CodePudding user response:

This is a simple timer that runs every a HTTP lookup every 5 seconds.


import 'package:http/http.dart' as http;

import "dart:async";

void main() {
  
  var timer = Timer.periodic(const Duration(seconds: 5), (_) async {
    var album = await fetchAlbum();
    print(album.body);
    //Update page with data here
  });
}
Future<http.Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}

I have included a basic HTTP lookup from here: https://docs.flutter.dev/cookbook/networking/fetch-data Without knowing more about your app I can't give anymore information.

  • Related