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是constText,所以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
相关产品推荐
相关产品推荐

