我有這個 StatefulWidget,它應該根據條件從 MySQL 資料庫檢索資料並將這些檢索到的值添加到數組中,以便我可以使用數組值顯示在 ListView 上。我的問題是,有時當陣列 (_fileValues
) 和 _custUsername
變數為空或未更新時,不會引發例外狀況。
這是我的有狀態小工具 (main.dart
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
|
UsernameGetter
類別(此類將根據文字欄位輸入中的電子郵件從資料庫表中檢索使用者使用者名稱)
當我從UsernameGetter
類別列印_usernameDetected
類別時,它會傳回傳回字串的更新版本,但是當我將_custUsername
# 指派給 UsernameValue
從main.dart
時,它不會更新,有時會傳回null值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
NameGetter
類別(檢索儲存在文字列中的使用者項目名稱)
對於 NameGetter
類,與 UsernameGetter
發生相同的情況。當我從 main.dart
檢索值並將值加到 _fileValues
列表中時,有時該值為空,有時該值未更新。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
我不確定我的錯誤在哪裡,但我很確定我犯了很多錯誤,我需要有人幫我解決。特別是關於為什麼列表和變數沒有更新/有時是空的。
參考連結:
Flutter ListView 未更新
我在 flutter 中的列表沒有更新程式碼中的問題
為什麼變數值在flutter中不刷新?
P粉5216974192024-04-02 09:09:07
callData()
方法的精簡版本如下:
var foo; void callData() { someAsyncFunction().then( ... foo = value ... ); anotherAsyncFunction(foo).then( ... ); }
如前所述,anotherAsyncFunction(foo)
在someAsyncFunction()
之後、then()
之前 立即呼叫> 分配foo
的值。
您可以透過有策略地插入 print()
語句來親自觀察此行為。
在底層,Future.then()
和 async
/await
是同一件事。然而,當使用async
/await
時,人們通常更容易推斷非同步程式碼的行為,因為這樣它讀起來就像順序執行的程式碼。
雖然您可以使用其中任何一個,但我建議您轉向 async
/await
以使程式碼在閱讀時更容易理解。
以下是如何重構 callData()
的一個範例:
FuturecallData() async { // @ Get username based on user email and assign it to _custUsername variable var custUsername = await UsernameGetter().Connection(_CustEmailInit!); // @ Get item names based on the user username (_custUsername) and add them into // _fileNameStores var namesValues = await NameGetter().Connection(custUsername); setState(() { _fileNameStores.addAll(namesValues); // @ Remove duplicates value and add them into main list (_fileValues) _fileValues.addAll(_fileNameStores.toSet()); }); }
這樣寫,很明顯 custUsername
是在呼叫 NameGetter().Connection(custUsername)
之前分配的。
請務必通讀非同步程式設計:futures、async、await。