skip to Main Content

I have a Flutter app that displays a list of data elements relating to the current day that are sourced from a RiverPod FutureProvider.

The app can be left open on the mobile phone over night, and I am trying to work out how to have the list automatically refresh when I pick up the mobile phone the next morning, so that it is showing the new day’s data elements.

I’ve tried using the following StreamProvider as the trigger for a refresh of the

final newDayProvider= StreamProvider<DateTime?>((ref)  async* {

  const String aPropName = 'dayCheckerTimestamp';

  await for (final  aDate in Stream<DateTime?>.periodic(const Duration(minutes: 1), (_) {
    var aDayHasChanged = false;
    final aStr = ref.read(sharedPrefsProvider).getString(aPropName);
    final aNow = DateTime.now();
    if (aStr != null) {
      DateTime aPrev = DateTime.parse(aStr);
      aDayHasChanged = (aNow.day != aPrev.day) || (aNow.month != aPrev.month) || (aNow.year != aPrev.year);
    }
    ref.read(sharedPrefsProvider).setString(aPropName,aNow.toIso8601String());
    if (aDayHasChanged) {
      return aNow;
    }
    return null;
  })
  ) {
    if (aDate != null) {
      yield aDate;
    }
  };

});

I then inject the following line into the related FutureProvider

final findTodayDashboardTaskProvider = FutureProvider.autoDispose<List<GdTask>>( (ref) async {
  final aNewDate = ref.watch(newDayProvider);

… the idea being that the new day stream event will trigger a refresh of the FutureProvider.

However, this is not working. When I pick up the mobile phone the next morning, the app is still showing the data elements related to yesterday, not the current day.

I’m guessing that as the phone is left overnight all the apps go into hibernation, and the StreamProvider code never runs. Is this correct?

Any suggestions on how to fix this?

2

Answers


  1. Maybe something like:

    final midnightProvider = Provider<DateTime>((ref) {
      final now = DateTime.now();
      final tomorrow =
          now.copyWith(hour: 24, minute: 0, second: 0); // midnight tomorrow
      final gap = tomorrow.difference(now);
      // print(gap);
      Timer(gap, ref.invalidateSelf);
      return tomorrow;
    });
    

    That should reset each night at midnight, and return the time of the next wakeup for grins.

    Login or Signup to reply.
  2. Change your FutureProveder to a StreamProvider.

    My understanding is that once a FutureProvider has provided a result it will not run again, and will stop listening to its providers. (Of course if the widget using the FutureProvider is rebuilt, and depending on how it’s coded, it may create a new FutureProvider and use its result.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search