-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpreferences_io.dart
49 lines (40 loc) · 1.54 KB
/
preferences_io.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import 'dart:convert';
import 'package:ensemble_device_preview/src/state/state.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../storage.dart';
/// A storage that keeps all preferences stored as json in the
/// preference entry with the [preferenceKey] key.
class PreferencesDevicePreviewStorage extends DevicePreviewStorage {
PreferencesDevicePreviewStorage({
this.preferenceKey = defaultPreferencesKey,
});
/// The preferences key used to save the user configuration.
final String preferenceKey;
/// The default preferences key used to save the user configuration.
static const String defaultPreferencesKey = 'device_preview.settings';
/// Load the last saved preferences (until [ignore] is `true`).
@override
Future<DevicePreviewData?> load() async {
final shared = await SharedPreferences.getInstance();
final json = shared.getString(preferenceKey);
if (json == null || json.isEmpty) return null;
return DevicePreviewData.fromJson(jsonDecode(json));
}
/// Save the current preferences (until [ignore] is `true`).
@override
Future<void> save(DevicePreviewData data) async {
_saveData = data;
_saveTask ??= _save();
await _saveTask;
}
Future<void>? _saveTask;
DevicePreviewData? _saveData;
Future _save() async {
await Future.delayed(const Duration(milliseconds: 500));
if (_saveData != null) {
final shared = await SharedPreferences.getInstance();
await shared.setString(preferenceKey, jsonEncode(_saveData!.toJson()));
}
_saveTask = null;
}
}