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
相关产品推荐
相关产品推荐

