flutterflame

Flutter Flame SpawnComponent sample


Trying to implement the Flame SpawnComponent but get the error:

The argument type 'MyComponent Function()' can't be assigned to the parameter type 'PositionComponent Function(int)'.dartargument_type_not_assignable

Here is my code which is basically from the documentation. Any idea on what I'm doing wrong?


SpawnComponent(
// Error on next line
  factory: () => MyComponent(size: Vector2(10, 20), amount: 2),
  period: 0.5,
  area: Circle(Vector2(100, 200), 150),
);

class MyComponent extends PositionComponent with HasVisibility {
  MyComponent({required Vector2 size, required int amount});

  @override
  void renderTree(Canvas canvas) {
    // Check for visibility
    if (isVisible) {
      // Custom code here

      // Continue rendering the tree
      super.renderTree(canvas);
    }
  }
}

I expect a Component that spawns PositionComponents at the given interval


Solution

  • The argument for the factory seems to be missing from the documentation, this is what it should look like:

    SpawnComponent(
      factory: (int x) => MyComponent(size: Vector2(10, 20), amount: 2),
      period: 0.5,
      area: Circle(Vector2(100, 200), 150),
    );
    

    Where x is the number of components that the SpawnComponent has spawned so far.

    On another note, you don't need to override renderTree to toggle the visibility when you are using the HasVisibility mixin, that mixin already handles it for you.