问题描述
今天我遇到了以下在颤振中实现渐变的代码片段
Today I came over following snippet of code that implements gradient in 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,但实际上不是.
1) What color system is 0xFF3366FF
this? it looks somewhat similar to HEX, but it isn't.
2) 为什么我们对 const Color()
使用 const
而不是 new Color()
我理解两者不同,但是 const这里对我来说感觉不直观,我希望它创建一个 new Color()
类实例,类似于我们使用 new Text("Some text")
的方式.如果它需要是常量,为什么 TileMode.clamp
不是常量?
2) Why do we use const
for const Color()
opposed to new Color()
I understand different between both, but const here feels unintuitive for me, I'd expect it to be creating a new Color()
class instance, similarly to how we use new Text("Some text")
. If it needs to be const, why isn't TileMode.clamp
also a const?
推荐答案
来自 Flutter 源码
From the Flutter source
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)
,则只会创建一个实例.
If you have multiple const Color(0xFF00CCFF)
in your code, only one instance will be created.
const
实例在编译时被评估.在 Dart VM 中,这是加载代码的时间,但在 Flutter 生产中使用 AoT 编译,因此 const 值提供了很小的性能优势.
const
instances are evaluated at compile time.In the Dart VM this is when the code is loaded, but in Flutter production AoT compilation is used and const values therefore provide a small performance benefit.
这篇关于flutter 使用什么颜色系统,为什么我们使用 `const Color` 而不是 `new Color`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!