updateColorsFile function
Updates the colors.xml with the new adaptive launcher icon color.
Rejects values that are neither a hex color literal nor an existing file
path, so we never write <color name="ic_launcher_background">assets/x.jpg</color>
or <color name="ic_launcher_background">not-a-color</color> and break
mergeDebugResources at build time (upstream #132).
Implementation
Future<void> updateColorsFile(File colorsFile, String backgroundColor) async {
if (!isHexColorLiteral(backgroundColor)) {
final asPath = File(backgroundColor);
if (!asPath.existsSync()) {
throw InvalidConfigException(
"adaptive_icon_background: '$backgroundColor' is not a hex color "
"(e.g. '#FFFFFF') and not an existing file path. Refusing to write "
'an invalid value into colors.xml.',
);
}
}
// Write foreground color
final List<String> lines = await colorsFile.readAsLines();
bool foundExisting = false;
for (int x = 0; x < lines.length; x++) {
String line = lines[x];
if (line.contains('name="ic_launcher_background"')) {
foundExisting = true;
// replace anything between tags which does not contain another tag
line = line.replaceAll(RegExp(r'>([^><]*)<'), '>$backgroundColor<');
lines[x] = line;
break;
}
}
// Add new line if we didn't find an existing value
if (!foundExisting) {
lines.insert(
lines.length - 1,
'\t<color name="ic_launcher_background">$backgroundColor</color>',
);
}
await colorsFile.writeAsString(lines.join('\n'));
}