小编典典

我想你可能要出台一些辅助功能,以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,

);

}

}

在此示例中,我使用内联三元有条件地设置Text and 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

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐