Flutter - 如何在单击时切换 FlatButton 的颜色?

Flutter - How do I toggle the color of a FlatButton upon click?

我想在按下 FlatButton 时更改颜色。感谢您的帮助。

import 'package:flutter/material.dart';

class ButtonCalculate extends StatelessWidget {

@override
Widget build(BuildContext context) {
var container = Container(
  decoration: BoxDecoration(gradient: null,
  borderRadius: BorderRadius.circular(20.0),
  //color: Colors.amber,
  boxShadow: [
    BoxShadow(
      color: Colors.black12,
      offset: Offset(0.0, 0.5),
      blurRadius: 40.5,
    ),
  ]),
  child: new FlatButton(
    child: Image(
      image:AssetImage('assets/2.0x/Button_Calculate.png')),
    onPressed: () {},
  ),
  width: 290.0,
);

先把你的class改成StatefulWidget:

 import 'package:flutter/material.dart';

 class ButtonCalculate extends StatefulWidget {

 ButtonCalculate({Key key,}): super(key: key);

  @override
  _ButtonCalculateState createState() => new _ButtonCalculateState();
 }

然后在Stateclass中添加一个检测按钮状态的变量:

class _ButtonCalculateState extends State<ButtonCalculate> {

var pressed = false ; // This is the press variable

@override
Widget build(BuildContext context) {
var container = Container(
  decoration: BoxDecoration(gradient: null,
  borderRadius: BorderRadius.circular(20.0),
  color: pressed ? Colors.amber : Colors.blue , // if the button is pressed color will be amber if pressed again it'll go back to blue
  boxShadow: [
   BoxShadow(
    color: Colors.black12,
    offset: Offset(0.0, 0.5),
     blurRadius: 40.5,
   ),
  ]),
  child: new FlatButton(
  child: Image(
  image:AssetImage('assets/2.0x/Button_Calculate.png')),
  onPressed: () {
     setState((){
      pressed = !pressed ; // update the state of the class to show color change
    });
  },
  ),
 width: 290.0,
 );
 // Add the reminder of your code and remember to close the class parenthesis