我有一个函数,它把Color作为参数。我想为这个函数中的颜色生成一个随机样本列表。例如,如果传递的颜色是Colors.amber,则需要如下所示的列表:
[ Colors.amber100,Colors.amber800,Colors.amber500,Colors.amber900,Colors.amber300.]
有可能吗?如有任何建议或帮助,将不胜感激。提前谢谢你。
发布于 2021-07-17 10:23:21
找到了一个简单的解决方案
让颜色作为传递的参数。现在,在Colors.primaries列表中找到该颜色的索引。
for(int i=0;i<Colors.primaries.length;i++){
if(color==Colors.primaries[i]){
colorIndex=i;
}
}使用此索引生成首选颜色的随机样本。
Colors.primaries[colorIndex][Random.nextInt(9) * 100]发布于 2021-07-14 20:17:08
您只可以随机选择“加色”列表:
颤振颜色
List<int> types = [50, 100, 200, 300, 400, 600, 700, 800, 900]将0.8之间的数字随机化
int get getRandomNumber => 0 + Random().nextInt(8 - 0);用于获取随机颜色
Color? selectedColor = Colors.amber[types[getRandomNumber]];更新:
使用这方法扩展,我们可以创建一个“解决方案”
extension HexColor on Color {
/// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
Color fromHex(String hexString) {
final buffer = StringBuffer();
if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
buffer.write(hexString.replaceFirst('#', ''));
return Color(int.parse(buffer.toString(), radix: 16));
}
/// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
'${alpha.toRadixString(16).padLeft(2, '0')}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}';
}并且使用这个函数
Color getRandomColor(String selectedColor) {
final List<int> types = [50, 100, 200, 300, 400, 600, 700, 800, 900];
int getRandomNumber = 0 + Random().nextInt(8 - 0);
return Color.fromHex(selectedColor)[types[getRandomNumber]];
}//true will return "#ffffff", false will return "ffffff"
Color _color = getRandomColor(Color.red.toHex(true));https://stackoverflow.com/questions/68384062
复制相似问题