我刚刚开始掌握 Flutter 的窍门,但我无法弄清楚如何设置按钮的启用状态。
从文档中,它说将 onPressed
设置为 null 以禁用按钮,并给它一个值以启用它。如果按钮在生命周期内继续处于相同状态,这很好。
我觉得我需要创建一个自定义的有状态小部件,它允许我以某种方式更新按钮的启用状态(或 onPressed 回调)。
所以我的问题是我该怎么做?这似乎是一个非常简单的要求,但我在文档中找不到任何关于如何做到这一点的内容。
谢谢。
最佳答案
我认为您可能想要引入一些帮助函数来build
您的按钮以及 Stateful 小部件以及一些要关闭的属性。
isButtonDisabled
)onPressed
值设置为 null
或某个函数 onPressed: () {}
isButtonDisabled
作为此条件的一部分并返回 null
或某些函数。setState(() => isButtonDisabled = true)
来翻转条件变量。build()
方法,并且按钮将使用 null
按下处理程序呈现并被禁用。这里是使用 Flutter 计数器项目的更多上下文。
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
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: <Widget>[
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
和 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();
};
}
}
https://stackoverflow.com/questions/49351648/