我正在嘗試將資料從TextFieldwithonChange屬性傳遞到onPressed按鈕。
如果我輸入我的字串如下:
String newTextTitle;
然后我得到錯誤print(newTextTitle);:
不可為空的區域變數 'newTextTitle' 必須在使用前賦值。嘗試給它一個初始化運算式,或者確保它被分配到每個執行路徑上。
所以我把它改成
String? newTextTitle;
那么錯誤就不會再出現了。但是資料不會從TextField我的按鈕傳遞到我的按鈕,實際上是傳遞null.
如果我分配了一些字串,那么它總是列印我分配的內容,而不管TextField.
我的TextField代碼:
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newValue) {
newTextTitle = newValue;
},
),
我的button代碼:
TextButton(
onPressed: () {
print('Passing Test $newTextTitle');
},
),
我的輸出控制臺:
I/flutter (23788):通過測驗 null
這段代碼在舊的顫振中作業得很好。但是現在我用了Flutter 2.5.2并且有一些東西已經改變了。
uj5u.com熱心網友回復:
使用 aTextEditingController是 Flutter 推薦的做你想做的事情的方式。請參閱(
String? newTextTitle; //past it here
Buildwidget(){
String? newTextTitle; //remove from here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/350631.html
