Flutter中如何点击Container时循环切换背景颜色?
实现点击循环切换Container背景色
你只需要完成两个关键修改:
- 给Container添加
color属性,绑定当前选中的颜色 - 在
onTap回调里更新索引,通过取模实现循环切换
修改后的完整代码:
import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( body: MyApp(), ), ), ); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int index = 0; List<Color> mycolors = [ Colors.pink, Colors.red, Colors.green, Colors.blue, ]; @override Widget build(BuildContext context) { return Center( child: Wrap(children: [ InkWell( child: Container( alignment: Alignment.center, margin: EdgeInsets.all(5), height: 100, width: 100, // 绑定当前选中的颜色 color: mycolors[index], ), onTap: () { setState(() { // 索引自增后取模,到达末尾自动回到起始位置实现循环 index = (index + 1) % mycolors.length; }); }), ])); } }
关键逻辑说明
color: mycolors[index]:让Container的背景色跟随当前索引对应的颜色列表项index = (index + 1) % mycolors.length:每次点击索引加1,当索引到达列表最后一项时,取模运算会让它重置为0,从而实现粉色→红色→绿色→蓝色→粉色的循环切换setState:必须包裹索引更新逻辑,触发Flutter组件重建,更新UI显示
内容的提问来源于stack exchange,提问作者zeyzey
相关产品推荐
相关产品推荐

