今天我看到了下面一段在flutter中实现渐变的代码
return new Container(
...
decoration: new BoxDecoration(
gradient: new LinearGradient(
colors: [
const Color(0xFF3366FF),
const Color(0xFF00CCFF),
]
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp
),
),
),
它提出了两个问题:
1) 0xFF3366FF
这个是什么色系?它看起来有点类似于 HEX,但实际上并非如此。
2) 为什么我们使用 const
for const Color()
而不是 new Color()
我理解两者之间的不同,但是 const这里对我来说感觉不直观,我希望它会创建一个 new Color()
类实例,类似于我们使用 new Text("Some text")
的方式。如果需要const,为什么TileMode.clamp
也不也是const?
最佳答案
来自 Flutter 源码
class Color {
/// Construct a color from the lower 32 bits of an [int].
///
/// The bits are interpreted as follows:
///
/// * Bits 24-31 are the alpha value.
/// * Bits 16-23 are the red value.
/// * Bits 8-15 are the green value.
/// * Bits 0-7 are the blue value.
///
/// In other words, if AA is the alpha value in hex, RR the red value in hex,
/// GG the green value in hex, and BB the blue value in hex, a color can be
/// expressed as `const Color(0xAARRGGBB)`.
///
/// For example, to get a fully opaque orange, you would use `const
/// Color(0xFFFF9000)` (`FF` for the alpha, `FF` for the red, `90` for the
/// green, and `00` for the blue).
const Color(int value) : value = value & 0xFFFFFFFF;
const
实例被规范化。
如果您的代码中有多个 const Color(0xFF00CCFF)
,则只会创建一个实例。
const
实例在编译时进行评估。
在 Dart VM 中,这是加载代码的时间,但在 Flutter 生产环境中使用 AoT 编译,因此 const 值提供了小的性能优势。
关于dart - Flutter 使用什么颜色系统,为什么我们使用 `const Color` 而不是 `new Color`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47996420/