/// Unions [remote] and [local] by ID, keeping whichever copy of each /// record has the newer `updatedAt` when a record exists on both sides. /// This lets two devices' independent new records both survive a sync; /// it does not propagate deletions (see plan doc's Known limitations). List mergeById( List remote, List local, String Function(T) idOf, DateTime Function(T) updatedAtOf, ) { final merged = {}; for (final item in remote) { merged[idOf(item)] = item; } for (final item in local) { final id = idOf(item); final existing = merged[id]; if (existing == null || !updatedAtOf(existing).isAfter(updatedAtOf(item))) { merged[id] = item; } } return merged.values.toList(); }