Search code examples
flutterdartcolorshex

Create a flutter Color object and Compute hex color code for an arbitrary string flutter


Most of the time, dynamic Colors in flutter will fetch from the server. But what if we need to generate a dynamic color just based on title or name? Is there any way to convert a simple string to a color on flutter? For example:

  • input:
String title = "Lord of the rings";
  • Output
Color color = getTitleColor(title);

Solution

  • Yes, the best way is to create a new extension on String model like this

    extension StringColor on String {
      Color textToColor() {
        if(isEmpty){
          return Colors.black;
        }
        var hash = 0;
        for (var i = 0; i < length; i++) {
          hash = codeUnitAt(i) + ((hash << 5) - hash);
        }
        return Color(hash + 0xFF000000);
      }
    }