【问题标题】:Flutter - How do I toggle the color of a FlatButton upon click?Flutter - 如何在单击时切换 FlatButton 的颜色?
【发布时间】: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,
);

【问题讨论】:

    标签: android dart flutter widget flutter-animation


    【解决方案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
    

    【讨论】:

    • 感谢您的回答,按下按钮时会放置灰色背景..
    • 如果有帮助,请接受答案,以便其他人知道这对他们有益。
    猜你喜欢
    • 2018-11-24
    • 1970-01-01
    • 2020-12-01
    • 2021-12-18
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多