小编典典
我认为您可能想向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,
);
}
}
在此示例中,我使用内联三元有条件地设置Textand 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