flame icon indicating copy to clipboard operation
flame copied to clipboard

The toString method of different ComponentKey instances will return the same string.

Open weijiewow opened this issue 11 months ago • 2 comments

What could be improved

The toString method of different ComponentKey instances returns the same string, making it difficult to debug the issue about ComponentKey.

Run the following code:

import 'package:flame/components.dart';

void main() {
  ComponentKey keyA = ComponentKey.named('key_a');
  ComponentKey keyB = ComponentKey.named('key_b');

  print('keyA: $keyA, keyB: $keyB');
}

We will see:

flutter: keyA: Instance of 'ComponentKey', keyB: Instance of 'ComponentKey'

Would overriding the toString method to return different values be a better approach?

Why should this be improved

Run and restart the following code:

import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(GameWidget(game: MyGame()));
}

class MyGame extends FlameGame {
  @override
  void onMount() {
    super.onMount();
    world.add(Player(
      position: Vector2.all(10.0),
    ));
    world.add(Player(
      position: Vector2.zero(),
    ));
  }
}

class Player extends PositionComponent {
  static String keyName = 'player_key';

  Player({required super.position})
      : super(
          size: Vector2(100, 2),
          anchor: Anchor.center,
          key: ComponentKey.named(keyName),
        );
}

We will see the message following:

════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building FutureBuilder<void>(dirty, state: _FutureBuilderState<void>#cf097):
Key Instance of 'ComponentKey' is already registered
'package:flame/src/components/core/component_tree_root.dart':
Failed assertion: line 172 pos 12: '!_index.containsKey(key)'

In a complicated project, the information above cannot help us quickly identify which instance of ComponentKey was registered repeatedly.

Risks

No response

More information

The part of my pubspec.yaml for this case follow:

environment: sdk: ^3.5.4

dependencies: flutter: sdk: flutter flame: ^1.23.0

Other

  • [ ] Are you interested in working on a PR for this?

weijiewow avatar Jan 25 '25 09:01 weijiewow

Sure, sounds like a good idea. What do you think @erickzanardo?

spydon avatar Jan 25 '25 11:01 spydon

Sure thing! Just don't know exactly how we will do that, since we don't store the string of the named key, but maybe we could use the hash

erickzanardo avatar Jan 25 '25 11:01 erickzanardo