import "dart:convert"; import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/shared_prefs.dart"; class ShownNotificationsHelper(final Ref ref) { static const _key = "shownNotifications"; /// Applies [update], returning the IDs from before it. Future>> _update( IMap> Function(IMap> shown) update, ) async { final prefs = ref.read(SharedPrefsController.provider); final shown = IMap>.fromJson( json.decode(await prefs.getString(_key) ?? "{}"), (threadId) => threadId as String, (ids) => .fromJson(ids, (id) => id as int), ); await prefs.setString( _key, json.encode( update(shown) .toJson((threadId) => threadId, (ids) => ids.toJson((id) => id)), ), ); return shown; } Future add(String threadId, int id) => _update( (shown) => shown.update( threadId, (ids) => ids.add(id), ifAbsent: () => .new({id}), ), ); /// Forgets the notifications shown for [threadIds], returning their IDs. Future> remove(ISet threadIds) async { final shown = await _update( (shown) => shown.removeWhere((threadId, _) => threadIds.contains(threadId)), ); return threadIds.map((threadId) => shown[threadId]).nonNulls.flattened; } static final provider = Provider( ShownNotificationsHelper.new, ); }