繁体   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