[英]Constant constructor and Function in Dart
我想要 onPressed 它打印一個文本,但它拋出一個錯誤。
無效的常數值
為什么在使用 const 時不能使用 onPressed? 有人可以解釋一下嗎? 對不起,我是新手。
const IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
tooltip: 'Search',
onPressed: () => print('Hello'),
)
您將IconButton
小部件聲明為常量,這也要求其所有子項也是常量,但 onPressed 箭頭函數是動態的並且在運行時分配,因此它不是常量。
這樣做的原因是 Flutter 使用 const 關鍵字作為小部件永遠不會重建的指示器,因為它會在編譯時被評估並且只會被評估一次。 因此,它的每一部分也必須保持不變。
要解決此問題,您不應將 const 與Icon
小部件一起使用,而不是與整個按鈕小部件一起使用。
IconButton(
icon: const Icon(
Icons.search,
color: Colors.black,
),
tooltip: 'Search',
onPressed: () => print("hello"),
)
您可以,但是無論出於何種原因,匿名函數在 dart 中都不能是const
,並且傳遞給IconButton
所有內容都需要是const
以便IconButton
是const
。 但是,您可以創建一個命名函數並將其傳入。
// should be a standalone function, not a class member.
void hello() {
print('Hello');
}
然后你可以使用IconButton
作為const
:
const IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
tooltip: 'Search',
onPressed: hello,
)
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.