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個變數來儲存每個按鈕的禁用狀態?或者說這種用法是錯誤的?