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

Posted

技术标签:

【中文标题】Flutter - 如何在单击时切换 FlatButton 的颜色?【英文标题】:Flutter - How do I toggle the color of a FlatButton upon click? 【发布时间】:2019-08-19 10:47:04 【问题描述】:

我想在按下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,
);

【问题讨论】:

【参考方案1】:

首先将您的class 更改为StatefulWidget

 import 'package:flutter/material.dart';

 class ButtonCalculate extends StatefulWidget 

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

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

然后在State类中添加一个变量来检测按钮状态:

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

【讨论】:

感谢您的回答,按下按钮时会放置灰色背景.. 如果有帮助,请接受答案,以便其他人知道这对他们有益。

以上是关于Flutter - 如何在单击时切换 FlatButton 的颜色?的主要内容,如果未能解决你的问题,请参考以下文章

在 Flutter 上单击背景通知时如何导航?

Flutter - 如何在点击时切换 RaisedButton 的颜色?

GoogleMap,如何在单击 Market en Flutter 时删除图标

Flutter单击后退按钮时如何执行

如何在按钮单击时切换下拉菜单并在外部单击时关闭?

当用户单击flutter应用程序中的后缀图标时,如何一一显示密码和确认密码?