gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:20:37 24 4
gpt4 key购买 nike

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

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

最佳答案

根据 documentation :

Stateless widget are useful when the part of the user interface you are describing does not depend on anything other than the configuration information in the object itself and the BuildContext in which the widget is inflated.

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

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

关于flutter - 为什么任何小部件都是无状态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55866663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com