我正在尝试以这种方式更改容器的颜色->
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/