You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何点击Container时循环切换背景颜色?

实现点击循环切换Container背景色

你只需要完成两个关键修改:

  1. 给Container添加color属性,绑定当前选中的颜色
  2. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:15:44