fetchConfig method

Future<Map<String, dynamic>> fetchConfig({
  1. bool forceRefresh = false,
})

Implementation

Future<Map<String, dynamic>> fetchConfig({bool forceRefresh = false}) async {
  final prefs = await SharedPreferences.getInstance();
  final lastFetchTime = prefs.getInt(_lastFetchTimeKey) ?? 0;
  final now = DateTime.now().millisecondsSinceEpoch;

  if (!forceRefresh && now - lastFetchTime < fetchInterval.inMilliseconds) {
    final cachedConfig = prefs.getString(_cacheKey);
    if (cachedConfig != null) {
      _lastFetchStatus = RemoteConfigStatus.throttled;
      return json.decode(cachedConfig);
    }
  }

  try {
    final response = await http
        .get(Uri.parse('https://gist.githubusercontent.com/raw/$gistId/$filename'))
        .timeout(timeout);

    if (response.statusCode == 200) {
      final config = json.decode(response.body) as Map<String, dynamic>;
      prefs.setString(_cacheKey, response.body);
      prefs.setInt(_lastFetchTimeKey, now);
      _lastFetchStatus = RemoteConfigStatus.success;
      _lastFetchTime = DateTime.now();
      return config;
    } else {
      _lastFetchStatus = RemoteConfigStatus.failure;
      final cachedConfig = prefs.getString(_cacheKey);
      if (cachedConfig != null) return json.decode(cachedConfig);
      return defaultConfig;
    }
  } catch (e) {
    _lastFetchStatus = RemoteConfigStatus.failure;
    final cachedConfig = prefs.getString(_cacheKey);
    if (cachedConfig != null) return json.decode(cachedConfig);
    return defaultConfig;
  }
}