为每个不同的消息发件人随机获取颜色(如哈希)

问题描述 投票:0回答:2

我正在开发一个应用程序(其中包括许多其他功能),它从匈牙利的学校管理系统(ekreta.hu)接收向学生发送的消息。

我想为这些邮件的发件人提供个人资料图片,但API没有提供这些图片,所以我想到了:与Gmail相似,它们名称的首字母出现在随机彩色的圈子。

我的问题是:如何获得一种随机的颜色,但对于每个发件人来说都是唯一的?它的行为应类似于哈希,因此它将从相同的输入(从相同的发件人名称)生成相同的颜色。

Here's an example of the layout

flutter dart colors message
2个回答
0
投票

您可能会将这些消息保留在诸如ReceivedMessages之类的地方。比方说,receivedMessages是带有发送者和值的键的映射,那么您可以在发送者第一次发送消息时为其指定随机颜色,将其另存为该键的值,然后使用相同的颜色。

CircleAvatar( color: (receivedMessages[sender] == null) ? randomColor : receivedMessages[sender][color],  child: Message(), ... other attributes )


0
投票

我从JavaScript答案中得出答案,然后将其翻译为Dart。这将从给定的字符串生成哈希值,并返回Dart颜色。

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.