簡體   English   中英

Flutter - 如何在單擊時切換 RaisedButton 的顏色?

[英]Flutter - How do I toggle the color of a RaisedButton upon click?

我正在嘗試切換凸起按鈕的顏色。 最初按鈕應該是藍色的,當它被按下時它會變成灰色。 現在我有一個名為 pressAttention 的 bool 值,它被設置為 false。 我正在使用它最初將其設置為 false。 當按下按鈕時,它會切換 pressAttention 布爾值,但該小部件似乎永遠不會再次更新。

new RaisedButton(
                  child: new Text("Attention"),
                  textColor: Colors.white,
                  shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
                  color: pressAttention?Colors.grey:Colors.blue,
                  onPressed: () => doSomething("Attention"),
                )

void doSomething(String buttonName){
if(buttonName == "Attention"){
  if(pressAttention = false){
    pressAttention = true;
  } else {
    pressAttention = false;
  }
}

}

這個按鈕需要在StatefulWidgetStatebuild中創建,並且 State 必須有一個成員變量bool pressAttention = false; . 正如 Edman 所建議的,您需要在setState回調中更改狀態,以便 Widget 重繪。

new RaisedButton(
  child: new Text('Attention'),
  textColor: Colors.white,
  shape: new RoundedRectangleBorder(
    borderRadius: new BorderRadius.circular(30.0),
  ),
  color: pressAttention ? Colors.grey : Colors.blue,
  onPressed: () => setState(() => pressAttention = !pressAttention),
);

如果您希望按鈕為按下狀態更改顏色,您只需要使用 RaisedButton 中的“highlightColor”屬性

       RaisedButton(
          onPressed: () {},
          child: Text("Test"),
          highlightColor: YOUR_PRESSED_COLOR, //Replace with actual colors
          color: IDLE_STATE_COLOR,
        ),

或者你可以使用 rxdart:

import 'package:rxdart/rxdart.dart';

...

bool presssedFavorite = false;
final _pressAttention = BehaviorSubject<bool>();
Observable<bool> get coursesStream => _pressAttention.stream;

...

StreamBuilder(stream: _pressAttention,
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (snapshot.hasData)
  presssedFavorite = snapshot.data;

  return RawMaterialButton(
      onPressed: (){
        _addToFavorites(context);
      },
      child: Padding(
        padding: EdgeInsets.all(5),
        child: Icon(
          presssedFavorite ? Icons.favorite : Icons.favorite_border,
          color: Colors.red,
          size: 17,
        ),
      ),
    );
  },
),

void _addToFavorites(BuildContext context) async{
  //my code...
  _pressAttention.sink.add(!presssedFavorite);
}

它更復雜,但您也可以將此解決方案與 Web 服務、firestore、db 一起使用……並且您可以與 StatelessWidget 和 StatefulWidget 一起使用。

暫無
暫無

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

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