英文:
Create a flutter Color object and Compute hex color code for an arbitrary string flutter
问题
以下是翻译好的内容:
大部分情况下,在Flutter中,动态颜色将从服务器获取。但是如果我们需要根据标题或名称生成动态颜色怎么办?有没有办法在Flutter中将简单的字符串转换为颜色?例如:
- 输入:
String title = "指环王";
- 输出:
Color color = getTitleColor(title);
- 如果需要任何包,请添加
- 如果您知道在整个项目中添加的简洁方法,请添加
如果您想与我联系:
基于Flutter Web的我的简历网页
英文:
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);
- List item
- List item
- if it needs any package, please add
- if you know a clean way to add among all the project, please add
if you want to contact me:
My resume web page based on flutter web
答案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 < length; i++) {
hash = codeUnitAt(i) + ((hash << 5) - hash);
}
return Color(hash + 0xFF000000);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论