flutterdartcolorsmessage

Get color for each different message sender randomly (like a hash)


I'm working on an app which (among many other features) gets messages sent to a student from the school administration system of Hungary (ekreta.hu).

I'd like to have profile pictures for the senders of these messages, but the API doesn't provide them, so this is what I came up with: Similar to Gmail, the first letter of their name appears on a randomly colored circle.

My question is: How do I get a color that is random, but unique to each sender? It should behave like a hash, so it would generate the same color from the same input (from the same sender's name).

Here's an example of the layout


Solution

  • I figured it out from a JavaScript answer, translated it to Dart. This generates a hash from the given string and returns a Dart Color.

    Color stringToColor(String str) {
      int hash = 0;
    
      for (int i = 0; i < str.length; i++) {
        hash = str.codeUnitAt(i) + ((hash << 5) - hash);
      }
    
      String color = '#';
    
      for (int i = 0; i < 3; i++) {
        var value = (hash >> (i * 8)) & 0xFF;
        color += value.toRadixString(16);
      }
    
      color += "0";
      color = color.substring(0, 7);
    
      print(color);
    
      return colorFromHex(color);
    }