【问题标题】:Constant constructor and Function in DartDart 中的常量构造函数和函数
【发布时间】:2021-12-25 19:54:56
【问题描述】:

我想 onPressed 打印一个文本,但它抛出一个错误。

无效的常量值

为什么我在使用 const 时不能使用 onPressed?有人可以解释吗?对不起,我是新手。

 const IconButton(
        icon: Icon(
          Icons.search,
          color: Colors.white,
        ),
        tooltip: 'Search',
        onPressed: () => print('Hello'),
      )

【问题讨论】:

  • () => print('Hello') 不是常数。
  • stackoverflow.com/a/69214531 上查看我的注释:允许 lambdas 成为 const 不是免费的。

标签: flutter dart


【解决方案1】:

您将 IconButton 小部件声明为 const,这要求其所有子级也都是 const,但 onPressed 箭头函数是动态的并且在运行时分配,因此它不是常量。

这样做的原因是 Flutter 使用 const 关键字作为小部件的指示符,它永远不会重新构建,因为它将在编译时进行评估,并且只评估一次。因此,它的每一部分也必须保持不变。

要解决此问题,您不应将 const 与 Icon 小部件一起使用,而不应与整个按钮小部件一起使用。

IconButton(
 icon: const Icon(
   Icons.search,
   color: Colors.black,
   ),
 tooltip: 'Search',
 onPressed: () => print("hello"),
 )

【讨论】:

    【解决方案2】:

    你可以,但是匿名函数不能是 dart 中的const。传入IconButton 的所有内容都必须是const,才能使IconButton 成为const。也就是说,独立函数和静态函数都可以用作const

    // should be a standalone function (or a static function)
    void hello() {
      print('Hello');
    }
    

    然后你可以将IconButton 用作const

     const IconButton(
            icon: Icon(
              Icons.search,
              color: Colors.white,
            ),
            tooltip: 'Search',
            onPressed: hello,
          )
    

    【讨论】:

    • 函数hello一定是const吧?
    • hello 函数将被视为const,只要它是独立函数(顶级函数)或静态函数。如果定义为类的(非静态)方法,则不会被视为const
    • 感谢重播
    【解决方案3】:
    Read Dart official Documentation [const modifier][1]
    when we use const key 
    const IconButton(             //Here you are use const keyword
            icon: Icon(
              Icons.search,
              color: Colors.white,
            ),
            tooltip: 'Search',
            onPressed: () => print('Hello'), //error show here: Invalid constant value.
          )
        
    
    Use this after Remove Const key modifier prefect work onPress
    IconButton(
            icon: Icon(
              Icons.search,
              color: Colors.white,
            ),
            tooltip: 'Search',
            onPressed: () => print('Hello'),
          )
    
    
      [1]: https://api.flutter.dev/flutter/services/GtkKeyHelper/modifierShift-constant.html
    

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 2015-07-24
      • 2023-03-20
      • 2018-12-03
      • 2015-08-27
      • 2018-09-16
      • 1970-01-01
      • 2020-05-05
      相关资源
      最近更新 更多