为什么在Flutter中`appBar`小部件不是常数?

huangapple go评论66阅读模式
英文:

Why isn't the appBar widget constant in flutter

问题

为什么在尝试以下代码时会出现错误:

  Widget build(BuildContext context) {
    return const Scaffold(
      appBar: AppBar(title: Text("Verify Email")),
      body: Text("需要验证电子邮件 @_@"),
    );
  }

错误信息:

调用的构造函数不是一个const构造函数。
请从构造函数调用中删除 'const'。

为什么AppBar构造函数不是const的?

英文:

Why do I get an error when I try the following:

  Widget build(BuildContext context) {
    return const Scaffold(
      appBar: AppBar(title: Text("Verify Email")),
      body: Text("Needa verify that email dawg @_@"),
    );
  }

Error:

The constructor being called isn't a const constructor.
Try removing 'const' from the constructor invocation.

Why is the AppBar constructor not const?

答案1

得分: 2

因为AppBar小部件包含许多不是常量的属性,所以它不能是常量,也不能接受const

您可以将AppBar小部件视为更多其他小部件的整个子树,如果其中一个不是常量,那么整个AppBar也不是常量。

例如,actions属性接受一个List<Widget>?作为参数,而该列表可以动态更改,对吧?所以它不是常量,因此AppBar也不是常量。

希望你明白我想说的意思,AppBar是许多属性的子集,这些属性不能是常量,这会影响AppBar

英文:

because the AppBar widget contains many properties that are not constant, so it can't also be constant and so it can't accept const.

you can think about the AppBar widget, as a whole sub-tree of more other widgets, and if one of them is not contact, then the whole AppBar is not as well.

For example, the actions property, accepts as an argument a List&lt;Widget&gt;? and that list can be changed dynamically, right ? so it is not constant, and so the AppBar is not.

I hope you get the idea of what I'm trying to say, the AppBar is a sub-set of many properties that can not be constant, and this affects the AppBar.

答案2

得分: 2

AppBar构造函数不是常量(没有const关键字在其构造函数前导),因为在编译程序之前,它具有未知值的属性:

preferredSize = _PreferredAppBarSize(toolbarHeight, bottom?.preferredSize.height);

英文:

AppBar constructor isn't constant (no const keyword leading its constructor) and it couldn't because it have property with unknown value before compiling the program which:

preferredSize = 
          _PreferredAppBarSize(toolbarHeight, bottom?.preferredSize.height);

huangapple
  • 本文由 发表于 2023年2月24日 05:35:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定