flutter - 点击时如何更改容器的背景颜色
问题描述
我正在尝试以这种方式更改容器的颜色->
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'
),
),
),
),
),
),
);
}
}
推荐阅读
- types - 在 Idris 的接口内定义数据类型
- r - 粘贴晶须模板的方法
- angular - 当 FormArray 为空时,FormArray 应该是无效的
- kubernetes - 当节点在 k8s 中崩溃时,20% 的请求会超时。如何解决这个问题?
- c - 更新使用“-Bsymbolic”链接器选项生成的 ELF 共享对象
- postgresql - GiST索引中的索引元组与用户表行之间的关系是多对一还是一对一?
- c# - 循环遍历 excel 表中的每个单元格并使用 EPP Plus 分配 NULL 值
- android - 从数据库读取数据时索引超出范围
- jquery - 表单上的多个日期选择器
- android - Debug 似乎没有显示 AndroidManifest 图标