dart - Flutter 使用什么颜色系统,为什么我们使用 `const Color` 而不是 `new Color`

标签 dart flutter

今天我看到了下面一段在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 值提供了小的性能优势。

另见 How does the const constructor actually work?

关于dart - Flutter 使用什么颜色系统,为什么我们使用 `const Color` 而不是 `new Color`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47996420/

相关文章:

以像素为单位的字符串长度抖动

flutter - 按下后退按钮并重新打开应用程序后,Flutter 卡在启动屏幕上

date - Flutter/Dart : DateTime. fromMillisecondsSinceEpoch 返回不正确的时间

flutter - 整数列表的基本操作

flutter - 使用 Flutter 编写的 Windows 桌面应用程序,编译为机器代码还是字节码?

dart - Flutter:如何在英雄动画期间更改子元素的大小?

flutter - 在抖动中出现空错误时调用了PhotoURL

dart - 为纸张项目分配变量值

dart - Dart 中预先填充空格的字符串

flutter - 参数 'id' 因其类型不能有 'null' 的值,但隐含的默认值为 'null'