appendToJsonArray method

Future<void> appendToJsonArray(
  1. String path,
  2. Map<String, dynamic> item, {
  3. String? uniqueKey,
})

Append an item to a JSON array file

Implementation

Future<void> appendToJsonArray(String path, Map<String, dynamic> item,
    {String? uniqueKey}) async {
  List<dynamic> array;

  if (fileExists(path)) {
    array = await readJsonArray(path);
  } else {
    array = [];
  }

  // Check for duplicates if uniqueKey is provided
  if (uniqueKey != null) {
    final exists =
        array.any((existing) => existing[uniqueKey] == item[uniqueKey]);
    if (exists) {
      comment('Item with $uniqueKey="${item[uniqueKey]}" already exists');
      return;
    }
  }

  array.add(item);
  await writeJson(path, array);
}