simc / dartx

Superpowers for Dart. Collection of useful static extension methods.
https://pub.dev/packages/dartx
Apache License 2.0
1.08k stars 88 forks source link

Extension for text coloring based on luminance #128

Open nogipx opened 3 years ago

nogipx commented 3 years ago
extension TextColor on Color {
  static Color Function(Color) luminanceDyer({
    Color light = Colors.white,
    Color dark = Colors.black,
  }) => (color) => color.computeLuminance() > 0.5 ? dark : light;

  Color dye(Color Function(Color) dyer) => dyer(this);

  Color luminance({
    Color light = Colors.white,
    Color dark = Colors.black,
  }) => TextColor.luminanceDyer(light: light, dark: dark).call(this);
}

void main() {
  final dyer = TextColor.luminanceDyer(
    light: Colors.white,
    dark: Colors.black,
  );
  Colors.white.dye(dyer); // Colors.black
  Colors.black.dye(dyer); // Colors.white
  Colors.greenAccent.dye(dyer); // Colors.black
  Colors.green.dye(dyer); // Colors.white
}

class ExampleWidget extends StatelessWidget {
  final Color? color;

  const ExampleWidget({
    Key? key,
    this.color,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color?.luminance(
        light: Colors.white,
        dark: Colors.black87,
      ),
    );
  }
}