App开发中比较常用的一个场景是:点击一个按钮button,设置button.setEnabled(false),然后发送一个请求,请求成功返回或失败时将按钮恢复为可以点击的状态:button.setEnabled(true)。
那么在flutter中能实现一样的效果吗?
参考:https://stackoverflow.com/questions/49351648/how-do-i-disable-a-button-in-flutter
先看效果图:
点击第二个按钮,会增加_counter 的值,如果_counter 是奇数,则第一个按钮可以点击,如果_counter 是偶数,则第一个按钮不可点击。
实现代码如下:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
@override
TestMyAppState createState() => new TestMyAppState();
}
class TestMyAppState extends State<MyApp> {
bool _isButton1Disabled;
int _counter = 1;
GlobalKey<ScaffoldState> _key;
@override
void initState() {
_isButton1Disabled = false;
}
void _incrementCounter() {
setState(() {
_counter++;
if (_counter % 2 == 0) {
_isButton1Disabled = true;
} else {
_isButton1Disabled = false;
}
});
}
@override
Widget build(BuildContext context) {
_key= new GlobalKey<ScaffoldState>();
return new MaterialApp(
home: new Scaffold(
key: _key,
appBar: new AppBar(title: new Text("test app")),
body: new Container(
alignment: Alignment.center,
child: new Container(
child: new Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: buildButtons(),
)))));
}
List<Widget> buildButtons() {
List<Widget> list = [
_buildButton1(_counter),
_buildSpaceView(20.0), //在两个按钮间添加一点间隔
_buildButton2()
];
return list;
}
Widget _buildSpaceView(double _height) {
return new Container(height: _height);
}
RaisedButton _buildButton1(int counter) {
return new RaisedButton(
padding: new EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
child: new Text(
'count: ' + counter.toString(),
style: new TextStyle(
fontSize: 18.0, //textsize
color: Colors.white, // textcolor
),
),
color: Theme.of(context).accentColor,
elevation: 4.0,
//shadow
splashColor: Colors.blueGrey,
onPressed: _getBtn1ClickListener());
}
RaisedButton _buildButton2() {
return new RaisedButton(
padding: new EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
child: new Text(
'click me',
style: new TextStyle(
fontSize: 18.0, //textsize
color: Colors.white, // textcolor
),
),
color: Theme.of(context).accentColor,
elevation: 4.0,
//shadow
splashColor: Colors.blueGrey,
onPressed: _getBtn2ClickListener());
}
Function _getBtn2ClickListener() {
return () {
_incrementCounter();
};
}
_getBtn1ClickListener() {
if (_isButton1Disabled) {
return null;
} else {
return () {
_key.currentState.showSnackBar(new SnackBar(
content: new Text('Hello!'),
));
};
}
}
}
可以看出,flutter里的无状态控件实际用起来还是比较麻烦的,如果界面上有10个按钮,难道就要创建10个变量来保存每个按钮的禁用状态?或者说这种用法是错误的?