问题描述
我发现有关每隔几秒钟或几秒钟后更改背景的问题。不知道晚上是否太晚或我的情况是否有所不同。发生特定事件时,我想将容器的背景颜色更改1秒。
setState(() {
flashBackground = (answer == result ? false : true);
Timer(Duration(seconds: 1),() {flashBackground = false;});
});
这会触发容器的背景
color: (flashBackground ? CupertinoColors.destructiveRed : CupertinoColors.white)
当flashBackground设置为true时,背景变为破坏性红色(我喜欢它),但是此后计时器不会将颜色恢复为白色。我在做什么错了?
解决方法
这是一种实现方法:
class Example extends StatefulWidget {
const Example({Key key}) : super(key: key);
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
bool _changeColor = false;
void _changeBackgroundColor() {
setState(() => _changeColor = !_changeColor);
Future.delayed(const Duration(seconds: 1),() => setState(() => _changeColor = !_changeColor));
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _changeBackgroundColor,child: AnimatedContainer(
duration: const Duration(milliseconds: 100),width: 100,height: 100,color: _changeColor ? Colors.red : Colors.green,),);
}
}