flutter - Flutter:使用 Switch 语句时颜色没有改变
问题描述
我在 ListView.builder 中有一行容器,按下时应该会改变容器背景的颜色。我使用 switch 语句来改变颜色取决于 isSelected 与否。
问题是当我按下容器时颜色没有改变,即使打印显示我按下了正确的容器。
ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categoryData.length,
itemBuilder: (context,index){
bool isSelected = false;
return GestureDetector(
onTap: (){
switch(index){
case 0 :
isSelected = true;
break;
case 1 :
isSelected = true;
}
print(category[index].name + index.toString());
},
child: Row(
children: <Widget>[
Column(
children: <Widget>[
Container(
width: 68,
height: 68,
decoration: BoxDecoration(
color: isSelected ? Colors.white: Colors.transparent,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: Colors.white,
width: 1,
),
boxShadow: isSelected
?[
BoxShadow(
color: Color(0x14000000),
blurRadius: 10
)
]: null
),
这是我正在使用的类别列表:
class list {
final String name;
final String count;
final String imageUrl;
list({this.imageUrl, this.name, this.count});
}
List<list> category = [
new list(
imageUrl: "assets/tops.png",
name: "TOPS",
count: "5"
),
new list(
imageUrl: "assets/fashion.png",
name: "Pants",
count: "5"
),
new list(
imageUrl: "assets/dress.png",
name: "DRESSES",
count: "4"
),
new list(
imageUrl: "assets/coat.png",
name: "COATS",
count: "4"
),
new list(
imageUrl: "assets/suits.png",
name: "SUITS",
count: "4"
),
];
解决方案
试试这个解决方案
class checking extends StatefulWidget {
@override
_checkingState createState() => _checkingState();
}
class _checkingState extends State<checking> {
List<String>categoryData=['abc','xyz','xyz'];
int _selectedIndex = 0;
_onSelected(int index) {
print(index);
setState(() =>
_selectedIndex = index
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categoryData.length,
itemBuilder: (context,index){
return GestureDetector(
onTap: () => _onSelected(index),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 68,
height: 68,
decoration: BoxDecoration(
color: _selectedIndex != null && _selectedIndex == index ? Colors.black : Colors.grey,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: Colors.blue,
width: 1,
),
),
),
)
);
}
),
),
);
}
}
推荐阅读
- python - Python3以一种奇怪的方式处理非ASCII字符
- cloud-foundry - 如何在将默认 Docker 映像推送到 Cloud Foundry 时添加配置文件
- c# - 如何使用 ASP.Net MVC 从局部视图执行操作?
- python - 我如何从用户那里获得接受语言标题?
- python - 如何在 Python 中修复 `pywintypes.com_error`
- php - 在jquery函数中处理单引号和双引号
- ios - 如何将导航栏置于最前面
- python - 导入语句中的点表示什么?
- python - Is it possible to club 2 or more Scripts in Python(spyder)?
- java - Java 泛型 - 类型参数“K”不在其范围内;应该实施 X