Dart 中的常量构造函数和函数

Min*_*tin 5 dart flutter

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

无效常量值

为什么使用 const 时不能使用 onPressed?有人可以解释一下吗?抱歉我是新手。

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

mmc*_*n20 8

可以,但是匿名函数不能const在 dart 中。一切传递给你的IconButton需求都是const为了IconButton存在const。也就是说,独立函数和静态函数可以用作const

// should be a standalone function (or a static function)
void hello() {
  print('Hello');
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用IconButtonas const

 const IconButton(
        icon: Icon(
          Icons.search,
          color: Colors.white,
        ),
        tooltip: 'Search',
        onPressed: hello,
      )
Run Code Online (Sandbox Code Playgroud)