我對 Flutter 非常缺乏經驗,我創建了一個小部件,里面有這段代碼:
使用這樣撰寫的代碼:(不呼叫 ToolModify 函式)
final VoidCallback ToolModify;
onTap: () {
// rest of the code
widget.ToolModify;
},
相反,它是用這樣撰寫的代碼呼叫的:
onTap: widget.ToolModify,
誰能向我解釋為什么會這樣?
因為除了widget.ToolModify之外我還需要寫其他代碼行;我如何在 OnTap 中呼叫 ToolModify 函式:() {...} ?
希望可以有人幫幫我。謝謝 :)
uj5u.com熱心網友回復:
像這樣撰寫代碼是完全合法且良好的風格:
onTap: widget.ToolModify,
在這種情況下,widget.ToolModify表示一個函式,并且您將函式分配給onTap稍后onTap 呼叫該函式。
如果你這樣呼叫它,你會創建一個新的匿名且無引數() {}的函式,它只呼叫另一個函式widget.ToolModify():
onTap: () {
widget.ToolModify();
},
請注意,這widget.ToolModify 表示函式本身。Whilewidget.ToolModify()呼叫不帶引數的函式。
此外,您可以這樣寫,因為您只回傳一個運算式:
onTap: () => widget.ToolModify(),
例子
看看這個定義了一個函式 ad() 的例子,它回傳一個匿名函式,然后將它應用于一些引數:
// This function takes one argument x and returns a new function
// of one parameter
Function(int) add( y ) {
return ( x ) => ( x y );
}
// The above => notation is only applicable, if exactly one expression is returned
// In case the structure of the inner function is more complex, write
// it using non shorthand notation like so
Function(int) divideBy( y ) {
return ( x ) {
assert( y > 0 );
return ( x / y );
};
}
// Use the above function to create two specialist functions
Function(int) add100 = add( 100 );
// Simmilar, but implicitly typed
var add10 = add( 10 );
var halfOf = divideBy( 2 );
var doubleOf = divideBy( 0.2 );
// Now apply two specialized functions
print( add10( 1 ) );
print( add100( 1) );
print( halfOf( 10 ) );
print( doubleOf( 10 ) );
輸出這個:
11
101
5
50
uj5u.com熱心網友回復:
您需要實際呼叫該方法:
onTap: () {
// rest of the code
widget.ToolModify(); // notice the brackets
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459951.html
上一篇:我可以從firebasefirestore獲取資料而不將其放入串列中嗎?
下一篇:為什么應用程式下降
