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

时间:2020-02-24 16:12:40

标签: 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”,但不更改颜色。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您需要使用StatelessWidget而不是StatefulWidget并在setState属性中调用方法onTap。此外,您可以在build方法中设置_color的值,这意味着刷新屏幕状态时始终会将其重置为Colors.amber,需要将_color移至build

代码示例:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: GestureDetector(
      onTap: () {
        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',
              ),
            ),
          ),
        ),
      ),
    ),
  );
}​