簡體   English   中英

在 flutter 中按下時更改按鈕的顏色

[英]Change color of button when pressed in flutter

我有這個模擬 ElevatedButton 的小部件標簽。 我想要的是每次點擊時更改按鈕本身的顏色。 我認為在回調“ontap”中設置 state 會起作用,但沒有任何反應。

我試過了,但沒有顏色變化,它保持藍色:

        return SingleChildScrollView(
      child: Wrap(
        children: <Widget>[
          for (var i = 0; i < attributesFoundDistinct.length; i++)
            FilterChipCustom(
                color: filteredByTag == true ? Colors.red : Colors.blue,
                label: attributesFoundDistinct[i],
                onSelected: (value) {
                  setState(() {
                    snapList = snapListAll;
                    _filteredDogList = snapList
                        .where((dog) => (dog[attributesFoundDistinct[i]]
                            .toLowerCase()
                            .contains(textControllerValue.toLowerCase())))
                        .toList();
                    filteredByTag = true;
                  });
                }),
        ],
      ),
    );
  }
}


class FilterChipCustom extends StatelessWidget {
  var label;
  var color;
  final ValueChanged<bool?> onSelected;

  FilterChipCustom(
      {Key? key, required this.label, this.color, required this.onSelected})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FilterChip(
      selectedColor: color,
      labelPadding: EdgeInsets.all(5.0),
      avatar: CircleAvatar(
        backgroundColor: Colors.grey.shade600,
        child: Text(label[0].toUpperCase()),
      ),
      label: Text(
        label,
        style: TextStyle(
          color: Colors.white,
        ),
      ),
      onSelected: onSelected,
      backgroundColor: Colors.blue,
      elevation: 6.0,
      shadowColor: Colors.grey[60],
      padding: EdgeInsets.all(6.0),
    );
    ;
  }
}

執行沒有到達這一行: filteredByTag = true;

這可能是因為:

  • onTap 實際上並沒有被調用
  • 此行之前的行拋出異常

您應該調試並查看 onTap function 中到底發生了什么。 一些猜測: snapListAll可能是 null,或者點左側的其他任何東西都可能是 null。

 setState(() {
                    snapList = snapListAll;
                    _filteredDogList = snapList
                        .where((dog) => (dog[attributesFoundDistinct[i]]
                            .toLowerCase()
                            .contains(textControllerValue.toLowerCase())))
                        .toList();
                    filteredByTag = true; //Here
                  });

這里filteredByTag 總是正確的。 所以它總是會顯示紅色。

如果您需要更改兩個 colors 或者單擊按鈕,我認為您可以嘗試此操作。

 filteredByTag = !filteredByTag;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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