今天我来看一下在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个是什么 colored颜色 系统?它看起来有点像祸不单行,但它不是.

2)为什么我们用const代替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编译,因此常量值提供了很小的性能优势.

另见How does the const constructor actually work?

Dart相关问答推荐

聆听Firestore计数()

列表、捕获和...REST";元素的模式匹配

在异步方法中,有没有更优雅的方式在DART中等待!=NULL?

Dart 列表中的 addAll() 和 followBy() 有什么区别?

在Flutter中重命名文件/图像

如何在 Dart 中实现继承?

从 Future 实例中获取值

如何在 Flutter 中将 textEditiing 控制器与 Provider 一起使用

如何使用Flutter在按钮网格中滑动(swipe)/拖动(drag) 2 个或更多按钮

如何用 Flutter 在同屏路由上制作英雄风格的动画?

Dart JavaScript 与 jQuery 的互操作回调

如何在 Flutter 中忽略整个文件的 lint 规则?

如何在Flatter中设置特定容器中所有文本的 colored颜色 ?

Flitter中的谷歌 map 没有出现

如何使用flatter删除Firestore文档中的字段

在 Flutter 的 TextFormField 中管理事件

Dart 的服务器端框架

如何初始化构造函数主体中的最终字段?

将多张map合并/合并为一张map

Dart 字符串比较器