flutter的按钮如何变为不可选中_如何在Flutter中禁用按钮?
小編典典
我想你可能要出臺一些輔助功能,以build您的按鈕
,以及與一些屬性鍵關(guān)機(jī)的沿有狀態(tài)的部件。
使用StatefulWidget / State并創(chuàng)建一個(gè)變量來保存您的條件(例如isButtonDisabled)
最初將其設(shè)置為true(如果您要這樣做)
呈現(xiàn)按鈕時(shí),請勿將onPressed值直接設(shè)置為null某個(gè)或某些函數(shù)onPressed: () {}而是使用三元或輔助函數(shù)有條件地設(shè)置它(以下示例)
isButtonDisabled作為此條件的一部分進(jìn)行檢查,并返回一個(gè)null或某些函數(shù)。當(dāng)按下按鈕時(shí)(或每當(dāng)您要禁用按鈕時(shí)),使用setState(() => isButtonDisabled = true)來翻轉(zhuǎn)條件變量。
Flutter將build()使用新狀態(tài)再次調(diào)用該方法,并且按鈕將由null按下處理程序呈現(xiàn)并被禁用。
這是使用Flutter計(jì)數(shù)器項(xiàng)目的更多背景信息。
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,
);
}
}
在此示例中,我使用內(nèi)聯(lián)三元有條件地設(shè)置Text and onPressed,但是將其提取到
函數(shù)中可能更合適(您也可以使用相同的方法來更改按鈕的文本):
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
總結(jié)
以上是生活随笔為你收集整理的flutter的按钮如何变为不可选中_如何在Flutter中禁用按钮?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一加手机虚拟键失灵解决方案
- 下一篇: ServiceComb抛出llegalS