为什么任何小部件都将是无状态的?

时间:2019-04-26 11:28:54

标签: flutter

哪种类型的小部件不会具有无法突变的状态/属性?我想不出任何可能。按钮具有文本,图像具有大小,文本具有颜色等。什么窗口小部件永远不会具有某种属性?

在Flutter演示代码中,“ MyApp”是无状态的,但具有属性。为什么这是无状态而不是有状态的?

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

2 个答案:

答案 0 :(得分:1)

根据documentation

  

无状态窗口小部件在用户界面的一部分   所描述的不依赖于   对象本身和BuildContext中的配置信息   小部件膨胀了。

那这到底是什么意思? StatelessWidget不包含需要随时间变化进行跟踪的属性,例如,一个文本框。
StatelessWidget的典型示例是布局。它确实包含可能需要或不一定需要维护状态的子项,但您本身的布局不需要。

此方法的一大优势是StatelessWidget不会触发重建。并非您的所有窗口小部件树都响应文本框的文本更改,而是仅跟踪被跟踪的部分(如果确实发生更改)以及何时更改。不用说这会对性能产生巨大影响。

答案 1 :(得分:0)

有两种状态:

  • 外部状态:传递给构造函数的变量, InheritedWidget ,全局变量等...
  • 内部状态:此小部件创建的对象。

StatelessWidget 是没有内部状态的小部件,但是可以使用外部状态。

StatelessWidget 的参数更改时(包括 InheritedWidget 更新时)将正确更新。

相关问题