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

Flutter实现点击网格方块切换颜色的技术求助

解决Flutter网格方块点击切换颜色问题

修改后的完整代码

import 'package:flutter/material.dart';

class MyPage extends StatefulWidget {
  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  late List<Color> _boxColors;
  late int _columns;
  late int _totalBoxes;
  late double _boxSize;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        double screenWidth = constraints.maxWidth;
        double screenHeight = constraints.maxHeight;
        
        _boxSize = screenWidth < screenHeight ? screenWidth / 10 : screenHeight / 10;
        _columns = (screenWidth / _boxSize).floor();
        int rows = (screenHeight / _boxSize).floor();
        _totalBoxes = _columns * rows;

        // 初始化/更新颜色列表,适配屏幕变化后的方块数量
        if (_boxColors == null || _boxColors.length != _totalBoxes) {
          _boxColors = List.generate(_totalBoxes, (_) => Colors.blue);
        }

        return GridView.count(
          crossAxisCount: _columns,
          children: List.generate(
            _totalBoxes,
            (index) => GestureDetector(
              onTap: () {
                setState(() {
                  // 点击切换蓝绿颜色
                  _boxColors[index] = _boxColors[index] == Colors.blue 
                      ? Colors.green 
                      : Colors.blue;
                });
              },
              child: Container(
                decoration: BoxDecoration(
                  color: _boxColors[index],
                  border: Border.all(color: Colors.white),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

// 若不再需要详情页可直接删除此类
class DetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detail Page'),
      ),
      body: Center(
        child: Text('Detail Page Content'),
      ),
    );
  }
}

关键改动说明

  • 把MyPage从无状态组件改成有状态组件:因为需要动态维护方块的颜色状态,只有状态组件能通过setState触发UI更新。
  • 新增_boxColors列表:专门存储每个方块的当前颜色,初始状态全设为蓝色。
  • 移除全局GestureDetector:给每个网格子项单独绑定点击事件,直接通过index定位点击的方块,逻辑更直观。
  • 替换跳转逻辑为颜色切换:在点击回调里修改对应索引的颜色,通过setState刷新UI,实现点击切换蓝绿的效果。
  • 适配屏幕变化:每次计算网格参数时,检查颜色列表长度是否匹配当前方块总数,避免屏幕旋转等场景下出现状态不匹配的问题。

内容的提问来源于stack exchange,提问作者Aliezza navi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:55:01