[英]Flutter Gesture Detector transform.scale animate but doesn't uncolor the unselected items
在我的 flutter 項目中,我正在創建自己的芯片。 其中有 4 個。 我正在使用一個裝飾過的容器和一個手勢檢測器來捕捉任何點擊。 我想實現這種行為:當用戶點擊一個芯片時,有一個 animation 使它像一個按鈕一樣工作(我正在使用transform.scale
來獲得它)並被選中。 最后選擇的芯片變為未選擇模式。 我只想從 4 個芯片中選擇 1 個。
`
class ChipTile extends StatefulWidget {
final String text;
final index;
const ChipTile({
super.key,
required this.text,
required this.index,
});
@override
State<ChipTile> createState() => _ChipTileState();
}
class _ChipTileState extends State<ChipTile>
with SingleTickerProviderStateMixin {
//animation on tap
late AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 100),
lowerBound: 0.0,
upperBound: 0.1,
)..addListener(() {
setState(() {});
});
}
void onTapDown(TapDownDetails details) {
_animationController.forward();
}
void onTapUp(TapUpDetails details) {
_animationController.reverse();
}
void onTapCancel() {
_animationController.reverse();
}
//----------------------------
@override
Widget build(BuildContext context) {
var scale = 1 + _animationController.value;
return GestureDetector(
onTap: () {
setState(() {
globals.selectedChip = widget.index;
});
},
onTapDown: onTapDown,
onTapUp: onTapUp,
onTapCancel: onTapCancel,
child: Transform.scale(
scale: scale,
child: SizedBox(
height: 30,
width: 70,
child: Container(
child: Center(
child: Text(
widget.text,
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: globals.selectedChip == widget.index
? Colors.blue[100]
: Colors.grey[300],
),
),
),
),
);
}
}
`
animation 運行良好,但芯片着色有不良行為。 當我 select 一個不同的芯片時,最后選擇的芯片不會變成未選擇的。 全部選中的籌碼
所有按鈕ChipTile
都有自己的 state,單擊一個按鈕不會觸發其他按鈕 state。您需要以某種方式連接所有按鈕點擊事件。 我正在使用ValueNotifier
並使小部件保持最小以了解概念。
ValueNotifier<int?> selectedChip = ValueNotifier(null);
class ChipTile extends StatefulWidget {
final String text;
final int index;
const ChipTile({
super.key,
required this.text,
required this.index,
});
@override
State<ChipTile> createState() => _ChipTileState();
}
class _ChipTileState extends State<ChipTile> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
selectedChip.value = widget.index;
setState(() {});
},
child: ValueListenableBuilder(
valueListenable: selectedChip,
builder: (context, value, child) => Container(
child: Text(
widget.text,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: value == widget.index.toInt()
? Colors.blue[100]
: Colors.grey[300],
),
),
),
);
}
}
在腳手架上進行測試
body: Column(
children: [
for (int i = 0; i < 3; i++)
ChipTile(
index: i,
text: "i $i",
),
],
),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.