account(initial_balance) {
deposit(amount) {
dispatch['balance'] = amount; //error message on dispatch here.
return dispatch['balance'];//error message on dispatch here.
}
withdraw(amount) {
if (amount > dispatch['balance']) { //error message on dispatch here.
return 'Insufficient funds';
}
dispatch['balance'] -= amount;//error message on dispatch here.
return dispatch['balance'];//error message on dispatch here.
}
var dispatch = {
'deposit': deposit,
'withdraw': withdraw,
'balance': initial_balance
};
return dispatch;
}
withdraw(account, amount) {
return account['withdraw'](amount);
}
deposit(account, amount) {
return account['deposit'](amount);
}
check_balance(account) {
return account['balance'];
}
我從 python 字典中翻譯了這段代碼,但是在 dart 中我收到以下錯誤
“區域變數調度在宣告之前不能被參考。嘗試在第一次使用之前重命名/移動宣告,這樣它就不會隱藏封閉范圍內的名稱”
關于導致此類錯誤的原因以及如何使用字典而無需在函式之前宣告它的任何想法?該代碼在 python 中作業,我可以在函式的最后部分宣告字典。
uj5u.com熱心網友回復:
正如錯誤訊息所說,dispatch必須在參考之前宣告。您可以在定義本地函式之前dispatch單獨宣告(作為空Map或作為late變數),然后可以稍后添加這些參考。
Map<String, dynamic> account(dynamic initial_balance) {
late Map<String, dynamic> dispatch;
dynamic deposit(dynamic amount) {
dispatch['balance'] = amount;
return dispatch['balance'];
}
dynamic withdraw(dynamic amount) {
if (amount > dispatch['balance']) {
return 'Insufficient funds';
}
dispatch['balance'] -= amount;
return dispatch['balance'];
}
dispatch = <String, dynamic>{
'deposit': deposit,
'withdraw': withdraw,
'balance': initial_balance
};
return dispatch;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511292.html
標籤:扑功能镖字典变量
