addCounterAndCheck method
should be called when event with eventName
is caught
Implementation
void addCounterAndCheck(String eventName) async {
await Future.delayed(const Duration(seconds: 1), () {});
try {
final mapConfig = await _remoteConfigRepo.getConfigs();
final config = mapConfig == null
? null
: FeedbackConfig.fromJson(mapConfig);
if (config == null) {
throw Exception('configs null');
}
final events = config.events;
if (events == null) {
throw Exception('null events');
}
final counter = events[eventName];
if (counter == null) {
throw Exception('invalid counter');
}
final prefs = await SharedPreferences.getInstance();
/// getting current counters map
CurrentFeedbackCounters currentCounters = _loadCounters(prefs);
final Map<String, int> eventsMap = {};
eventsMap.addAll(currentCounters.events ?? {});
/// incrementing [eventName] counter
int value = eventsMap[eventName] ?? 0;
value += 1;
if (value >= INT_FEEDBACK_MAX_VALUE - 1) {
value -= 1;
}
final currVersion = await _appVersion();
final savedAppVersion = currentCounters.savedAppVersion ?? currVersion;
final dontDisturb = config.doNotDisturbOnNewVersion ?? false;
/// if last time dialog was shown in another app version and also dont_disturb_on_new_versions is false
/// we will renew all the counters (set all to 0 and reacted one to 1) and set feedbackDialogShown to false;
/// so next time any counter will reach needed number, dialog will be shown.
/// dont_disturb_on_new_versions is true, we'll skip it and dialog won't be shown
///
if (savedAppVersion != currVersion && !dontDisturb) {
for (final String key in events.keys.toList()) {
int v = 0;
if (key == eventName) {
v = 1;
}
eventsMap[key] = v;
}
currentCounters = currentCounters.copyWith(
feedbackDialogShown: false,
savedAppVersion: currVersion,
events: eventsMap,
);
_saveCounters(prefs, currentCounters);
/// FeedbackRepoResponse() has countersBorderPassed = false, so bloc shouldn't react to it
/// showing feedback dialog.
provideDataToListeners(FeedbackRepoLoadResponse());
return;
}
eventsMap[eventName] = value;
currentCounters = currentCounters.copyWith(events: eventsMap);
onDebugPrint?.call('added constant value to $eventName, val is $value');
bool hasShown = currentCounters.feedbackDialogShown ?? false;
hasShown = _checkDelayed(config, currentCounters, hasShown);
if (value >= counter && !hasShown) {
currentCounters = currentCounters.copyWith(
feedbackDialogShown: true,
savedAppVersion: currVersion,
feedbackDelayDateMillis: null,
);
provideDataToListeners(FeedbackRepoLoadResponse.passed());
_saveCounters(prefs, currentCounters);
return;
}
provideDataToListeners(FeedbackRepoLoadResponse());
_saveCounters(prefs, currentCounters);
} catch (e) {
onDebugPrint?.call(
'Catched Exception: cannot write $eventName value. Cause: ${e.toString()}',
);
}
provideDataToListeners(FeedbackRepoLoadResponse());
}