小部件的“const”是否只需要在有状态小部件中使用?

Sye*_*yed 1 dart flutter

很明显,StatefulWidget如果状态发生变化,则const Text('...')不会重建。

class _SomeWidgetState extends State<SomeWidget> {
  @override
  Widget build(BuildContext context) {
    return const Text('Some Static Text'); // doesn't rebuild
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,我的问题是:使用constin有什么好处StatelessWidget吗?

class ListItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const Text('Some Static Text') // Is `const` useful here?
  }
}
Run Code Online (Sandbox Code Playgroud)

Rém*_*let 6

是的,它很有用。

build 中的 Const 构造函数对所有类型的小部件都很有用,包括 StatelessWidget 和其他不太常见的小部件,如 InheritedWidget 或 RenderObjectWidget。

请记住,所有小部件都可能带有参数,因此您可能有:

class MyStateless extends StatelessWidget {
  const MyStateless({Key key, this.count}): super(key: key);

  final int count;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text('$count'),
        const Text('static text'),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的无状态小部件可能会使用不同的参数进行重建,例如:

MyStateless(count: 0);
Run Code Online (Sandbox Code Playgroud)

到:

MyStateless(count: 42);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,使用const Text('static text')不会导致此文本重建。