Global variables or singletons lose their value (reset) after refresh

Viewed 661

I have a simple webpage that I would like to refresh every few minutes, defined by the user. So, for that I thought of using a global variable to store the value of how often the page should be refreshed. Unfortunately, it seems that after the page refreshes, all of the variable values are lost/restarted for some reason.

I tried using different kinds of imports, the singleton pattern, service pattern, a simple static variable inside a "Globals" class but nothing seems to work.

My current, relevant code for the global class is this:

class Globals {
  static final Globals _instance = Globals._internal();

  factory Globals() => _instance;

  Globals._internal() {
    _GLOBAL_REFRESH_MINUTES = 0;
  }

  int? _GLOBAL_REFRESH_MINUTES;

  int get REFRESH_MINUTES => _GLOBAL_REFRESH_MINUTES!;

  set REFRESH_MINUTES(int value) => _GLOBAL_REFRESH_MINUTES = value;
}
import 'package:myproject/common/globals.dart';
   Globals _globals = Globals();
   if (_globals.REFRESH_MINUTES > 0) {
      new Timer.periodic(Duration(minutes: _globals.REFRESH_MINUTES),
          (Timer t) => html.window.location.reload());
    }
1 Answers

To solve your problem you need to save data to the browser, I could suggest hive: https://pub.dev/packages/hive this is great for things like 'remember me' on login or user preferences, configurations that need to persist across browser sessions.

Without knowing why you are refreshing the browser every few minutes, is it possible that another solution which does not globally restart the application could be leveraged? Perhaps whatever needs restarting could be disposed and reinitialized in its own class for example. If so that would be the correct approach to take.

Related