You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发:如何在StatelessWidget代码中正确使用const语法?

如何在你的Flutter代码中正确添加const以避免报错

在你的代码里,这些位置可以添加const,既能满足Dart的语法要求,又能消除报错:

  • 给MyHomePage构造函数加const:
    因为MyHomePage是StatelessWidget,且成员变量title是final类型,符合const构造的条件。修改后构造函数为:

    const MyHomePage({required this.title});
    

    当传入的title是编译时常量时,整个MyHomePage实例会被const化,能提升Widget树的构建性能。

  • 给静态文本的Text和TextStyle加const:
    Text('Hello, Text Widget')的内容是字符串字面量,其TextStyle的参数(fontSize:25、color:Colors.purple)都是编译时常量,所以可以给两者都加上const:

    child: const Text(
      'Hello, Text Widget',
      style: const TextStyle(
        fontSize: 25,
        color: Colors.purple,
      ),
    ),
    

    如果你用的是Dart 2.17及以上版本,只需要在最外层的Text加const,内层的TextStyle会自动被推断为const,简化后代码如下:

    child: const Text(
      'Hello, Text Widget',
      style: TextStyle(
        fontSize: 25,
        color: Colors.purple,
      ),
    ),
    
  • 给Center加const:
    由于Center的child是const Text,所以Center本身也可以被const化:

    body: const Center(
      child: const Text(
        'Hello, Text Widget',
        style: const TextStyle(
          fontSize: 25,
          color: Colors.purple,
        ),
      ),
    ),
    

修改后的完整代码

class MyHomePage extends StatelessWidget {
  final String title;
  const MyHomePage({required this.title});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          title,
        ),
      ),
      body: const Center(
        child: const Text(
          'Hello, Text Widget',
          style: const TextStyle(
            fontSize: 25,
            color: Colors.purple,
          ),
        ),
      ),
    );
  }
}

(注:Dart 2.17+版本可简化内层const,仅保留最外层const即可)

内容的提问来源于stack exchange,提问作者ParkJunYoung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:42:15