@override
Widget build(BuildContext context) {
var backgroundColor = Colors.orange; // this color could be anything
return Scaffold(
body: Center(
child: Container(
padding: const EdgeInsets.all(12),
color: backgroundColor,
child: Text("Hello World"), // if backgroundColor: Colors.orange this is visible but if backgroundColor: Colors.black, it isn't visible
),
),
);
}
输出(backgroundColor:Colors.orange,文本可见):
输出(backgroundColor:Colors.black,文本不可见):
答案 0 :(得分:1)
您可以使用Color类的computeLuminance()。像这样:
@override
Widget build(BuildContext context) {
var backgroundColor = Colors.orange; // this color could be anything
var foregroundColor = backgroundColor.computeLuminance() > 0.5 ? Colors.black : Colors.white;
return Scaffold(
body: Center(
child: Container(
padding: const EdgeInsets.all(12),
color: backgroundColor,
child: Text("Hello World", style: TextStyle(color: foregroundColor)),
),
),
);
}
当然,您需要使用亮度IF语句... 1.0是白色,而0.0是黑色。例如,黄色大约为0.8。