【问题标题】:prefer const literals as parameters of constructors on @immutable classes in android studio更喜欢 const 文字作为 android studio 中 @immutable 类的构造函数的参数
【发布时间】:2021-08-12 13:54:21
【问题描述】:

在下面的代码中,我收到“更喜欢 const 文字作为 @immutable 类上的构造函数的参数”的检查警告,这很烦人。我该怎么做才能让它消失?

screenshot from ide

Container(
        margin: const EdgeInsets.all(20),
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'Enter a search term'),
            ),
            Text("these are the search results", textAlign: TextAlign.left),
          ],
        ),
      )

我试图让每个构造函数都调用 'const' 无济于事。

Container(
        margin: const EdgeInsets.all(20),
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const TextField(
              decoration: const InputDecoration(
                  border: const OutlineInputBorder(),
                  hintText: 'Enter a search term'),
            ),
            const Text("these are the search results", textAlign: TextAlign.left),
          ],
        ),
      ),

【问题讨论】:

    标签: android-studio dart jetbrains-ide


    【解决方案1】:

    只需将列表标记为 const:

    Container(
        margin: const EdgeInsets.all(20),
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: const [
            TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'Enter a search term'),
            ),
            Text("these are the search results", textAlign: TextAlign.left),
          ],
        ),
      ),
    

    【讨论】:

    • 为什么要将列表定义为常量?
    • 通过使列表const 列表和列表中的所有内容都将成为编译时常量。这只有在列表中的所有内容都可以是const 时才能完成。好处是列表只会在编译时创建一次,而不是每次调用周围的build 方法时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多