70 lines
2.6 KiB
Dart
70 lines
2.6 KiB
Dart
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// Flutter has its own store; the former Android `lumen.xml` is never imported.
|
|
class Progress {
|
|
Progress._(this._disk, this._values, [this._storyId, this._root]);
|
|
final String? _storyId;
|
|
final Progress? _root;
|
|
|
|
/// The original book retains its existing save keys. Other stories get a
|
|
/// namespace; device settings, daily/practice records and totals stay global.
|
|
Progress forStory(String id) => Progress._(_disk, _values, id, _root ?? this);
|
|
String _key(String key) {
|
|
if (_storyId == null || _storyId == 'mara-island') return key;
|
|
final storyKey =
|
|
key.startsWith('notebook_') ||
|
|
key.startsWith('flutter_') ||
|
|
key.startsWith('viewed_') ||
|
|
key.startsWith('storyAd_') ||
|
|
key.startsWith('grid_story_') ||
|
|
key.startsWith('done_story_') ||
|
|
key == 'campaignUnlocked' ||
|
|
key == 'story_access_level';
|
|
return storyKey ? 'story/$_storyId/$key' : key;
|
|
}
|
|
|
|
final SharedPreferencesAsync? _disk;
|
|
final Map<String, Object> _values;
|
|
static Future<Progress> load() async {
|
|
final disk = SharedPreferencesAsync();
|
|
return Progress._(disk, (await disk.getAll()).cast<String, Object>());
|
|
}
|
|
|
|
factory Progress.memory([Map<String, Object> values = const {}]) =>
|
|
Progress._(null, Map.of(values));
|
|
int number(String key, [int fallback = 0]) =>
|
|
(_values[_key(key)] as num?)?.toInt() ?? fallback;
|
|
double decimal(String key, [double fallback = 1]) =>
|
|
(_values[_key(key)] as num?)?.toDouble() ?? fallback;
|
|
bool flag(String key) => _values[_key(key)] == true;
|
|
String text(String key, [String fallback = '']) =>
|
|
_values[_key(key)] as String? ?? fallback;
|
|
bool contains(String key) => _values.containsKey(_key(key));
|
|
Map<String, Object> get snapshot => Map.unmodifiable(_values);
|
|
Future<void> _writes = Future.value();
|
|
Future<void> set(String key, Object value) {
|
|
_values[_key(key)] = value;
|
|
final disk = _disk;
|
|
if (disk == null) return Future.value();
|
|
final writer = _root ?? this;
|
|
final storedKey = _key(key);
|
|
writer._writes = writer._writes.then((_) async {
|
|
switch (value) {
|
|
case bool v:
|
|
await disk.setBool(storedKey, v);
|
|
case int v:
|
|
await disk.setInt(storedKey, v);
|
|
case double v:
|
|
await disk.setDouble(storedKey, v);
|
|
case String v:
|
|
await disk.setString(storedKey, v);
|
|
default:
|
|
throw ArgumentError('Unsupported preference');
|
|
}
|
|
});
|
|
return writer._writes;
|
|
}
|
|
|
|
Future<void> get flushed => (_root ?? this)._writes;
|
|
}
|