如何在颤动中更改按钮颜色

时间:2020-12-29 04:42:21

标签: flutter dart flutter-layout

我想在按下时更改按钮颜色但它不起作用

Expanded(child:  RaisedButton(
              child: Text("Civilian"),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18.0),
            side: BorderSide(color: Colors.black),
          ),
            color: pressAttention ? Colors.blue : Colors.black,
              // 3
              onPressed: () => {

                setState(() {

                  pressAttention = !pressAttention;
                  print(pressAttention);


                })
              },

            ),
            ),

注意:我在上面定义了pressAttention var

3 个答案:

答案 0 :(得分:1)

您必须在 @override 上方初始化您的变量

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool pressAttention = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          RaisedButton(
            child: Text("Civilian"),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.black),
            ),
            color: pressAttention ? Colors.blue : Colors.black,
            // 3
            onPressed: () => {
              setState(() {
                pressAttention = !pressAttention;
                print(pressAttention);
              })
            },
          ),
        ],
      ),
    );
  }
}

答案 1 :(得分:0)

你能重新启动应用程序看看它是否有效吗?因为使用有状态小部件需要热重启才能看到更改,所以热重载在这里不起作用。

答案 2 :(得分:0)

在 RaisedButton 中使用 highlightColor

示例


Expanded(
              child: RaisedButton(
                child: Text("Civilian"),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                  side: BorderSide(color: Colors.black),
                ),
                highlightColor: Colors.deepPurpleAccent,
                onPressed: () {},
              ),
            ),