flutter - 如何在切换按钮打开时更改卡片颜色
问题描述
我想在打开切换按钮时更改容器颜色。我正在使用 ListTile,这是我的代码
Container(
color:Colors.red, //want to change this color
child:ListTile(
dense:true,
trailing:Switch(
value: _selectedProducts.contains(book.id),
onChanged:(bool? selected) {
if (selected != null) {
setState(() {
_onProductSelected(
selected, book.id);
print(selected);
print(book.id);
});
}},
activeTrackColor: HexColor("#b8c2cc"),
activeColor: HexColor("#7367f0"),
),
title: Text(book.title,style: ),
subtitle: Text("Rs/- 40",),
),
);
_onProductSelected
在方法中,我正在处理特定的切换按钮。
更新:
我正在调用这个小buildBook
部件Widget build(BuildContext context)
Expanded(
child: ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
final book = books[index];
return Column(
children: [
buildBook(book,index),
Divider()
],
);
},
),
),
Widget buildBook(Book book) => InkWell(
onTap:(){Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ProductProfile(),
));},
child: Container(
color:isChangeColor?Colors.red:Colors.green,
child: ListTile(
dense:true,
leading: SizedBox(
width: 50,
height: 90,
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.network(
book.urlImage,
fit: BoxFit.cover,
),
),
),
trailing:Switch(
value: _selectedProducts.contains(book.id),
onChanged:(bool? selected) {
if (selected != null) {
// setState(() {
// if(selected){
// cardColor = Colors.blue;
// }else{
// cardColor = Colors.pink;
// }});
setState(() {
isChangeColor = selected;
// isChangeColor=true;
_onProductSelected(
selected, book.id);
print(selected);
print(book.id);
});
}},
activeTrackColor: HexColor("#b8c2cc"),
activeColor: HexColor("#7367f0"),
),
title: Text(book.title,style: GoogleFonts.montserrat(color:Colors.black,fontWeight:FontWeight.w500,fontSize: 15),),
// isThreeLine: true,
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(book.author,style: GoogleFonts.montserrat()),
// SizedBox10(),
Text("Rs/- 40",style: GoogleFonts.montserrat(fontSize: 15,color: Colors.black,fontWeight: FontWeight.w400),),
],
),
),
),
);
}
请帮助如何做到这一点。
解决方案
您可以使用类似isSelected的bool变量来检查 ListTile 是否被选中。
示例:
bool isSelected = true;
Container(
color: isSelected ? Colors.red : Colors.green,
...
)
推荐阅读
- sql-server - 自动将字段设置为 getdate() 而无需触发
- concat - 使用来自两个不同对象的数据创建句子
- selenium - 带空格的 Seleniumt webelement
- ios - Swift 在单元格中隐藏/显示 UIView(来自数据库的数据)
- angular - 我的 testing.spec.ts 不起作用。错误:无法从伪造的异步测试中生成 XHR。请求网址:http://xxxxxx/v1/products
- javascript - 为 Web 的 FCM 推送通知启用或禁用切换选项
- javascript - 无法在 express js 节点中获取请求有效负载
- android - 图像在 RecyclerView 中的第 11 项后消失
- c++ - C++:无法重新分配类,在线使用默认构造函数
- java - 使用 bash globing 设置 Java 命令行属性