flutter的按钮如何变为不可选中_如何在Flutter中禁用按钮?
小編典典
我想你可能要出臺一些輔助功能,以build您的按鈕
,以及與一些屬性鍵關機的沿有狀態的部件。
使用StatefulWidget / State并創建一個變量來保存您的條件(例如isButtonDisabled)
最初將其設置為true(如果您要這樣做)
呈現按鈕時,請勿將onPressed值直接設置為null某個或某些函數onPressed: () {}而是使用三元或輔助函數有條件地設置它(以下示例)
isButtonDisabled作為此條件的一部分進行檢查,并返回一個null或某些函數。當按下按鈕時(或每當您要禁用按鈕時),使用setState(() => isButtonDisabled = true)來翻轉條件變量。
Flutter將build()使用新狀態再次調用該方法,并且按鈕將由null按下處理程序呈現并被禁用。
這是使用Flutter計數器項目的更多背景信息。
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State {
int _counter = 0;
bool _isButtonDisabled;
@override
void initState() {
_isButtonDisabled = false;
}
void _incrementCounter() {
setState(() {
_isButtonDisabled = true;
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("The App"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
_buildCounterButton(),
],
),
),
);
}
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _isButtonDisabled ? null : _incrementCounter,
);
}
}
在此示例中,我使用內聯三元有條件地設置Text and onPressed,但是將其提取到
函數中可能更合適(您也可以使用相同的方法來更改按鈕的文本):
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _counterButtonPress(),
);
}
Function _counterButtonPress() {
if (_isButtonDisabled) {
return null;
} else {
return () {
// do anything else you may want to here
_incrementCounter();
};
}
}
2020-08-13
總結
以上是生活随笔為你收集整理的flutter的按钮如何变为不可选中_如何在Flutter中禁用按钮?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一加手机虚拟键失灵解决方案
- 下一篇: ServiceComb抛出llegalS