更新时间:2022-06-12 06:22:27
我认为您可能想引入一些辅助函数来 build
您的按钮以及一个有状态的小部件
I think you may want to introduce some helper functions to build
your button as well as a Stateful widget along with some property to key off of.
isButtonDisabled
) onPressed
的值直接设置为 null
或某些函数 onPressed:(){}
isButtonDisabled
并返回 null
或某些功能。 setState(()=> isButtonDisabled = true)
来翻转条件变量。 build()
方法并具有新状态,按钮将使用 null
按下处理程序呈现并被禁用。isButtonDisabled
)onPressed
value to either null
or some function onPressed: () {}
isButtonDisabled
as part of this conditional and return either null
or some function.setState(() => isButtonDisabled = true)
to flip the conditional variable.build()
method again with the new state and the button will be rendered with a null
press handler and be disabled.这里是使用Flutter计数器项目的更多上下文。
Here's is some more context using the Flutter counter project.
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
,但将其提取到函数中可能更合适(可以使用同样的方法也可以更改按钮的文本):
In this example I am using an inline ternary to conditionally set the Text
and onPressed
, but it may be more appropriate for you to extract this into a function (you can use this same method to change the text of the button as well):
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();
};
}
}