generateBackupJson method

Future<String> generateBackupJson({
  1. String keyToString(
    1. K key
    )?,
  2. Object? valueToJson(
    1. T value
    )?,
})

Generates a JSON string representing all key-value pairs in the box.

  • keyToString: Optional function to convert each key of type K to a String. If not provided, key.toString() is used.
  • valueToJson: Optional function to convert each value of type T to a JSON-serializable object. If not provided, the value is used as-is (must be directly encodable by jsonEncode).

Returns a Future that completes with the JSON string containing all box entries.

Throws BoxNotInitializedException if the box is not initialized.

Implementation

Future<String> generateBackupJson({
  String Function(K key)? keyToString,
  Object? Function(T value)? valueToJson,
}) async {
  await ensureInitialized();
  final keys = await getAllKeys();
  final Map<String, dynamic> data = {};

  for (final key in keys) {
    final value = await get(key);
    if (value != null) {
      final stringKey = keyToString?.call(key) ?? key.toString();
      final jsonValue = valueToJson?.call(value) ?? value;
      data[stringKey] = jsonValue;
    }
  }

  return jsonEncode(data);
}