flutter - 我需要更改单个容器的颜色,但它会更改整个容器的颜色
问题描述
AnimationController? controller;
Animation<double>? animation;
@override
void initState() {
super.initState();
controller =
AnimationController(duration: const Duration(seconds: 3), vsync: this)
..addListener(() => setState(() {}));
animation = Tween(begin: -500.0, end: 500.0).animate(controller!);
controller!.forward();
}
List tile = [
[true, true, true, true],
[true, true, true, true],
[true, true, true, true],
[true, true, true, true],
];
String? gettw;
Container(
color: Colors.white,
child: ListView.builder(
reverse: false,
itemCount: tile[0].length,
itemBuilder: (BuildContext context, int index) {
String? gettw;
if (tile[index][0]) {
if (gettw != 'transparent') {
gettw = 'black';
}
} else if (tile[index][0] == false) {
gettw = 'transparent';
}
print('gettw $gettw');
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
setState(() {
if (tile[index][0] == true) {
print('working');
gettw = 'transparent';
print('gettw $gettw');
} else if (tile[index][0] == false) {
gettw = 'red';
}
});
},
child: Transform.translate(
offset: Offset(0.0, animation!.value),
child: Container(
height: MediaQuery.of(context).size.height / 4,
color: (gettw == 'black')
? Colors.black
: (gettw == 'transparent')
? Colors.transparent
: (gettw == 'red')
? Colors.red
: Colors.green,
child: Text('${tile[index][0]}',
style: const TextStyle(color: Colors.purple)),
),
),
);
},
)),
我从上到下为 4 个容器设置动画。如果用户单击容器。容器颜色需要将黑色变为白色。但所有 4 个容器的颜色都发生了变化。gettw 变量包含需要在容器中显示的颜色。请有人帮我解决这个问题。
解决方案
试试这个
import 'package:flutter/material.dart';
class ColorChanger extends StatefulWidget {
const ColorChanger({ Key? key }) : super(key: key);
@override
_ColorChangerState createState() => _ColorChangerState();
}
class _ColorChangerState extends State<ColorChanger> {
List<bool> widgetActive = List.generate(4, (index){
return false;
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 4,
itemBuilder: (context, index){
return InkWell(
onTap: (){
setState(() {
widgetActive[index] = !widgetActive[index];
});
},
child: Container(
margin: EdgeInsets.all(30),
width: 40,
height:50,
color: widgetActive[index] ? Colors.black:Colors.red,
),
);
}),
);
}
}
推荐阅读
- google-cloud-platform - 如何将 bigquery 表中的 16000 多行作为 CSV 文件导出到本地机器?
- java - 使用 TLS 的 Java 中的 Eclipse Paho MQTT 客户端
- swift - Swift 5:按下按钮时如何添加文本和日期?
- excel - 使用 VBA Excel 宏自动填充工作表顺序
- javascript - 尽管已连接,但我的 SCSS 文件无法正常工作,并且 firefox 开发人员编辑向我显示所有属性都正常
- python - 发送 HTTP 多部分/表单数据响应
- r - 如何在整个向量上运行一组条件
- python - 使用 boto3 列出 SNS 主题
- grpc-go - 如何在不使用 http 协议中使用 oltp 导出器的 opentelemtry 收集器的情况下将跟踪直接发送到 Web 服务?
- python - 单击时放大子图(带有 inset_axes 图)