【问题标题】:Is const keyword still better to have in Flutter (Dart 2) for performance?在 Flutter(Dart 2)中使用 const 关键字来提高性能是否更好?
【发布时间】:2019-10-17 04:42:33
【问题描述】:

我已经阅读了很多关于 const 讨论的文章和 Stack Overflow 问题/答案。

人们说如果你创建一个 const 实例,该实例只会被创建一次。如果您稍后尝试创建相同的实例,则将返回旧实例并且不需要新的内存分配。这听起来在性能上更好。例如:

child: Column(
  children: <Widget>[
    Container(padding: const EdgeInsets.symmetric(horizontal: 8.0)),
    Container(padding: const EdgeInsets.symmetric(horizontal: 8.0)),
   ]
)

上面的代码只是展示了这个想法。 const EdgeInsets.symmetric(horizontal: 8.0)) 不必在同一个小部件类中。

现在,当我阅读official Dart 2 announcement 时,它有一个相反的例子。我只是在这里复制那篇文章中的代码块:

// Before Dart 2
Widget build(BuildContext context) {
  return new Container(
    height: 56.0,
    padding: const EdgeInsets.symmetric(horizontal: 8.0),
    decoration: new BoxDecoration(color: Colors.blue[500]),
    child: new Row(
      ...
    ),
  );
}

// After Dart 2
Widget build(BuildContext context) =>
  Container(
    height: 56.0,
    padding: EdgeInsets.symmetric(horizontal: 8.0),
    decoration: BoxDecoration(color: Colors.blue[500]),
    child: Row(
      ...
    ),
  );

因此,我是否仍应在 Dart 2 中添加 const 关键字?

一开始,我删除了所有的 const 关键字。但是当我读到人们建议添加 const 关键字以提高性能时,我正在添加 const 关键字。但是今天,当我偶然看到这篇文章时,我完全糊涂了。对于这种情况, const auto 是否会在 Dart 2 Flutter 引擎中暗示?或者这在 Flutter 中是否重要?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    Dart 2 颤振引擎中的 const auto 是否会隐含

    没有。 Dart 2 并不暗示 const 关键字。它会删除多余的。

    Foo()
    

    const Foo()
    

    等价的。

    另一方面:

    const Foo(Bar())
    

    const Foo(const Bar())
    

    确实是等价的。

    所以是的,const 关键字仍然是性能优化所必需的。

    【讨论】:

    • 非常感谢您的快速回答。但它并没有回答我真正的问题。我应该在颤振中添加 const 关键字吗?公告显示我应该删除它。对性能有影响吗?非常感谢。
    • 是的,你应该这样做。事实上,您应该在您的analysis_options.yaml 上启用prefer_const_constructor lint 选项。
    • 我以为我有analysis_options.yaml,但是当我检查根目录时,flutter create 默认情况下不会创建它....你能告诉我推荐的analysis_options.yaml 文件应该是什么样子吗颤振(示例文件)?如果您认为我应该在颤振中添加 const,您能否也更新答案?然后我可以将其标记为答案。非常感谢。
    • 更新:我找到了这个文件github.com/flutter/flutter/blob/master/analysis_options.yaml。所以现在不需要给我举个例子了。请更新答案以获得在颤振中使用 const 的建议(dart 2)。然后我可以将其标记为最终答案。非常感谢。
    猜你喜欢
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2019-06-01
    • 2022-11-20
    • 2021-05-19
    • 2020-03-02
    相关资源
    最近更新 更多