创建一个Flutter颜色对象并计算任意字符串的十六进制颜色代码。

huangapple go评论63阅读模式
英文:

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

问题

以下是翻译好的内容:

大部分情况下,在Flutter中,动态颜色将从服务器获取。但是如果我们需要根据标题或名称生成动态颜色怎么办?有没有办法在Flutter中将简单的字符串转换为颜色?例如:

  • 输入:
String title = "指环王";
  • 输出:
Color color = getTitleColor(title);
英文:

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);

答案1

得分: 1

是的,最好的方法是创建一个新的String模型扩展,像这样:

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);
  }
}
英文:

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 &lt; length; i++) {
      hash = codeUnitAt(i) + ((hash &lt;&lt; 5) - hash);
    }
    return Color(hash + 0xFF000000);
  }
}

huangapple
  • 本文由 发表于 2023年4月19日 19:12:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定