[英]change color of the Flutter's FlatButton onPressed
我想在單擊按鈕時更改按鈕的顏色和文本。 但它沒有改變。 我在 setState 中更改我的變量,並使用三元運算符設置文本和顏色。 我希望你能幫助伙計們。
Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 15),
alignment: Alignment.bottomCenter,
child: SizedBox(
width: double.infinity, //Full width
height: 40,
child: FlatButton(
child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
onPressed: () {
setState(() {
stopSelling = !stopSelling;
});
},
textColor: Colors.white,
color: stopSelling?Colors.red:Colors.green,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
)
),
),
你的代碼是完美的,但我不知道你在哪里聲明你的 stopSelling 變量,但我很確定你已經在 build() 方法中聲明了 stopSelling,所以你必須在 build() 方法之外和內部聲明 stopSelling 變量類(有狀態或無狀態)。
它是 flutter 生命周期規則,當調用 setState() 時,那時 build() 方法會自動調用,它會像以前一樣影響你的變量。
嘗試這個....
Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 15),
alignment: Alignment.bottomCenter,
child: SizedBox(
width: double.infinity, //Full width
height: 40,
child: stopSelling? FlatButton(
child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
onPressed: () {
setState(() {
stopSelling = !stopSelling;
});
},
textColor: Colors.white,
color: Colors.red,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
):FlatButton(
child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
onPressed: () {
setState(() {
stopSelling = !stopSelling;
});
},
textColor: Colors.white,
color: Colors.green,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.