Search code examples
dartcolorsflutter-layoutuicolorcolor-scheme

Programmatically Lighten or Darken a hex color in dart


I am trying to convert this hash color code #159424 (GREEN-COLOR) to more darken and lighten programmatically. How to do this please help?

make green color darker

toDarkColor(String hashColor){
  // how to convert that hash string to make green color darker?
}

make green color lighter

toLightColor(String hashColor){
  // how to convert that hash string to make green color lighter? 
}

Solution

  • For people who want to darken or lighten Color instead of hex string

    // ranges from 0.0 to 1.0
    
    Color darken(Color color, [double amount = .1]) {
      assert(amount >= 0 && amount <= 1);
    
      final hsl = HSLColor.fromColor(color);
      final hslDark = hsl.withLightness((hsl.lightness - amount).clamp(0.0, 1.0));
    
      return hslDark.toColor();
    }
    
    Color lighten(Color color, [double amount = .1]) {
      assert(amount >= 0 && amount <= 1);
    
      final hsl = HSLColor.fromColor(color);
      final hslLight = hsl.withLightness((hsl.lightness + amount).clamp(0.0, 1.0));
    
      return hslLight.toColor();
    }
    
    // usage
    final lightRed = lighten(Colors.red);
    final darkBlue = darken(Colors.blue, .3);
    

    Live Demo