![](/img/trans.png)
[英]how to change "text" to "text field" when clicking a button in Flutter
[英]How to change Text button Color when I write something in the Text Field
我希望文本按鈕在文本字段為空時顯示灰色,在文本字段中輸入一些文本時顯示綠色。 我該怎么做?
TextField (),
TextButton(
child: Text("Press Here"),
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)){
return Colors.green;}
return Colors.grey;
}
),
),
),
檢查您輸入的文本是否為空?
TextEditingController textEditingController = TextEditingController();
bool isTextEmpty;
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: textEditingController,
onChanged: (value) {
setState(() {
if (value.length > 0) {
isTextEmpty = true;
} else {
isTextEmpty = false;
}
});
},
),
TextButton(
child: Text("Press Here"),
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (isTextEmpty) {
return Colors.green;
}
return Colors.grey;
}),
),
),
],
);
}
您可以將TextButton
的背景顏色保留為變量,然后在onChange
回調中發生TextField's
值更改時更改變量的值。
查看此示例代碼:
Color primaryColor = Colors.grey;
Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
onChanged: (val) {
setState(() {
primaryColor = val.isNotEmpty ? Colors.green : Colors.grey;
});
},
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey.shade50,
),
),
const SizedBox(height: 16),
SizedBox(
width: MediaQuery.of(context).size.width,
child: TextButton(
onPressed: () {},
style: TextButton.styleFrom(backgroundColor: primaryColor),
child: Text("Submit"),
),
),
],
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.