我刚刚开始掌握Flutter 的诀窍,但我想不出如何设置按钮的启用状态.
在文档中,它说将onPressed
设置为NULL来禁用按钮,并给它一个值来启用它.如果按钮在整个生命周期中继续处于相同状态,则可以这样做.
我得到的印象是,我需要创建一个自定义的Stateful小部件,它将允许我以某种方式更新按钮的启用状态(或onPressed回调).
所以我的问题是我该怎么做?这似乎是一个非常简单的要求,但我在文档中找不到任何关于如何做到这一点的信息.
谢谢你.
我刚刚开始掌握Flutter 的诀窍,但我想不出如何设置按钮的启用状态.
在文档中,它说将onPressed
设置为NULL来禁用按钮,并给它一个值来启用它.如果按钮在整个生命周期中继续处于相同状态,则可以这样做.
我得到的印象是,我需要创建一个自定义的Stateful小部件,它将允许我以某种方式更新按钮的启用状态(或onPressed回调).
所以我的问题是我该怎么做?这似乎是一个非常简单的要求,但我在文档中找不到任何关于如何做到这一点的信息.
谢谢你.
我想你可能想在你的按钮上引入一些帮助函数,以及一个有状态的小部件,以及一些要关闭的属性.
isButtonDisabled
)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();
};
}
}