如何在点击时更改按钮背景颜色并使其粘在 Flutter 中?

问题描述 投票:0回答:1

我的应用程序中有一个测试,因此当您单击按钮时,如果正确,它会将颜色更改为绿色。背景颜色更改已完成并且工作正常,但我想在单击后将按钮变为绿色,即使用户不再按下它。是否可以改变背景颜色并保持原样?

这是我当前的代码:

                        Consumer<LevelState>(
                    builder: (context, levelState, child) =>
                    FilledButton(
                    onPressed: ()  {
                        if (_buttonpressed = true)
                        // if (score != null )
                        {
                  
                          levelState.setProgress((10).round());
                          levelState.evaluate();
                            {
                              if (score != null)
                                {
                                  // GoRouter.of(context).go('/play/won',extra: {'score': score});
                                }
                            }
                         }
                        else if (score == null)
                        {
                         GoRouter.of(context).go('/');
                        }
                    },
                    style: ButtonStyle(
                    fixedSize: MaterialStateProperty.all(Size(320, 40)),
                    backgroundColor: MaterialStateProperty.resolveWith<Color>(
                    (Set<MaterialState> states) {
                    if (states.contains(MaterialState.pressed)) return Color(0xFF55A318);
                    return  Color(0XFFE4DBC8);
                  }, 
                ),
              ),
                      
                      child: Text('NOT TO REPOST', style: 
                          TextStyle(
                          color: Color(0xFF000000), 
                          fontSize: 14,
                          letterSpacing: 5,
                          fontFamily: 'Helvetica',
                          fontWeight: FontWeight.w500),),
              ),
              
              ),
flutter button background
1个回答
0
投票

请查看下面的代码,希望对您有所帮助。

定义一个布尔变量来跟踪按钮是否被按下

bool _buttonPressed = false;

在您的小部件树中,您的消费者小部件包装在其中

FilledButton

onPressed: _buttonPressed ? null : () {
  setState(() {
    // Update the button state to indicate it has been pressed
    _buttonPressed = true;

    // Your logic when the button is pressed goes here
    levelState.setProgress((10).round());
    levelState.evaluate();

    if (score != null) {
      // GoRouter.of(context).go('/play/won', extra: {'score': score});
    }
  });
},
style: ButtonStyle(
  fixedSize: MaterialStateProperty.all(Size(320, 40)),
  backgroundColor: MaterialStateProperty.resolveWith<Color>(
    (Set<MaterialState> states) {
      // Change the color based on the button state
      if (_buttonPressed) {
        return Color(0xFF55A318); // Green color
      } else {
        return Color(0XFFE4DBC8); // Default color
      }
    },
  ),
),
© www.soinside.com 2019 - 2024. All rights reserved.