Flutter-单击后如何切换FlatButton的颜色? [英] Flutter - How do I toggle the color of a FlatButton upon click?

查看:83
本文介绍了Flutter-单击后如何切换FlatButton的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to change the color when the FlatButton is pressed. Thanks for your help.

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();
 }

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

Then in the State class add a variable to detect the button 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的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆