-1

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);
hasanm08
  • 488
  • 4
  • 13
  • Does this answer your question? [How do I use hexadecimal color strings in Flutter?](https://stackoverflow.com/questions/50081213/how-do-i-use-hexadecimal-color-strings-in-flutter) – nvoigt Apr 19 '23 at 11:17
  • @nvoigt no this is for titles and names such as "Lord of rings" or "Amirhassan Amirmahani" – hasanm08 Apr 19 '23 at 11:22

1 Answers1

1

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

hasanm08
  • 488
  • 4
  • 13