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

Flutter:如何从数组创建带自定义边框的可作为障碍物的网格

实现Flutter自定义障碍物边框网格

要实现示例中的效果,核心是根据相邻单元格的障碍物状态动态控制边框显示——相邻的障碍物单元格之间不显示边框,只保留障碍物块的外围边框。以下是修改后的完整代码:

List<List<String>> gridState = [
  ['', '', '', '', '', '', '', ''],
  ['', '', '', 'x', '', '', '', ''],
  ['', '', '', '', '', '', 'x', ''],
  ['', '', 'x', 'x', '', '', '', ''],
  ['', 'x', '', '', '', '', '', ''],
  ['', '', '', '', '', 'x', '', ''],
  ['', 'x', '', '', '', '', '', ''],
  ['', '', '', '', '', '', '', ''],
];

Widget _buildGrid() {
  int gridStateLength = gridState.length;
  return Column(
    children: <Widget>[
      AspectRatio(
        aspectRatio: 1.0,
        child: Container(
          padding: const EdgeInsets.all(8.0),
          margin: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
              border: Border.all(color: Colors.black, width: 2.0)),
          child: GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: gridStateLength,
            ),
            itemBuilder: _buildGridItems,
            itemCount: gridStateLength * gridStateLength,
          ),
        ),
      ),
    ],
  );
}

Widget _buildGridItems(BuildContext context, int index) {
  int gridStateLength = gridState.length;
  int x = (index / gridStateLength).floor();
  int y = index % gridStateLength;

  // 检查上下左右是否为障碍物,决定是否显示对应边框
  bool showTopBorder = x == 0 || gridState[x-1][y] != 'x';
  bool showBottomBorder = x == gridStateLength-1 || gridState[x+1][y] != 'x';
  bool showLeftBorder = y == 0 || gridState[x][y-1] != 'x';
  bool showRightBorder = y == gridStateLength-1 || gridState[x][y+1] != 'x';

  return GestureDetector(
    onTap: () {
      setState(() {
        // 点击切换单元格障碍物状态
        gridState[x][y] = gridState[x][y] == 'x' ? '' : 'x';
      });
    },
    child: GridTile(
      child: Container(
        color: gridState[x][y] == 'x' ? Colors.black : Colors.transparent,
        decoration: BoxDecoration(
          border: Border(
            top: showTopBorder ? BorderSide(color: Colors.black, width: 0.5) : BorderSide.none,
            bottom: showBottomBorder ? BorderSide(color: Colors.black, width: 0.5) : BorderSide.none,
            left: showLeftBorder ? BorderSide(color: Colors.black, width: 0.5) : BorderSide.none,
            right: showRightBorder ? BorderSide(color: Colors.black, width: 0.5) : BorderSide.none,
          ),
        ),
      ),
    ),
  );
}

关键修改说明

  • 动态边框判断:通过showTopBorder等变量,检查当前单元格的上下左右是否为障碍物,相邻是障碍物则隐藏对应方向的边框,避免障碍物块内部出现多余细线。
  • 简化单元格渲染:直接通过Container的color属性设置障碍物颜色,移除冗余的_buildGridItem方法。
  • 优化交互逻辑:点击单元格可切换障碍物状态,更贴合实际使用场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:45:41