Hex String to Color in Flutter

PHOTO EMBED

Fri Apr 23 2021 02:25:58 GMT+0000 (UTC)

Saved by @theanonymost #dart #flutter

class AppColors {
  static MaterialColor hex(String hex) =>
      AppColors._factoryColor(AppColors._getColorHexFromStr(hex));

  static MaterialColor _factoryColor(int color) {
    return MaterialColor(color, <int, Color>{
      50: Color(color),
      100: Color(color),
      200: Color(color),
      300: Color(color),
      400: Color(color),
      500: Color(color),
      600: Color(color),
      700: Color(color),
      800: Color(color),
      900: Color(color),
    });
  }

  static int _getColorHexFromStr(String colorStr) {
    colorStr = "FF" + colorStr;
    colorStr = colorStr.replaceAll("#", "");
    int val = 0;
    int len = colorStr.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = colorStr.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        val = 0xFFFFFFFF;
      }
    }
    return val;
  }
}

// Example: In your app
// ...
class MyExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
    	height: 100.0,
      	width: 100.0,
      	decoration: BoxDecoration(
    		color: AppColors.hex('#000000'),	
    ),
    );
  }
}
content_copyCOPY

I'm not exactly sure where I got this from. Probably stackoverflow, but it does a pretty great job of converting strings to color.