变量中的 UI 实现片段与最终变量之间的差异



这个来自Google的例子展示了如何在变量中存储UI片段。

var stars = Row(
  mainAxisSize: MainAxisSize.min,
  children: [
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.black),
    Icon(Icons.star, color: Colors.black),
  ],
);
final ratings = Container(
  padding: EdgeInsets.all(20),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      stars,
      Text(
        '170 Reviews',
        style: TextStyle(
          color: Colors.black,
          fontWeight: FontWeight.w800,
          fontFamily: 'Roboto',
          letterSpacing: 0.5,
          fontSize: 20,
        ),
      ),
    ],
  ),
);
请注意,stars UI 部分存储在var变量中

,而 UI ratings部分存储在final变量中。

var stars = Row(...(; 最终评级 = 容器(...(;

我的问题是:

  • 这种差异背后的动机是什么?
  • 何时将一段 UI 存储在 var 变量中,何时存储在final变量中?

名思义,var意味着其值可以在以后更改的东西,而final是一旦分配的值将永远不会更改的东西。因此,您几乎可以使用其中任何一个,这完全取决于您的需要。

var widget = Container(color: Colors.black);
widget = Container(color: Colors.white); // no problem
final widget2 = Container(color: Colors.black);
widget2 = Container(...)// error you can't assign anything to this widget again

最新更新