簡體   English   中英

當我在文本字段中寫東西時如何更改文本按鈕顏色

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM