【问题标题】:Why would any widget ever be stateless?为什么任何小部件都是无状态的?
【发布时间】:2019-04-26 11:28:54
【问题描述】:

什么类型的小部件不会有不能改变的状态/属性?我想不出任何可能。按钮有文本,图像有大小,文本有颜色等等。什么小部件不会有某种属性?

在 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'),
    );
  }
}

【问题讨论】:

  • 属性!= 状态。

标签: flutter


【解决方案1】:

根据documentation

无状态小部件在您作为用户界面的一部分时很有用 所描述的不依赖于除 对象本身和BuildContext中的配置信息 小部件被膨胀了。

那么这到底意味着什么? StatelessWidget 不包含它需要随着时间的推移跟踪更改的属性 - 例如,一个文本框。
StatelessWidget 的一个典型示例是布局。它确实包含可能需要或可能不需要分别维护状态的子项,但您的布局本身不需要。

这样做的一个巨大优势是StatelessWidget 不会触发重建。并非所有小部件树都会响应文本框的文本更改,只有当它们发生更改时被跟踪的部分。不用说,这会对性能产生巨大影响。

【讨论】:

    【解决方案2】:

    有两种状态:

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

    StatelessWidget 是一个没有内部状态的小部件——但它可以使用外部状态。

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

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 2021-05-30
      • 2018-02-06
      • 2019-10-06
      • 2018-05-10
      • 2019-01-31
      • 2021-09-15
      相关资源
      最近更新 更多