generateColors function

String generateColors(
  1. File pubspecFile,
  2. DartFormatter formatter,
  3. FlutterGenColors colorsConfig
)

Implementation

String generateColors(
  File pubspecFile,
  DartFormatter formatter,
  FlutterGenColors colorsConfig,
) {
  if (colorsConfig.inputs.isEmpty) {
    throw const InvalidSettingsException(
        'The value of "flutter_gen/colors:" is incorrect.');
  }

  final buffer = StringBuffer();
  final className = colorsConfig.outputs.className;
  buffer.writeln(header);
  buffer.writeln(ignore);
  buffer.writeln("import 'package:flutter/painting.dart';");
  buffer.writeln("import 'package:flutter/material.dart';");
  buffer.writeln();
  buffer.writeln('class $className {');
  buffer.writeln('$className._();');
  buffer.writeln();

  final colorList = <_Color>[];
  colorsConfig.inputs
      .map((file) => ColorPath(join(pubspecFile.parent.path, file)))
      .forEach((colorFile) {
    final data = colorFile.file.readAsStringSync();
    if (colorFile.isXml) {
      colorList.addAll(
          XmlDocument.parse(data).findAllElements('color').map((element) {
        return _Color.fromXmlElement(element);
      }));
    } else {
      throw 'Not supported file type ${colorFile.mime}.';
    }
  });

  colorList
      .distinctBy((color) => color.name)
      .sortedBy((color) => color.name)
      .map(_colorStatement)
      .forEach(buffer.write);

  buffer.writeln('}');
  return formatter.format(buffer.toString());
}