feat: enhanced component_controller

pull/111/head
alestiago 4 years ago
parent 27e12148f8
commit 0f62028eeb

@ -14,19 +14,18 @@ abstract class ComponentController<T extends Component> extends Component {
/// The [Component] controlled by this [ComponentController]. /// The [Component] controlled by this [ComponentController].
final T component; final T component;
/// Ads the [ComponentController] to its [component].
Future<void> attach() async {
// TODO(alestiago): check if component already attached.
await component.add(this);
}
@override @override
Future<void> onLoad() async { Future<void> addToParent(Component parent) async {
await super.onLoad();
assert( assert(
parent! == component, parent == component,
'ComponentController should be child of $component. ' 'ComponentController should be child of $component. '
'Use attach() instead.', 'Use attach() instead.',
); );
await super.addToParent(parent);
}
/// Ads the [ComponentController] to its [component].
Future<void> attach() async {
if (parent == null) await component.add(this);
} }
} }

@ -0,0 +1,63 @@
// ignore_for_file: cascade_invocations
import 'package:flame/game.dart';
import 'package:flame/src/components/component.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/flame/flame.dart';
class TestComponentController extends ComponentController {
TestComponentController(Component component) : super(component);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(FlameGame.new);
group('ComponentController', () {
flameTester.test(
'throws AssertionError when not attached to controlled component',
(game) async {
final component = Component();
final controller = TestComponentController(component);
final anotherComponet = Component();
await expectLater(
() async => await anotherComponet.add(controller),
throwsAssertionError,
);
},
);
group('attach', () {
flameTester.test(
'adds component controller to controlled component',
(game) async {
final component = Component();
final controller = TestComponentController(component);
await controller.attach();
await game.add(component);
await game.ready();
expect(component.contains(controller), isTrue);
},
);
flameTester.test(
"doesn't fail when already has a parent",
(game) async {
final component = Component();
final controller = TestComponentController(component);
await controller.attach();
await expectLater(
() async => controller.attach(),
returnsNormally,
);
},
);
});
});
}
Loading…
Cancel
Save