flutter - 通过颤振标签为容器着色
问题描述
我有许多 ((Tabbed)) 项目的列,当我在其中一个项目上进行选项卡时,它应该是彩色的,而其他项目是透明的,这是我的 Tabbed 类,这个图像是我现在用我的代码所拥有的
class Tabbed extends StatefulWidget {
@override
_TabbedState createState() => _TabbedState();
}
class _TabbedState extends State<Tabbed> {
Color color = Colors.transparent;
@override
void initState() {
color = Colors.transparent;
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
print("tab");
if (color == Colors.transparent){
setState(() {
color = Colors.purple;
});
}
else{
setState(() {
color = Colors.transparent;
});
}
},
child: Container(
height: 100,
width: 100,
decoration: BoxDecoration(
color: color,
border: Border.all(color: Colors.red,width: 1),
),
),
);
}
}
解决方案
您可以简单地尝试为您的盒子创建一个模型并拥有一个boolean
属性并将每个盒子的状态存储在一个列表中以了解该盒子是否被点击,您也可以选择一个布尔列表,但我更喜欢创建一个模型列表因为它允许您添加更多属性,所以我对您的代码进行了一些修改,您也可以在 dartpad 上看到它的工作原理
class Tabbed extends StatefulWidget {
@override
_TabbedState createState() => _TabbedState();
}
class _TabbedState extends State<Tabbed> {
Color color = Colors.green;
@override
void initState() {
for(int i=0;i<listLength;i++){
list1.add(
TabModel(isTapped: false)); // assigns initial value to false
}
for(int i=0;i<listLength;i++){
list2.add(
TabModel(isTapped: false)); // assigns initial value to false
}
}
Widget column1(){
return Column(
children: List.generate(
listLength,
(index) =>GestureDetector(
onTap: (){
// this selects only one out of many and disables rest
for(int i=0;i<list1.length;i++){
if(i!=index){
list1[i].isTapped=false;
}
};
setState((){
list1[index].isTapped = true;
});
},
child:Container(
margin:EdgeInsets.all(5),
color: list1[index].isTapped? Colors.red:color,
height:100,
width:100
))
));
}
Widget column2(){
return Column(
children: List.generate(
listLength,
(index) =>GestureDetector(
onTap: (){
setState((){
list2[index].isTapped = !list2[index].isTapped;
});
},
child:Container(
margin:EdgeInsets.all(5),
color: list2[index].isTapped? Colors.red:color,
height:100,
width:100
))
));
}
List<TabModel> list1 =[];
List<TabModel> list2 =[];
int listLength=5;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
column1(),
column2()
],);
}
}
class TabModel{
bool isTapped = false;
TabModel({this.isTapped});
}
如果这不是您想要的,或者如果您在理解代码的任何部分时遇到任何问题,请随时发表评论其他你可以选择多个框
推荐阅读
- web-applications - 用于 Web 应用程序 AR.js 的无标记的 Agumented 现实
- c# - 针对 localhost 相对 url 的请求“无法分配请求的地址”
- angular - Angular 6:仪表板 - ngFor 中的唯一 ID
- oracle-cloud-infrastructure - 我们能否使用 CLI 或 API 导出 Oracle OCI 的服务限制
- javascript - 我试图在页面加载时隐藏一个段落,然后执行显示/隐藏 jquery 并更改按钮名称 onclick
- javascript - 如何在 JavaScript 的帮助下遍历 JSON
- redis - 如何使用redis作为部分LRU?
- spring-boot - 如何在 Spring Security 中获取未经身份验证的 URL 的引用
- angular - 在动态添加表单字段时限制空字段
- sql - SQL Query 计算视图表中的库存