首页 > 解决方案 > 点击时如何更改容器的背景颜色

问题描述

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

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' 但不改变颜色。

那么,我怎样才能以正确的方式做到这一点?

标签: flutterdart

解决方案


  1. 将您的小部件转换为StatefulWidget.

  2. 使用setState回调。

  3. 在类级别声明变量(外部构建)

完整解决方案:

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'
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

推荐阅读