#Flame Signals
flame_signals
offers a simple, type-safe mechanism to provide signals with or without data payloads
between components in a FlameGame
.
Follow this link for a simple example. This is the example in the github repo.
To use flame_signals
, start by adding the HasSignals
mixin to your game class:
class SpaceGame extends FlameGame with HasSignals {
//...
}
The mixin defines a Stream
of type FlameSignal
to adding and broadcasting the signals.
Extend the base class FlameSignal
to define one or more signal objects.
class MeteorDestroyedSignal extends FlameSignal {
final Vector2 position;
final double laserAngle;
const MeteorDestroyedSignal({required this.position, required this.laserAngle});
}
class DecreaseMeteorCountSignal extends FlameSignal {}
Any component in the tree will be able to send a FlameSignal
. Both the SendSignals
and
FlameSignalListenable
mixins provide an addSignal
method to send out a signal.
class Meteor extends Component with SendSignals {
//...
//...
void onHitByLaser() {
addSignal(MeteorDestroyedSignal(
position: position,
laserAngle: laser.angle,
));
}
}
Components that need to react to game signal use the FlameSignalListenable
mixin.
A signal handler must be registered in the components onMount
life cycle method.
This creates a subscription to the signal stream. When the component is removed from the component tree, the onRemove life cycle method cancels the subscription.
class MeteorManager extends Component with FlameSignalListenable {
@override
void onMount() {
super.onMount();
onSignal<MeteorDestroyedSignal>((signal) {
_generateNewMeteor();
_updateMeteorCount();
});
}
}
A component using the FlameSignalListenable mixin can also add signals.
class MeteorManager extends Component with FlameSignalListenable {
@override
void onMount() {
super.onMount();
onSignal<MeteorDestroyedSignal>((signal) {
_generateNewMeteor();
_updateMeteorCount();
});
}
//...
//...
void _updateMeteorCount() {
addSignal(DecreaseMeteorCountSignal());
}
}