flutter - 点击时如何更改容器的背景颜色

标签 flutter dart

我正在尝试以这种方式更改容器的颜色->

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Color _color = Colors.amber;

    return Scaffold(
      body: GestureDetector(
        onTap: () {
          _color = Colors.deepPurple;
          print('clicked');
        },
        child: SizedBox.expand(
          child: Container(
            color: _color,
            child: Center(
              child: Text(
                'HELLo THERE',
                style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'Starjedi'
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

它打印字符串“clicked”,但不更改颜色。

那么,我该如何以正确的方式做到这一点?

最佳答案

  • 将您的小部件转换为StatefulWidget
  • 使用setState回调。
  • 在类级别声明变量(外部构建)

  • 完整解决方案:
    class Home extends StatefulWidget { // use this
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      Color _color = Colors.amber; // declare it here
    
      @override
      Widget build(BuildContext context) {
    
        return Scaffold(
          body: GestureDetector(
            onTap: () {
              setState(() { // use setState
                _color = Colors.deepPurple;
              });
              print('clicked');
            },
            child: SizedBox.expand(
              child: Container(
                color: _color,
                child: Center(
                  child: Text(
                    'HELLo THERE',
                    style: TextStyle(
                        fontSize: 20.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Starjedi'
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }
    

    关于flutter - 点击时如何更改容器的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60379891/

    相关文章:

    dart - Flutter:继承的 Widget 和路由

    debugging - Flutter - 如何获取错误代码行 : "Another exception was thrown"

    flutter - 为什么这个循环只发生一次? flutter/Dart

    flutter - 如何在Flutter中在运行时将项目添加到Row对象?

    flutter - 覆盖给我一个错误,我找不到函数

    flutter - "Could not connect to lockdownd"尝试运行 flutter 应用程序时

    firebase - 为什么Firestore数据赋予Class 'QueryDocumentSnapshot'没有实例方法 '[]'。错误?

    http - 如何在 flutter 中使用带有 url 编码正文的 http.post 下载文件?

    dart - 如何在 Flutter 中使用其他组件在页面中实现选项卡 Controller ?

    dart - Dart有逗号运算符吗?