I’m trying to draw a grid in flutter canvas with flame
framework but really having a hard time. This is my current code that I’m using to draw the grid:
import 'dart:async';
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:learning_flame/my_game.dart';
class GameBoard extends PositionComponent with HasGameRef<MyGame> {
@override
FutureOr<void> onLoad() {
super.onLoad();
// game size
final gameSize = gameRef.size;
const cellSize = 40.0;
const cellSpacing = 10.0;
// starting position
final startingPosition = Vector2(-(gameSize.x / 2) + cellSize, 0);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
add(
Cell(
position: startingPosition +
Vector2(
(cellSize + cellSpacing) * j,
i * (cellSize + cellSpacing),
),
size: Vector2.all(cellSize),
),
);
}
}
}
}
class Cell extends RectangleComponent {
Cell({
required super.position,
required super.size,
}) : super(anchor: Anchor.center);
@override
void render(Canvas canvas) {
super.render(canvas);
canvas.drawRect(
Rect.fromCenter(
center: Offset.zero,
width: position.y,
height: position.x,
),
paint..color = Colors.white,
);
}
}
This is the result I’m getting:
Expected results
I was expective a 5×5 grid to be drawn on the canvas with the code provided.