當在 TextFormField 中獲取資料時,我想禁用表單的提交按鈕。
在 TextFormField 上方,我有一個 datePicker,如果在 datePicker 中選擇的特定日期在 DB 中有資料,則 TextFormFilled 將填充此資料并禁用。
以下是我如何使用 FutureBuilder 執行此操作:
FutureBuilder<double?>(
future: getTimes(selectedDate),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData){
return TextFormField(
controller: _timeController,
textAlign: TextAlign.center,
enabled: false,
decoration: InputDecoration(
hintText: snapshot.data.toString() " h",
contentPadding: EdgeInsets.zero,
filled: true,
fillColor: Colors.white
),
);
}
else {
return TextFormField(
controller: _timeController,
textAlign: TextAlign.center,
enabled: true,
decoration: InputDecoration(
hintText: "0 h",
contentPadding: EdgeInsets.zero,
filled: true,
fillColor: Colors.white
),
);
}
}
)
問題是我也想禁用表單的提交按鈕,所以我創建了一個_isButtonDisabled變數,
這是我的按鈕代碼:
ElevatedButton(
onPressed: _isButtonDisabled == true ? null : () async {postTimes(await convertDate(selectedDate), convertTime(_timeController.text));},
child: Text("Submit")
),
如果在我的 futureBuilder 中獲取資料,我嘗試使用 setState 方法將此變數設定為 true:
FutureBuilder<double?>(
future: getTimes(selectedDate),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData){
setState(() {
_isButtonDisabled = true;
});
return TextFormField(...
哪個回傳我這個錯誤:FlutterError (setState() 或 markNeedsBuild() 在構建程序中呼叫。
我試圖通過使用本主題中的一些函式示例來封裝 setState 方法,但它并沒有真正起作用,因為 TextFormField 的內容在獲取的資料和默認文本之間不斷閃爍,而不僅僅是顯示獲取的資料。
謝謝你的幫助,
uj5u.com熱心網友回復:
您不需要setState在您的情況下呼叫:您不需要重建小部件。FutureBuider 收到新資料后會自動為你重建。
你唯一需要做的就是確保你ElevatedButton在里面FutureBuilder。
改變這個:
if (snapshot.hasData){
setState(() {
_isButtonDisabled = true;
});
進入這個:
_isButtonDisabled = true;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341347.html
