diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.yml index 61205af8515..2ccae843a8c 100644 --- a/.github/workflows/cicd.yml +++ b/.github/workflows/cicd.yml @@ -9,7 +9,7 @@ on: env: - FLUTTER_MIN_VERSION: '3.44.0' + FLUTTER_MIN_VERSION: '3.47.0' jobs: # BEGIN LINTING STAGE @@ -29,10 +29,10 @@ jobs: with: flutter-version: ${{env.FLUTTER_MIN_VERSION}} - uses: bluefireteam/melos-action@v3 - # flame_3d always requires the latest stable, since flutter_gpu is still - # unstable, so it is only analyzed in the analyze-latest job. - name: "Analyze with lowest supported version" - run: melos exec --ignore="flame_3d*" -- dart analyze --fatal-infos . + uses: invertase/github-action-dart-analyzer@v3 + with: + fatal-infos: true analyze-latest: runs-on: ubuntu-latest diff --git a/doc/flame/examples/lib/anchor.dart b/doc/flame/examples/lib/anchor.dart index eec4b18ce62..6502be66605 100644 --- a/doc/flame/examples/lib/anchor.dart +++ b/doc/flame/examples/lib/anchor.dart @@ -5,7 +5,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame/palette.dart'; -class AnchorGame extends FlameGame { +class AnchorGame() extends FlameGame { final _parentAnchorText = TextComponent(position: Vector2.all(5)); final _childAnchorText = TextComponent(position: Vector2(5, 30)); @@ -50,13 +50,11 @@ class AnchorGame extends FlameGame { } } -class _AnchoredRectangle extends RectangleComponent with TapCallbacks { - _AnchoredRectangle({ - super.position, - super.size, - super.paint, - }); - +class _AnchoredRectangle({ + super.position, + super.size, + super.paint, +}) extends RectangleComponent with TapCallbacks { @override void onTapDown(TapDownEvent event) { var index = Anchor.values.indexOf(anchor) + 1; diff --git a/doc/flame/examples/lib/anchor_by_effect.dart b/doc/flame/examples/lib/anchor_by_effect.dart index 0c8eac7456a..2b649811c2d 100644 --- a/doc/flame/examples/lib/anchor_by_effect.dart +++ b/doc/flame/examples/lib/anchor_by_effect.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class AnchorByEffectGame extends FlameGame { +class AnchorByEffectGame() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/anchor_to_effect.dart b/doc/flame/examples/lib/anchor_to_effect.dart index 45a91b37d3f..222dd94b4a0 100644 --- a/doc/flame/examples/lib/anchor_to_effect.dart +++ b/doc/flame/examples/lib/anchor_to_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class AnchorToEffectGame extends FlameGame { +class AnchorToEffectGame() extends FlameGame { @override Future onLoad() async { final flower = Flower( diff --git a/doc/flame/examples/lib/collision_detection.dart b/doc/flame/examples/lib/collision_detection.dart index e4b4e012486..351b3daf1c9 100644 --- a/doc/flame/examples/lib/collision_detection.dart +++ b/doc/flame/examples/lib/collision_detection.dart @@ -5,7 +5,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart' hide Image; -class CollisionDetectionGame extends FlameGame with HasCollisionDetection { +class CollisionDetectionGame() extends FlameGame with HasCollisionDetection { @override Future onLoad() async { final emberPlayer = EmberPlayer( @@ -30,12 +30,14 @@ class CollisionDetectionGame extends FlameGame with HasCollisionDetection { } } -class RectangleCollidable extends PositionComponent with CollisionCallbacks { +class RectangleCollidable(Vector2 position) + extends PositionComponent + with CollisionCallbacks { final _collisionStartColor = Colors.amber; final _defaultColor = Colors.cyan; late ShapeHitbox hitbox; - RectangleCollidable(Vector2 position) + this : super( position: position, size: Vector2.all(50), diff --git a/doc/flame/examples/lib/color_effect.dart b/doc/flame/examples/lib/color_effect.dart index 3551fb71554..71e8429bd8d 100644 --- a/doc/flame/examples/lib/color_effect.dart +++ b/doc/flame/examples/lib/color_effect.dart @@ -5,7 +5,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flutter/animation.dart'; -class ColorEffectExample extends FlameGame { +class ColorEffectExample() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/decorator_blur.dart b/doc/flame/examples/lib/decorator_blur.dart index 517e17e0e83..d63d83f0506 100644 --- a/doc/flame/examples/lib/decorator_blur.dart +++ b/doc/flame/examples/lib/decorator_blur.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; -class DecoratorBlurGame extends FlameGame { +class DecoratorBlurGame() extends FlameGame { @override Future onLoad() async { var step = 0; diff --git a/doc/flame/examples/lib/decorator_grayscale.dart b/doc/flame/examples/lib/decorator_grayscale.dart index c55618890e5..13fe869f5e2 100644 --- a/doc/flame/examples/lib/decorator_grayscale.dart +++ b/doc/flame/examples/lib/decorator_grayscale.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; -class DecoratorGrayscaleGame extends FlameGame { +class DecoratorGrayscaleGame() extends FlameGame { @override Future onLoad() async { var step = 0; diff --git a/doc/flame/examples/lib/decorator_hue.dart b/doc/flame/examples/lib/decorator_hue.dart index 94c8e4c7e78..39f63279b09 100644 --- a/doc/flame/examples/lib/decorator_hue.dart +++ b/doc/flame/examples/lib/decorator_hue.dart @@ -4,7 +4,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; -class DecoratorHueGame extends FlameGame { +class DecoratorHueGame() extends FlameGame { @override Future onLoad() async { var step = 0; diff --git a/doc/flame/examples/lib/decorator_rotate3d.dart b/doc/flame/examples/lib/decorator_rotate3d.dart index 6d300f9aed5..fbdcfa8efd2 100644 --- a/doc/flame/examples/lib/decorator_rotate3d.dart +++ b/doc/flame/examples/lib/decorator_rotate3d.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; -class DecoratorRotate3DGame extends FlameGame { +class DecoratorRotate3DGame() extends FlameGame { @override Future onLoad() async { var step = 0; diff --git a/doc/flame/examples/lib/decorator_shadow3d.dart b/doc/flame/examples/lib/decorator_shadow3d.dart index 3b7c43b7c46..a344a55402c 100644 --- a/doc/flame/examples/lib/decorator_shadow3d.dart +++ b/doc/flame/examples/lib/decorator_shadow3d.dart @@ -5,7 +5,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; -class DecoratorShadowGame extends FlameGame { +class DecoratorShadowGame() extends FlameGame { @override Color backgroundColor() => const Color(0xFFC7C7C7); @@ -52,7 +52,7 @@ class DecoratorShadowGame extends FlameGame { } } -class Grid extends Component { +class Grid() extends Component { final paint = Paint() ..color = const Color(0xffa9a9a9) ..style = PaintingStyle.stroke diff --git a/doc/flame/examples/lib/decorator_tint.dart b/doc/flame/examples/lib/decorator_tint.dart index 8ae52e6745c..093a8b31dc2 100644 --- a/doc/flame/examples/lib/decorator_tint.dart +++ b/doc/flame/examples/lib/decorator_tint.dart @@ -4,7 +4,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; -class DecoratorTintGame extends FlameGame { +class DecoratorTintGame() extends FlameGame { @override Future onLoad() async { var step = 0; diff --git a/doc/flame/examples/lib/drag_events.dart b/doc/flame/examples/lib/drag_events.dart index cb4253917fe..16c587a9824 100644 --- a/doc/flame/examples/lib/drag_events.dart +++ b/doc/flame/examples/lib/drag_events.dart @@ -6,7 +6,7 @@ import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:flutter/rendering.dart'; -class DragEventsGame extends FlameGame { +class DragEventsGame() extends FlameGame { @override Future onLoad() async { addAll([ @@ -49,8 +49,8 @@ class DragEventsGame extends FlameGame { /// This component is the pink-ish rectangle in the center of the game window. /// It uses the [DragCallbacks] mixin in order to receive drag events. -class DragTarget extends PositionComponent with DragCallbacks { - DragTarget() : super(anchor: Anchor.center); +class DragTarget() extends PositionComponent with DragCallbacks { + this : super(anchor: Anchor.center); final _rectPaint = Paint()..color = const Color(0x88AC54BF); @@ -99,11 +99,9 @@ class DragTarget extends PositionComponent with DragCallbacks { } } -class Trail extends Component { - Trail(Vector2 origin) - : _paths = [Path()..moveTo(origin.x, origin.y)], - _opacities = [1], - _lastPoint = origin.clone(), +class Trail(Vector2 origin) extends Component { + this + : _opacities = [1], _color = HSLColor.fromAHSL( 1, random.nextDouble() * 360, @@ -111,7 +109,7 @@ class Trail extends Component { 0.8, ).toColor(); - final List _paths; + final List _paths = [Path()..moveTo(origin.x, origin.y)]; final List _opacities; Color _color; late final _linePaint = Paint()..style = PaintingStyle.stroke; @@ -119,7 +117,7 @@ class Trail extends Component { bool _released = false; double _timer = 0; final _vanishInterval = 0.03; - final Vector2 _lastPoint; + final Vector2 _lastPoint = origin.clone(); static final random = Random(); static const lineWidth = 10.0; @@ -182,15 +180,15 @@ class Trail extends Component { } } -class Star extends PositionComponent with DragCallbacks { - Star({ - required int n, - required double radius1, - required double radius2, - required double sharpness, - required this.color, - super.position, - }) { +class Star({ + required int n, + required double radius1, + required double radius2, + required double sharpness, + required final Color color, + super.position, +}) extends PositionComponent with DragCallbacks { + this { _path = Path()..moveTo(radius1, 0); for (var i = 0; i < n; i++) { final p1 = Vector2(radius2, 0)..rotate(tau / n * (i + sharpness)); @@ -201,7 +199,6 @@ class Star extends PositionComponent with DragCallbacks { _path.close(); } - final Color color; final Paint _paint = Paint(); final Paint _borderPaint = Paint() ..color = const Color(0xFFffffff) diff --git a/doc/flame/examples/lib/ember.dart b/doc/flame/examples/lib/ember.dart index dfa81d2e9f0..428a483981e 100644 --- a/doc/flame/examples/lib/ember.dart +++ b/doc/flame/examples/lib/ember.dart @@ -3,16 +3,12 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/flame.dart'; -class EmberPlayer extends SpriteAnimationComponent with TapCallbacks { - EmberPlayer({ - required super.size, - super.position, - this._onTap, - }); - +class EmberPlayer({ + required super.size, + super.position, + final void Function(EmberPlayer player)? _onTap, +}) extends SpriteAnimationComponent with TapCallbacks { Vector2 velocity = Vector2(0, 0); - final void Function(EmberPlayer player)? _onTap; - @override Future onLoad() async { animation = SpriteAnimation.fromFrameData( diff --git a/doc/flame/examples/lib/flower.dart b/doc/flame/examples/lib/flower.dart index b364eb8a8d2..33601b498c6 100644 --- a/doc/flame/examples/lib/flower.dart +++ b/doc/flame/examples/lib/flower.dart @@ -5,16 +5,21 @@ import 'package:flame/events.dart'; import 'package:flame/geometry.dart'; import 'package:flame/rendering.dart'; -enum FlowerPaint { paintId1, paintId2, paintId3, paintId4, paintId5 } +enum FlowerPaint() { + paintId1, + paintId2, + paintId3, + paintId4, + paintId5, +} -class Flower extends PositionComponent - with TapCallbacks, HasPaint { - Flower({ - required double size, - this._onTap, - Decorator? decorator, - super.position, - }) : super(size: Vector2.all(size), anchor: Anchor.center) { +class Flower({ + required double size, + final void Function(Flower flower)? _onTap, + Decorator? decorator, + super.position, +}) extends PositionComponent with TapCallbacks, HasPaint { + this : super(size: Vector2.all(size), anchor: Anchor.center) { this.decorator.addLast(decorator); final radius = size * 0.38; _paths.add(_makePath(radius * 1.4, 6, -0.05, 0.8)); @@ -31,8 +36,6 @@ class Flower extends PositionComponent } final List _paths = []; - final void Function(Flower flower)? _onTap; - Path _makePath(double radius, int n, double sharpness, double f) { final radius2 = radius * f; final p0 = Vector2(radius, 0)..rotate(0); diff --git a/doc/flame/examples/lib/glow_effect.dart b/doc/flame/examples/lib/glow_effect.dart index 9fc2ee5e4f1..3b3ef4f3293 100644 --- a/doc/flame/examples/lib/glow_effect.dart +++ b/doc/flame/examples/lib/glow_effect.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class GlowEffectExample extends FlameGame { +class GlowEffectExample() extends FlameGame { @override Future onLoad() async { final paint = Paint()..color = const Color(0xff39FF14); diff --git a/doc/flame/examples/lib/hue_effect.dart b/doc/flame/examples/lib/hue_effect.dart index 6b396f25ec4..a6520be416b 100644 --- a/doc/flame/examples/lib/hue_effect.dart +++ b/doc/flame/examples/lib/hue_effect.dart @@ -5,7 +5,7 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class HueEffectExample extends FlameGame { +class HueEffectExample() extends FlameGame { @override Future onLoad() async { final ember = EmberPlayer( diff --git a/doc/flame/examples/lib/main.dart b/doc/flame/examples/lib/main.dart index 6e8fa5f8584..42451e7b8e4 100644 --- a/doc/flame/examples/lib/main.dart +++ b/doc/flame/examples/lib/main.dart @@ -94,13 +94,9 @@ void main() { } } -class _IndexRoute extends StatelessWidget { - final String page; - - const _IndexRoute({ - required this.page, - }); - +class const _IndexRoute({ + required final String page, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return Directionality( diff --git a/doc/flame/examples/lib/move_along_path_effect.dart b/doc/flame/examples/lib/move_along_path_effect.dart index d7ebabda235..9625480db94 100644 --- a/doc/flame/examples/lib/move_along_path_effect.dart +++ b/doc/flame/examples/lib/move_along_path_effect.dart @@ -4,7 +4,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class MoveAlongPathEffectGame extends FlameGame { +class MoveAlongPathEffectGame() extends FlameGame { bool reset = false; @override Future onLoad() async { diff --git a/doc/flame/examples/lib/move_by_effect.dart b/doc/flame/examples/lib/move_by_effect.dart index 459f929d1d8..73873f77c4d 100644 --- a/doc/flame/examples/lib/move_by_effect.dart +++ b/doc/flame/examples/lib/move_by_effect.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class MoveByEffectGame extends FlameGame { +class MoveByEffectGame() extends FlameGame { bool reset = false; @override Future onLoad() async { diff --git a/doc/flame/examples/lib/move_to_effect.dart b/doc/flame/examples/lib/move_to_effect.dart index 832be43adf4..581e32d1bf7 100644 --- a/doc/flame/examples/lib/move_to_effect.dart +++ b/doc/flame/examples/lib/move_to_effect.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class MoveToEffectGame extends FlameGame { +class MoveToEffectGame() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/opacity_by_effect.dart b/doc/flame/examples/lib/opacity_by_effect.dart index 5e691edc790..89aaa05c5d5 100644 --- a/doc/flame/examples/lib/opacity_by_effect.dart +++ b/doc/flame/examples/lib/opacity_by_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class OpacityByEffectGame extends FlameGame { +class OpacityByEffectGame() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/opacity_effect_with_target.dart b/doc/flame/examples/lib/opacity_effect_with_target.dart index 510b00c480d..a4493add95d 100644 --- a/doc/flame/examples/lib/opacity_effect_with_target.dart +++ b/doc/flame/examples/lib/opacity_effect_with_target.dart @@ -3,7 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class OpacityEffectWithTargetGame extends FlameGame { +class OpacityEffectWithTargetGame() extends FlameGame { bool reset = false; // This reference needs to be stored because every new instance of diff --git a/doc/flame/examples/lib/opacity_to_effect.dart b/doc/flame/examples/lib/opacity_to_effect.dart index 3a4a509d3ca..9cf2aac24b3 100644 --- a/doc/flame/examples/lib/opacity_to_effect.dart +++ b/doc/flame/examples/lib/opacity_to_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class OpacityToEffectGame extends FlameGame { +class OpacityToEffectGame() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/pointer_events.dart b/doc/flame/examples/lib/pointer_events.dart index ce89f949943..c447ecb522b 100644 --- a/doc/flame/examples/lib/pointer_events.dart +++ b/doc/flame/examples/lib/pointer_events.dart @@ -5,7 +5,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flutter/rendering.dart'; -class PointerEventsGame extends FlameGame with TapCallbacks { +class PointerEventsGame() extends FlameGame with TapCallbacks { @override Future onLoad() async { add(HoverTarget(Vector2(100, 200))); @@ -19,10 +19,12 @@ class PointerEventsGame extends FlameGame with TapCallbacks { } } -class HoverTarget extends PositionComponent with HoverCallbacks { +class HoverTarget(Vector2 position) + extends PositionComponent + with HoverCallbacks { static final Random _random = Random(); - HoverTarget(Vector2 position) + this : super( position: position, size: Vector2.all(50), diff --git a/doc/flame/examples/lib/post_process.dart b/doc/flame/examples/lib/post_process.dart index 2ef2e19eb0a..fffc819fd41 100644 --- a/doc/flame/examples/lib/post_process.dart +++ b/doc/flame/examples/lib/post_process.dart @@ -6,7 +6,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/post_process.dart'; -class PostProcessGame extends FlameGame { +class PostProcessGame() extends FlameGame { @override Future onLoad() async { await super.onLoad(); @@ -24,7 +24,7 @@ class PostProcessGame extends FlameGame { } } -class PixelationPostProcess extends PostProcess { +class PixelationPostProcess() extends PostProcess { @override Future onLoad() async { await super.onLoad(); diff --git a/doc/flame/examples/lib/ray_cast.dart b/doc/flame/examples/lib/ray_cast.dart index 65089a0de5e..d5d9d64f1ee 100644 --- a/doc/flame/examples/lib/ray_cast.dart +++ b/doc/flame/examples/lib/ray_cast.dart @@ -5,7 +5,7 @@ import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class RayCastExample extends FlameGame with HasCollisionDetection { +class RayCastExample() extends FlameGame with HasCollisionDetection { final origin = Vector2(20, 20); final direction = Vector2(1, 0); diff --git a/doc/flame/examples/lib/ray_trace.dart b/doc/flame/examples/lib/ray_trace.dart index d1903aea313..c090529f174 100644 --- a/doc/flame/examples/lib/ray_trace.dart +++ b/doc/flame/examples/lib/ray_trace.dart @@ -8,7 +8,8 @@ import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class RayTraceExample extends FlameGame +class RayTraceExample() + extends FlameGame with HasCollisionDetection, TapCallbacks { Paint paint = Paint()..color = Colors.red.withValues(alpha: 0.6); bool isClicked = false; diff --git a/doc/flame/examples/lib/remove_effect.dart b/doc/flame/examples/lib/remove_effect.dart index 550c635ef1e..9a722939ed1 100644 --- a/doc/flame/examples/lib/remove_effect.dart +++ b/doc/flame/examples/lib/remove_effect.dart @@ -4,7 +4,7 @@ import 'package:flame/effects.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class RemoveEffectGame extends FlameGame with TapCallbacks { +class RemoveEffectGame() extends FlameGame with TapCallbacks { static const double delayTime = 3; late EmberPlayer ember; late TextComponent textComponent; diff --git a/doc/flame/examples/lib/rive_example.dart b/doc/flame/examples/lib/rive_example.dart index cd3c0c53948..4941dacd296 100644 --- a/doc/flame/examples/lib/rive_example.dart +++ b/doc/flame/examples/lib/rive_example.dart @@ -4,7 +4,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame_rive/flame_rive.dart'; -class RiveExampleGame extends FlameGame with TapCallbacks { +class RiveExampleGame() extends FlameGame with TapCallbacks { ViewModelInstanceNumber? coinInput; ViewModelInstanceNumber? gemInput; diff --git a/doc/flame/examples/lib/rotate_around_effect.dart b/doc/flame/examples/lib/rotate_around_effect.dart index 557f157d663..acecfbdeecc 100644 --- a/doc/flame/examples/lib/rotate_around_effect.dart +++ b/doc/flame/examples/lib/rotate_around_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; -class RotateAroundEffectGame extends FlameGame { +class RotateAroundEffectGame() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/rotate_by_effect.dart b/doc/flame/examples/lib/rotate_by_effect.dart index 1be22feddc1..558a8829710 100644 --- a/doc/flame/examples/lib/rotate_by_effect.dart +++ b/doc/flame/examples/lib/rotate_by_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; -class RotateByEffectGame extends FlameGame { +class RotateByEffectGame() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/rotate_to_effect.dart b/doc/flame/examples/lib/rotate_to_effect.dart index 8d7ee67facc..eec95090bb8 100644 --- a/doc/flame/examples/lib/rotate_to_effect.dart +++ b/doc/flame/examples/lib/rotate_to_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; -class RotateToEffectGame extends FlameGame { +class RotateToEffectGame() extends FlameGame { bool reset = false; @override diff --git a/doc/flame/examples/lib/router.dart b/doc/flame/examples/lib/router.dart index f8b6bfc1f39..7efd473a06f 100644 --- a/doc/flame/examples/lib/router.dart +++ b/doc/flame/examples/lib/router.dart @@ -6,7 +6,7 @@ import 'package:flame/geometry.dart'; import 'package:flame/rendering.dart'; import 'package:flutter/rendering.dart'; -class RouterGame extends FlameGame { +class RouterGame() extends FlameGame { late final RouterComponent router; @override @@ -25,8 +25,8 @@ class RouterGame extends FlameGame { } } -class StartPage extends Component with HasGameRef { - StartPage() { +class StartPage() extends Component with HasGameRef { + this { addAll([ _logo = TextComponent( text: 'Your Game', @@ -67,31 +67,22 @@ class StartPage extends Component with HasGameRef { } } -class Background extends Component { - Background(this.color); - final Color color; - +class Background(final Color color) extends Component { @override void render(Canvas canvas) { canvas.drawColor(color, BlendMode.srcATop); } } -class RoundedButton extends PositionComponent with TapCallbacks { - RoundedButton({ - required this.text, - required this.action, - required Color color, - required Color borderColor, - super.position, - super.anchor = Anchor.center, - }) : _textDrawable = TextPaint( - style: const TextStyle( - fontSize: 20, - color: Color(0xFF000000), - fontWeight: FontWeight.w800, - ), - ).toTextPainter(text) { +class RoundedButton({ + required final String text, + required final void Function() action, + required Color color, + required Color borderColor, + super.position, + super.anchor = Anchor.center, +}) extends PositionComponent with TapCallbacks { + this { size = Vector2(150, 40); _textOffset = Offset( (size.x - _textDrawable.width) / 2, @@ -105,9 +96,13 @@ class RoundedButton extends PositionComponent with TapCallbacks { ..color = borderColor; } - final String text; - final void Function() action; - final TextPainter _textDrawable; + final TextPainter _textDrawable = TextPaint( + style: const TextStyle( + fontSize: 20, + color: Color(0xFF000000), + fontWeight: FontWeight.w800, + ), + ).toTextPainter(text); late final Offset _textOffset; late final RRect _rrect; late final Paint _borderPaint; @@ -137,8 +132,10 @@ class RoundedButton extends PositionComponent with TapCallbacks { } } -abstract class SimpleButton extends PositionComponent with TapCallbacks { - SimpleButton(this._iconPath, {super.position}) : super(size: Vector2.all(40)); +abstract class SimpleButton(final Path _iconPath, {super.position}) + extends PositionComponent + with TapCallbacks { + this : super(size: Vector2.all(40)); final Paint _borderPaint = Paint() ..style = PaintingStyle.stroke @@ -147,8 +144,6 @@ abstract class SimpleButton extends PositionComponent with TapCallbacks { ..style = PaintingStyle.stroke ..color = const Color(0xffaaaaaa) ..strokeWidth = 7; - final Path _iconPath; - void action(); @override @@ -177,8 +172,8 @@ abstract class SimpleButton extends PositionComponent with TapCallbacks { } } -class BackButton extends SimpleButton with HasGameRef { - BackButton() +class BackButton() extends SimpleButton with HasGameRef { + this : super( Path() ..moveTo(22, 8) @@ -193,8 +188,8 @@ class BackButton extends SimpleButton with HasGameRef { void action() => gameRef.router.pop(); } -class PauseButton extends SimpleButton with HasGameRef { - PauseButton() +class PauseButton() extends SimpleButton with HasGameRef { + this : super( Path() ..moveTo(14, 10) @@ -217,7 +212,7 @@ class PauseButton extends SimpleButton with HasGameRef { } } -class Level1Page extends DecoratedWorld with HasGameRef { +class Level1Page() extends DecoratedWorld with HasGameRef { @override Future onLoad() async { addAll([ @@ -264,7 +259,7 @@ class Level1Page extends DecoratedWorld with HasGameRef { } } -class Level2Page extends DecoratedWorld with HasGameRef { +class Level2Page() extends DecoratedWorld with HasGameRef { @override Future onLoad() async { addAll([ @@ -321,17 +316,13 @@ class Level2Page extends DecoratedWorld with HasGameRef { } } -class Planet extends PositionComponent { - Planet({ - required this.radius, - required this.color, - super.position, - super.children, - }) : _paint = Paint()..color = color; - - final double radius; - final Color color; - final Paint _paint; +class Planet({ + required final double radius, + required final Color color, + super.position, + super.children, +}) extends PositionComponent { + final Paint _paint = Paint()..color = color; @override void render(Canvas canvas) { @@ -339,24 +330,21 @@ class Planet extends PositionComponent { } } -class Orbit extends PositionComponent { - Orbit({ - required this.radius, - required this.planet, - required this.revolutionPeriod, - double initialAngle = 0, - }) : _paint = Paint() - ..style = PaintingStyle.stroke - ..color = const Color(0x888888aa), - _angle = initialAngle { +class Orbit({ + required final double radius, + required final Planet planet, + required final double revolutionPeriod, + double initialAngle = 0, +}) extends PositionComponent { + this + : _paint = Paint() + ..style = PaintingStyle.stroke + ..color = const Color(0x888888aa) { add(planet); } - final double radius; - final double revolutionPeriod; - final Planet planet; final Paint _paint; - double _angle; + double _angle = initialAngle; @override void render(Canvas canvas) { @@ -370,8 +358,8 @@ class Orbit extends PositionComponent { } } -class PauseRoute extends Route { - PauseRoute() : super(PausePage.new, transparent: true); +class PauseRoute() extends Route { + this : super(PausePage.new, transparent: true); @override void onPush(Route? previousRoute) { @@ -391,7 +379,7 @@ class PauseRoute extends Route { } } -class PausePage extends Component with TapCallbacks, HasGameRef { +class PausePage() extends Component with TapCallbacks, HasGameRef { @override Future onLoad() async { final game = findGame()!; @@ -421,7 +409,7 @@ class PausePage extends Component with TapCallbacks, HasGameRef { void onTapUp(TapUpEvent event) => gameRef.router.pop(); } -class DecoratedWorld extends World with CustomTraversal, HasTimeScale { +class DecoratedWorld() extends World with CustomTraversal, HasTimeScale { PaintDecorator? decorator; @override diff --git a/doc/flame/examples/lib/scale_by_effect.dart b/doc/flame/examples/lib/scale_by_effect.dart index 828e8ea96a4..b7ac862dbc0 100644 --- a/doc/flame/examples/lib/scale_by_effect.dart +++ b/doc/flame/examples/lib/scale_by_effect.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class ScaleByEffectGame extends FlameGame { +class ScaleByEffectGame() extends FlameGame { bool reverse = false; bool hold = false; @override diff --git a/doc/flame/examples/lib/scale_to_effect.dart b/doc/flame/examples/lib/scale_to_effect.dart index d64773e57f4..d71fdbd895b 100644 --- a/doc/flame/examples/lib/scale_to_effect.dart +++ b/doc/flame/examples/lib/scale_to_effect.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class ScaleToEffectGame extends FlameGame { +class ScaleToEffectGame() extends FlameGame { bool reverse = false; bool hold = false; @override diff --git a/doc/flame/examples/lib/sequence_effect.dart b/doc/flame/examples/lib/sequence_effect.dart index b6f9801f8c8..781724ab338 100644 --- a/doc/flame/examples/lib/sequence_effect.dart +++ b/doc/flame/examples/lib/sequence_effect.dart @@ -2,7 +2,7 @@ import 'package:doc_flame_examples/flower.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class SequenceEffectGame extends FlameGame { +class SequenceEffectGame() extends FlameGame { @override Future onLoad() async { final flower = Flower( diff --git a/doc/flame/examples/lib/size_by_effect.dart b/doc/flame/examples/lib/size_by_effect.dart index 64e188e6e49..d079b66d2f2 100644 --- a/doc/flame/examples/lib/size_by_effect.dart +++ b/doc/flame/examples/lib/size_by_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class SizeByEffectGame extends FlameGame { +class SizeByEffectGame() extends FlameGame { bool reset = false; @override Future onLoad() async { diff --git a/doc/flame/examples/lib/size_to_effect.dart b/doc/flame/examples/lib/size_to_effect.dart index cdde1b01fdc..774259c6073 100644 --- a/doc/flame/examples/lib/size_to_effect.dart +++ b/doc/flame/examples/lib/size_to_effect.dart @@ -3,7 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class SizeToEffectGame extends FlameGame { +class SizeToEffectGame() extends FlameGame { bool reset = false; @override Future onLoad() async { diff --git a/doc/flame/examples/lib/tap_events.dart b/doc/flame/examples/lib/tap_events.dart index bcc540e07f3..f6756617f88 100644 --- a/doc/flame/examples/lib/tap_events.dart +++ b/doc/flame/examples/lib/tap_events.dart @@ -5,7 +5,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flutter/rendering.dart'; -class TapEventsGame extends FlameGame { +class TapEventsGame() extends FlameGame { @override Future onLoad() async { add(TapTarget()); @@ -14,8 +14,8 @@ class TapEventsGame extends FlameGame { /// This component is the tappable blue-ish rectangle in the center of the game. /// It uses the [TapCallbacks] mixin to receive tap events. -class TapTarget extends PositionComponent with TapCallbacks { - TapTarget() : super(anchor: Anchor.center); +class TapTarget() extends PositionComponent with TapCallbacks { + this : super(anchor: Anchor.center); final _paint = Paint()..color = const Color(0x448BA8FF); @@ -61,8 +61,8 @@ class TapTarget extends PositionComponent with TapCallbacks { } } -class ExpandingCircle extends Component { - ExpandingCircle(this._center) +class ExpandingCircle(final Vector2 _center) extends Component { + this : _baseColor = HSLColor.fromAHSL( 1, random.nextDouble() * 360, @@ -71,7 +71,6 @@ class ExpandingCircle extends Component { ).toColor(); final Color _baseColor; - final Vector2 _center; double _outerRadius = 0; double _innerRadius = 0; bool _released = false; diff --git a/doc/flame/examples/lib/time_scale.dart b/doc/flame/examples/lib/time_scale.dart index e0ba9b59cc2..fc9e67a8320 100644 --- a/doc/flame/examples/lib/time_scale.dart +++ b/doc/flame/examples/lib/time_scale.dart @@ -4,7 +4,7 @@ import 'package:doc_flame_examples/ember.dart'; import 'package:flame/components.dart'; import 'package:flame/game.dart'; -class TimeScaleGame extends FlameGame with HasTimeScale { +class TimeScaleGame() extends FlameGame with HasTimeScale { final _timeScales = [0.5, 1.0, 2.0]; var _index = 1; @@ -17,7 +17,7 @@ class TimeScaleGame extends FlameGame with HasTimeScale { onTap: (p0) => timeScale = getNextTimeScale(), ), ); - return super.onLoad(); + await super.onLoad(); } double getNextTimeScale() { diff --git a/doc/flame/examples/lib/value_route.dart b/doc/flame/examples/lib/value_route.dart index 01fba63472c..43956b844fa 100644 --- a/doc/flame/examples/lib/value_route.dart +++ b/doc/flame/examples/lib/value_route.dart @@ -7,7 +7,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; -class ValueRouteExample extends FlameGame { +class ValueRouteExample() extends FlameGame { late final RouterComponent router; @override @@ -20,7 +20,7 @@ class ValueRouteExample extends FlameGame { } } -class HomePage extends Component with HasGameRef { +class HomePage() extends Component with HasGameRef { @override Future onLoad() async { add( @@ -46,8 +46,8 @@ class HomePage extends Component with HasGameRef { } } -class RateRoute extends ValueRoute with HasGameRef { - RateRoute() : super(value: -1, transparent: true); +class RateRoute() extends ValueRoute with HasGameRef { + this : super(value: -1, transparent: true); @override Component build() { @@ -80,20 +80,23 @@ class RateRoute extends ValueRoute with HasGameRef { } } -class DialogBackground extends RectangleComponent with TapCallbacks { - DialogBackground({super.position, super.size, super.children}) +class DialogBackground({super.position, super.size, super.children}) + extends RectangleComponent + with TapCallbacks { + this : super( anchor: Anchor.center, paint: Paint()..color = const Color(0xee858585), ); } -class Star extends PositionComponent with TapCallbacks { - Star({required this.value, required this.radius, super.position}) - : super(size: Vector2.all(2 * radius), anchor: Anchor.center); +class Star({ + required final int value, + required final double radius, + super.position, +}) extends PositionComponent with TapCallbacks { + this : super(size: Vector2.all(2 * radius), anchor: Anchor.center); - final int value; - final double radius; final Path path = Path(); final Paint borderPaint = Paint() ..style = PaintingStyle.stroke diff --git a/doc/flame/examples/pubspec.yaml b/doc/flame/examples/pubspec.yaml index 68e16449410..dd39cdaa8e1 100644 --- a/doc/flame/examples/pubspec.yaml +++ b/doc/flame/examples/pubspec.yaml @@ -5,8 +5,8 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: cupertino_ui: any diff --git a/doc/tutorials/klondike/app/lib/step2/components/foundation.dart b/doc/tutorials/klondike/app/lib/step2/components/foundation.dart index 9da612ce100..9395083c626 100644 --- a/doc/tutorials/klondike/app/lib/step2/components/foundation.dart +++ b/doc/tutorials/klondike/app/lib/step2/components/foundation.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Foundation extends PositionComponent { +class Foundation() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step2/components/pile.dart b/doc/tutorials/klondike/app/lib/step2/components/pile.dart index 7dcff07e1da..a481216d32b 100644 --- a/doc/tutorials/klondike/app/lib/step2/components/pile.dart +++ b/doc/tutorials/klondike/app/lib/step2/components/pile.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Pile extends PositionComponent { +class Pile() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step2/components/stock.dart b/doc/tutorials/klondike/app/lib/step2/components/stock.dart index 90656bed131..5ee860a87e0 100644 --- a/doc/tutorials/klondike/app/lib/step2/components/stock.dart +++ b/doc/tutorials/klondike/app/lib/step2/components/stock.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Stock extends PositionComponent { +class Stock() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step2/components/waste.dart b/doc/tutorials/klondike/app/lib/step2/components/waste.dart index dff70d4ce1c..17ce859243a 100644 --- a/doc/tutorials/klondike/app/lib/step2/components/waste.dart +++ b/doc/tutorials/klondike/app/lib/step2/components/waste.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Waste extends PositionComponent { +class Waste() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step2/klondike_game.dart b/doc/tutorials/klondike/app/lib/step2/klondike_game.dart index a6c88a66097..b27ee24b670 100644 --- a/doc/tutorials/klondike/app/lib/step2/klondike_game.dart +++ b/doc/tutorials/klondike/app/lib/step2/klondike_game.dart @@ -7,7 +7,7 @@ import 'components/pile.dart'; import 'components/stock.dart'; import 'components/waste.dart'; -class KlondikeGame extends FlameGame { +class KlondikeGame() extends FlameGame { static const double cardGap = 175.0; static const double cardWidth = 1000.0; static const double cardHeight = 1400.0; diff --git a/doc/tutorials/klondike/app/lib/step3/components/card.dart b/doc/tutorials/klondike/app/lib/step3/components/card.dart index fec7dd8634b..aa63760453c 100644 --- a/doc/tutorials/klondike/app/lib/step3/components/card.dart +++ b/doc/tutorials/klondike/app/lib/step3/components/card.dart @@ -2,19 +2,16 @@ import 'dart:math'; import 'dart:ui'; import 'package:flame/components.dart'; + import '../klondike_game.dart'; import '../rank.dart'; import '../suit.dart'; -class Card extends PositionComponent { - Card(int intRank, int intSuit) - : rank = Rank.fromInt(intRank), - suit = Suit.fromInt(intSuit), - _faceUp = false, - super(size: KlondikeGame.cardSize); +class Card(int intRank, int intSuit) extends PositionComponent { + this : _faceUp = false, super(size: KlondikeGame.cardSize); - final Rank rank; - final Suit suit; + final Rank rank = Rank.fromInt(intRank); + final Suit suit = Suit.fromInt(intSuit); bool _faceUp; bool get isFaceUp => _faceUp; diff --git a/doc/tutorials/klondike/app/lib/step3/components/foundation.dart b/doc/tutorials/klondike/app/lib/step3/components/foundation.dart index 9da612ce100..9395083c626 100644 --- a/doc/tutorials/klondike/app/lib/step3/components/foundation.dart +++ b/doc/tutorials/klondike/app/lib/step3/components/foundation.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Foundation extends PositionComponent { +class Foundation() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step3/components/pile.dart b/doc/tutorials/klondike/app/lib/step3/components/pile.dart index 7dcff07e1da..a481216d32b 100644 --- a/doc/tutorials/klondike/app/lib/step3/components/pile.dart +++ b/doc/tutorials/klondike/app/lib/step3/components/pile.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Pile extends PositionComponent { +class Pile() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step3/components/stock.dart b/doc/tutorials/klondike/app/lib/step3/components/stock.dart index 90656bed131..5ee860a87e0 100644 --- a/doc/tutorials/klondike/app/lib/step3/components/stock.dart +++ b/doc/tutorials/klondike/app/lib/step3/components/stock.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Stock extends PositionComponent { +class Stock() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step3/components/waste.dart b/doc/tutorials/klondike/app/lib/step3/components/waste.dart index dff70d4ce1c..17ce859243a 100644 --- a/doc/tutorials/klondike/app/lib/step3/components/waste.dart +++ b/doc/tutorials/klondike/app/lib/step3/components/waste.dart @@ -1,6 +1,6 @@ import 'package:flame/components.dart'; -class Waste extends PositionComponent { +class Waste() extends PositionComponent { @override bool get debugMode => true; } diff --git a/doc/tutorials/klondike/app/lib/step3/klondike_game.dart b/doc/tutorials/klondike/app/lib/step3/klondike_game.dart index d1b43769255..3d0f856c300 100644 --- a/doc/tutorials/klondike/app/lib/step3/klondike_game.dart +++ b/doc/tutorials/klondike/app/lib/step3/klondike_game.dart @@ -10,7 +10,7 @@ import 'components/pile.dart'; import 'components/stock.dart'; import 'components/waste.dart'; -class KlondikeGame extends FlameGame { +class KlondikeGame() extends FlameGame { static const double cardGap = 175.0; static const double cardWidth = 1000.0; static const double cardHeight = 1400.0; diff --git a/doc/tutorials/klondike/app/lib/step3/rank.dart b/doc/tutorials/klondike/app/lib/step3/rank.dart index 0e23c401515..44f6aa36ae9 100644 --- a/doc/tutorials/klondike/app/lib/step3/rank.dart +++ b/doc/tutorials/klondike/app/lib/step3/rank.dart @@ -1,9 +1,20 @@ import 'package:flame/components.dart'; import 'package:flutter/foundation.dart'; + import 'klondike_game.dart'; @immutable -class Rank { +// ignore: prefer_const_constructors_in_immutables +class Rank._( + final int value, + final String label, + double x1, + double y1, + double x2, + double y2, + double w, + double h, +) { factory Rank.fromInt(int value) { assert( value >= 1 && value <= 13, @@ -12,22 +23,8 @@ class Rank { return _singletons[value - 1]; } - Rank._( - this.value, - this.label, - double x1, - double y1, - double x2, - double y2, - double w, - double h, - ) : redSprite = klondikeSprite(x1, y1, w, h), - blackSprite = klondikeSprite(x2, y2, w, h); - - final int value; - final String label; - final Sprite redSprite; - final Sprite blackSprite; + final Sprite redSprite = klondikeSprite(x1, y1, w, h); + final Sprite blackSprite = klondikeSprite(x2, y2, w, h); static final List _singletons = [ Rank._(1, 'A', 335, 164, 789, 161, 120, 129), diff --git a/doc/tutorials/klondike/app/lib/step3/suit.dart b/doc/tutorials/klondike/app/lib/step3/suit.dart index d516180c9ea..797470126d2 100644 --- a/doc/tutorials/klondike/app/lib/step3/suit.dart +++ b/doc/tutorials/klondike/app/lib/step3/suit.dart @@ -1,9 +1,18 @@ import 'package:flame/sprite.dart'; import 'package:flutter/foundation.dart'; + import 'klondike_game.dart'; @immutable -class Suit { +// ignore: prefer_const_constructors_in_immutables +class Suit._( + final int value, + final String label, + double x, + double y, + double w, + double h, +) { factory Suit.fromInt(int index) { assert( index >= 0 && index <= 3, @@ -12,12 +21,7 @@ class Suit { return _singletons[index]; } - Suit._(this.value, this.label, double x, double y, double w, double h) - : sprite = klondikeSprite(x, y, w, h); - - final int value; - final String label; - final Sprite sprite; + final Sprite sprite = klondikeSprite(x, y, w, h); static final List _singletons = [ Suit._(0, '♥', 1176, 17, 172, 183), diff --git a/doc/tutorials/klondike/app/lib/step4/components/card.dart b/doc/tutorials/klondike/app/lib/step4/components/card.dart index 8f99afad943..947b37bd6e6 100644 --- a/doc/tutorials/klondike/app/lib/step4/components/card.dart +++ b/doc/tutorials/klondike/app/lib/step4/components/card.dart @@ -3,20 +3,20 @@ import 'dart:ui'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; + import '../klondike_game.dart'; import '../pile.dart'; import '../rank.dart'; import '../suit.dart'; import 'tableau_pile.dart'; -class Card extends PositionComponent with DragCallbacks { - Card(int intRank, int intSuit) - : rank = Rank.fromInt(intRank), - suit = Suit.fromInt(intSuit), - super(size: KlondikeGame.cardSize); +class Card(int intRank, int intSuit) + extends PositionComponent + with DragCallbacks { + this : super(size: KlondikeGame.cardSize); - final Rank rank; - final Suit suit; + final Rank rank = Rank.fromInt(intRank); + final Suit suit = Suit.fromInt(intSuit); Pile? pile; bool _faceUp = false; bool _isDragging = false; diff --git a/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart b/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart index ce2fc3a14c6..372431d775a 100644 --- a/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart +++ b/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart @@ -7,12 +7,12 @@ import '../pile.dart'; import '../suit.dart'; import 'card.dart'; -class FoundationPile extends PositionComponent implements Pile { - FoundationPile(int intSuit, {super.position}) - : suit = Suit.fromInt(intSuit), - super(size: KlondikeGame.cardSize); +class FoundationPile(int intSuit, {super.position}) + extends PositionComponent + implements Pile { + this : super(size: KlondikeGame.cardSize); - final Suit suit; + final Suit suit = Suit.fromInt(intSuit); final List _cards = []; //#region Pile API diff --git a/doc/tutorials/klondike/app/lib/step4/components/stock_pile.dart b/doc/tutorials/klondike/app/lib/step4/components/stock_pile.dart index 3a85debf7a7..2cae902cea6 100644 --- a/doc/tutorials/klondike/app/lib/step4/components/stock_pile.dart +++ b/doc/tutorials/klondike/app/lib/step4/components/stock_pile.dart @@ -8,8 +8,11 @@ import '../pile.dart'; import 'card.dart'; import 'waste_pile.dart'; -class StockPile extends PositionComponent with TapCallbacks implements Pile { - StockPile({super.position}) : super(size: KlondikeGame.cardSize); +class StockPile({super.position}) + extends PositionComponent + with TapCallbacks + implements Pile { + this : super(size: KlondikeGame.cardSize); /// Which cards are currently placed onto this pile. The first card in the /// list is at the bottom, the last card is on top. diff --git a/doc/tutorials/klondike/app/lib/step4/components/tableau_pile.dart b/doc/tutorials/klondike/app/lib/step4/components/tableau_pile.dart index 7f4a41399f8..1ea0deca009 100644 --- a/doc/tutorials/klondike/app/lib/step4/components/tableau_pile.dart +++ b/doc/tutorials/klondike/app/lib/step4/components/tableau_pile.dart @@ -6,8 +6,8 @@ import '../klondike_game.dart'; import '../pile.dart'; import 'card.dart'; -class TableauPile extends PositionComponent implements Pile { - TableauPile({super.position}) : super(size: KlondikeGame.cardSize); +class TableauPile({super.position}) extends PositionComponent implements Pile { + this : super(size: KlondikeGame.cardSize); /// Which cards are currently placed onto this pile. final List _cards = []; diff --git a/doc/tutorials/klondike/app/lib/step4/components/waste_pile.dart b/doc/tutorials/klondike/app/lib/step4/components/waste_pile.dart index bb8bc0e56aa..40885ae8947 100644 --- a/doc/tutorials/klondike/app/lib/step4/components/waste_pile.dart +++ b/doc/tutorials/klondike/app/lib/step4/components/waste_pile.dart @@ -4,8 +4,8 @@ import '../klondike_game.dart'; import '../pile.dart'; import 'card.dart'; -class WastePile extends PositionComponent implements Pile { - WastePile({super.position}) : super(size: KlondikeGame.cardSize); +class WastePile({super.position}) extends PositionComponent implements Pile { + this : super(size: KlondikeGame.cardSize); final List _cards = []; final Vector2 _fanOffset = Vector2(KlondikeGame.cardWidth * 0.2, 0); diff --git a/doc/tutorials/klondike/app/lib/step4/klondike_game.dart b/doc/tutorials/klondike/app/lib/step4/klondike_game.dart index 2b1d1e815c2..84ac16b42af 100644 --- a/doc/tutorials/klondike/app/lib/step4/klondike_game.dart +++ b/doc/tutorials/klondike/app/lib/step4/klondike_game.dart @@ -10,7 +10,7 @@ import 'components/stock_pile.dart'; import 'components/tableau_pile.dart'; import 'components/waste_pile.dart'; -class KlondikeGame extends FlameGame { +class KlondikeGame() extends FlameGame { static const double cardGap = 175.0; static const double cardWidth = 1000.0; static const double cardHeight = 1400.0; diff --git a/doc/tutorials/klondike/app/lib/step4/pile.dart b/doc/tutorials/klondike/app/lib/step4/pile.dart index de001f92d29..34536b81ac2 100644 --- a/doc/tutorials/klondike/app/lib/step4/pile.dart +++ b/doc/tutorials/klondike/app/lib/step4/pile.dart @@ -1,6 +1,6 @@ import 'components/card.dart'; -abstract class Pile { +abstract class Pile() { /// Returns true if the [card] can be taken away from this pile and moved /// somewhere else. bool canMoveCard(Card card); diff --git a/doc/tutorials/klondike/app/lib/step4/rank.dart b/doc/tutorials/klondike/app/lib/step4/rank.dart index 0e23c401515..44f6aa36ae9 100644 --- a/doc/tutorials/klondike/app/lib/step4/rank.dart +++ b/doc/tutorials/klondike/app/lib/step4/rank.dart @@ -1,9 +1,20 @@ import 'package:flame/components.dart'; import 'package:flutter/foundation.dart'; + import 'klondike_game.dart'; @immutable -class Rank { +// ignore: prefer_const_constructors_in_immutables +class Rank._( + final int value, + final String label, + double x1, + double y1, + double x2, + double y2, + double w, + double h, +) { factory Rank.fromInt(int value) { assert( value >= 1 && value <= 13, @@ -12,22 +23,8 @@ class Rank { return _singletons[value - 1]; } - Rank._( - this.value, - this.label, - double x1, - double y1, - double x2, - double y2, - double w, - double h, - ) : redSprite = klondikeSprite(x1, y1, w, h), - blackSprite = klondikeSprite(x2, y2, w, h); - - final int value; - final String label; - final Sprite redSprite; - final Sprite blackSprite; + final Sprite redSprite = klondikeSprite(x1, y1, w, h); + final Sprite blackSprite = klondikeSprite(x2, y2, w, h); static final List _singletons = [ Rank._(1, 'A', 335, 164, 789, 161, 120, 129), diff --git a/doc/tutorials/klondike/app/lib/step4/suit.dart b/doc/tutorials/klondike/app/lib/step4/suit.dart index d516180c9ea..797470126d2 100644 --- a/doc/tutorials/klondike/app/lib/step4/suit.dart +++ b/doc/tutorials/klondike/app/lib/step4/suit.dart @@ -1,9 +1,18 @@ import 'package:flame/sprite.dart'; import 'package:flutter/foundation.dart'; + import 'klondike_game.dart'; @immutable -class Suit { +// ignore: prefer_const_constructors_in_immutables +class Suit._( + final int value, + final String label, + double x, + double y, + double w, + double h, +) { factory Suit.fromInt(int index) { assert( index >= 0 && index <= 3, @@ -12,12 +21,7 @@ class Suit { return _singletons[index]; } - Suit._(this.value, this.label, double x, double y, double w, double h) - : sprite = klondikeSprite(x, y, w, h); - - final int value; - final String label; - final Sprite sprite; + final Sprite sprite = klondikeSprite(x, y, w, h); static final List _singletons = [ Suit._(0, '♥', 1176, 17, 172, 183), diff --git a/doc/tutorials/klondike/app/lib/step5/components/card.dart b/doc/tutorials/klondike/app/lib/step5/components/card.dart index 33222488da6..96c78928bc6 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/card.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/card.dart @@ -15,17 +15,16 @@ import 'foundation_pile.dart'; import 'stock_pile.dart'; import 'tableau_pile.dart'; -class Card extends PositionComponent +class Card(int intRank, int intSuit, {final bool isBaseCard = false}) + extends PositionComponent with DragCallbacks, TapCallbacks, HasWorldRef { - Card(int intRank, int intSuit, {this.isBaseCard = false}) - : rank = Rank.fromInt(intRank), - suit = Suit.fromInt(intSuit), - super( + this + : super( size: KlondikeGame.cardSize, ); - final Rank rank; - final Suit suit; + final Rank rank = Rank.fromInt(intRank); + final Suit suit = Suit.fromInt(intSuit); Pile? pile; // A Base Card is rendered in outline only and is NOT playable. It can be @@ -33,8 +32,6 @@ class Card extends PositionComponent // taps and short drags (on an empty Pile) with the same behavior and // tolerances as for regular cards (see KlondikeGame.dragTolerance) and using // the same event-handling code, but with different handleTapUp() methods. - final bool isBaseCard; - bool _faceUp = false; bool _isAnimatedFlip = false; bool _isFaceUpView = false; @@ -486,16 +483,12 @@ class Card extends PositionComponent //#endregion } -class CardMoveEffect extends MoveToEffect { - CardMoveEffect( - super.destination, - super.controller, { - super.onComplete, - this.transitPriority = 100, - }); - - final int transitPriority; - +class CardMoveEffect( + super.destination, + super.controller, { + super.onComplete, + final int transitPriority = 100, +}) extends MoveToEffect { @override void onStart() { super.onStart(); // Flame connects MoveToEffect to EffectController. diff --git a/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart b/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart index 566ba1b7b84..aee6f5fc3b1 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart @@ -3,39 +3,42 @@ import 'package:flame/input.dart'; import 'package:flame/text.dart'; import 'package:material_ui/material_ui.dart'; -class FlatButton extends ButtonComponent { - FlatButton( - String text, { - super.size, - super.onReleased, - super.position, - }) : super( - button: ButtonBackground(const Color(0xffece8a3)), - buttonDown: ButtonBackground(Colors.red), - children: [ - TextComponent( - text: text, - textRenderer: TextPaint( - style: TextStyle( - fontSize: 0.5 * size!.y, - fontWeight: FontWeight.bold, - color: const Color(0xffdbaf58), - ), - ), - position: size / 2.0, - anchor: Anchor.center, - ), - ], - anchor: Anchor.center, - ); +class FlatButton( + String text, { + super.size, + super.onReleased, + super.position, +}) extends ButtonComponent { + this + : super( + button: ButtonBackground(const Color(0xffece8a3)), + buttonDown: ButtonBackground(Colors.red), + children: [ + TextComponent( + text: text, + textRenderer: TextPaint( + style: TextStyle( + fontSize: 0.5 * size!.y, + fontWeight: FontWeight.bold, + color: const Color(0xffdbaf58), + ), + ), + position: size / 2.0, + anchor: Anchor.center, + ), + ], + anchor: Anchor.center, + ); } -class ButtonBackground extends PositionComponent with HasAncestor { +class ButtonBackground(Color color) + extends PositionComponent + with HasAncestor { final _paint = Paint()..style = PaintingStyle.stroke; late double cornerRadius; - ButtonBackground(Color color) { + this { _paint.color = color; } diff --git a/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart b/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart index 4ec0ff2ee57..30cc4ed5fd4 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart @@ -7,14 +7,12 @@ import '../pile.dart'; import '../suit.dart'; import 'card.dart'; -class FoundationPile extends PositionComponent implements Pile { - FoundationPile(int intSuit, this.checkWin, {super.position}) - : suit = Suit.fromInt(intSuit), - super(size: KlondikeGame.cardSize); +class FoundationPile(int intSuit, final VoidCallback checkWin, {super.position}) + extends PositionComponent + implements Pile { + this : super(size: KlondikeGame.cardSize); - final VoidCallback checkWin; - - final Suit suit; + final Suit suit = Suit.fromInt(intSuit); final List _cards = []; //#region Pile API diff --git a/doc/tutorials/klondike/app/lib/step5/components/stock_pile.dart b/doc/tutorials/klondike/app/lib/step5/components/stock_pile.dart index 9f234b8f47e..cf5cab54b23 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/stock_pile.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/stock_pile.dart @@ -7,10 +7,11 @@ import '../pile.dart'; import 'card.dart'; import 'waste_pile.dart'; -class StockPile extends PositionComponent +class StockPile({super.position}) + extends PositionComponent with HasGameRef implements Pile { - StockPile({super.position}) : super(size: KlondikeGame.cardSize); + this : super(size: KlondikeGame.cardSize); /// Which cards are currently placed onto this pile. The first card in the /// list is at the bottom, the last card is on top. diff --git a/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart b/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart index bcde19897d7..a22af52f94f 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart @@ -6,8 +6,8 @@ import '../klondike_game.dart'; import '../pile.dart'; import 'card.dart'; -class TableauPile extends PositionComponent implements Pile { - TableauPile({super.position}) : super(size: KlondikeGame.cardSize); +class TableauPile({super.position}) extends PositionComponent implements Pile { + this : super(size: KlondikeGame.cardSize); /// Which cards are currently placed onto this pile. final List _cards = []; diff --git a/doc/tutorials/klondike/app/lib/step5/components/waste_pile.dart b/doc/tutorials/klondike/app/lib/step5/components/waste_pile.dart index fd5c29c8199..c70a7320dde 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/waste_pile.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/waste_pile.dart @@ -4,10 +4,11 @@ import '../klondike_game.dart'; import '../pile.dart'; import 'card.dart'; -class WastePile extends PositionComponent +class WastePile({super.position}) + extends PositionComponent with HasGameRef implements Pile { - WastePile({super.position}) : super(size: KlondikeGame.cardSize); + this : super(size: KlondikeGame.cardSize); final List _cards = []; final Vector2 _fanOffset = Vector2(KlondikeGame.cardWidth * 0.2, 0); diff --git a/doc/tutorials/klondike/app/lib/step5/klondike_game.dart b/doc/tutorials/klondike/app/lib/step5/klondike_game.dart index 83731ce11c8..49f83b5693f 100644 --- a/doc/tutorials/klondike/app/lib/step5/klondike_game.dart +++ b/doc/tutorials/klondike/app/lib/step5/klondike_game.dart @@ -6,9 +6,14 @@ import 'package:flame/game.dart'; import 'klondike_world.dart'; -enum Action { newDeal, sameDeal, changeDraw, haveFun } +enum Action() { + newDeal, + sameDeal, + changeDraw, + haveFun, +} -class KlondikeGame extends FlameGame { +class KlondikeGame() extends FlameGame { static const double cardGap = 175.0; static const double topGap = 500.0; static const double cardWidth = 1000.0; @@ -29,7 +34,7 @@ class KlondikeGame extends FlameGame { static const int maxInt = 0xFFFFFFFE; // = (2 to the power 32) - 1 // This KlondikeGame constructor also initiates the first KlondikeWorld. - KlondikeGame() : super(world: KlondikeWorld()); + this : super(world: KlondikeWorld()); // These three values persist between games and are starting conditions // for the next game to be played in KlondikeWorld. The actual seed is diff --git a/doc/tutorials/klondike/app/lib/step5/klondike_world.dart b/doc/tutorials/klondike/app/lib/step5/klondike_world.dart index 9ea9911a350..c9165602836 100644 --- a/doc/tutorials/klondike/app/lib/step5/klondike_world.dart +++ b/doc/tutorials/klondike/app/lib/step5/klondike_world.dart @@ -12,7 +12,7 @@ import 'components/waste_pile.dart'; import 'klondike_game.dart'; -class KlondikeWorld extends World with HasGameRef { +class KlondikeWorld() extends World with HasGameRef { final cardGap = KlondikeGame.cardGap; final topGap = KlondikeGame.topGap; final cardSpaceWidth = KlondikeGame.cardSpaceWidth; diff --git a/doc/tutorials/klondike/app/lib/step5/pile.dart b/doc/tutorials/klondike/app/lib/step5/pile.dart index b19022fd573..471dac13f2b 100644 --- a/doc/tutorials/klondike/app/lib/step5/pile.dart +++ b/doc/tutorials/klondike/app/lib/step5/pile.dart @@ -1,8 +1,11 @@ import 'components/card.dart'; -enum MoveMethod { drag, tap } +enum MoveMethod() { + drag, + tap, +} -abstract class Pile { +abstract class Pile() { /// Returns true if the [card] can be taken away from this pile and moved /// somewhere else. A tapping move may need additional validation. bool canMoveCard(Card card, MoveMethod method); diff --git a/doc/tutorials/klondike/app/lib/step5/rank.dart b/doc/tutorials/klondike/app/lib/step5/rank.dart index 0e23c401515..44f6aa36ae9 100644 --- a/doc/tutorials/klondike/app/lib/step5/rank.dart +++ b/doc/tutorials/klondike/app/lib/step5/rank.dart @@ -1,9 +1,20 @@ import 'package:flame/components.dart'; import 'package:flutter/foundation.dart'; + import 'klondike_game.dart'; @immutable -class Rank { +// ignore: prefer_const_constructors_in_immutables +class Rank._( + final int value, + final String label, + double x1, + double y1, + double x2, + double y2, + double w, + double h, +) { factory Rank.fromInt(int value) { assert( value >= 1 && value <= 13, @@ -12,22 +23,8 @@ class Rank { return _singletons[value - 1]; } - Rank._( - this.value, - this.label, - double x1, - double y1, - double x2, - double y2, - double w, - double h, - ) : redSprite = klondikeSprite(x1, y1, w, h), - blackSprite = klondikeSprite(x2, y2, w, h); - - final int value; - final String label; - final Sprite redSprite; - final Sprite blackSprite; + final Sprite redSprite = klondikeSprite(x1, y1, w, h); + final Sprite blackSprite = klondikeSprite(x2, y2, w, h); static final List _singletons = [ Rank._(1, 'A', 335, 164, 789, 161, 120, 129), diff --git a/doc/tutorials/klondike/app/lib/step5/suit.dart b/doc/tutorials/klondike/app/lib/step5/suit.dart index d516180c9ea..797470126d2 100644 --- a/doc/tutorials/klondike/app/lib/step5/suit.dart +++ b/doc/tutorials/klondike/app/lib/step5/suit.dart @@ -1,9 +1,18 @@ import 'package:flame/sprite.dart'; import 'package:flutter/foundation.dart'; + import 'klondike_game.dart'; @immutable -class Suit { +// ignore: prefer_const_constructors_in_immutables +class Suit._( + final int value, + final String label, + double x, + double y, + double w, + double h, +) { factory Suit.fromInt(int index) { assert( index >= 0 && index <= 3, @@ -12,12 +21,7 @@ class Suit { return _singletons[index]; } - Suit._(this.value, this.label, double x, double y, double w, double h) - : sprite = klondikeSprite(x, y, w, h); - - final int value; - final String label; - final Sprite sprite; + final Sprite sprite = klondikeSprite(x, y, w, h); static final List _singletons = [ Suit._(0, '♥', 1176, 17, 172, 183), diff --git a/doc/tutorials/klondike/app/pubspec.yaml b/doc/tutorials/klondike/app/pubspec.yaml index f0bc72e496e..15a9d458bf8 100644 --- a/doc/tutorials/klondike/app/pubspec.yaml +++ b/doc/tutorials/klondike/app/pubspec.yaml @@ -5,7 +5,7 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/doc/tutorials/platformer/app/lib/actors/ember.dart b/doc/tutorials/platformer/app/lib/actors/ember.dart index 21fb146e6b2..b3c87e92558 100644 --- a/doc/tutorials/platformer/app/lib/actors/ember.dart +++ b/doc/tutorials/platformer/app/lib/actors/ember.dart @@ -9,11 +9,11 @@ import '../objects/platform_block.dart'; import '../objects/star.dart'; import 'water_enemy.dart'; -class EmberPlayer extends SpriteAnimationComponent +class EmberPlayer({ + required super.position, +}) extends SpriteAnimationComponent with KeyboardHandler, CollisionCallbacks, HasGameRef { - EmberPlayer({ - required super.position, - }) : super(size: Vector2.all(64), anchor: Anchor.center); + this : super(size: Vector2.all(64), anchor: Anchor.center); final Vector2 velocity = Vector2.zero(); final Vector2 fromAbove = Vector2(0, -1); diff --git a/doc/tutorials/platformer/app/lib/actors/water_enemy.dart b/doc/tutorials/platformer/app/lib/actors/water_enemy.dart index 1fe0b2df29d..6665f490318 100644 --- a/doc/tutorials/platformer/app/lib/actors/water_enemy.dart +++ b/doc/tutorials/platformer/app/lib/actors/water_enemy.dart @@ -4,17 +4,13 @@ import 'package:flame/effects.dart'; import '../ember_quest.dart'; -class WaterEnemy extends SpriteAnimationComponent - with HasGameRef { - final Vector2 gridPosition; - double xOffset; - +class WaterEnemy({ + required final Vector2 gridPosition, + required var double xOffset, +}) extends SpriteAnimationComponent with HasGameRef { final Vector2 velocity = Vector2.zero(); - WaterEnemy({ - required this.gridPosition, - required this.xOffset, - }) : super(size: Vector2.all(64), anchor: Anchor.bottomLeft); + this : super(size: Vector2.all(64), anchor: Anchor.bottomLeft); @override Future onLoad() async { diff --git a/doc/tutorials/platformer/app/lib/ember_quest.dart b/doc/tutorials/platformer/app/lib/ember_quest.dart index 71a0183868e..d3110dbfb06 100644 --- a/doc/tutorials/platformer/app/lib/ember_quest.dart +++ b/doc/tutorials/platformer/app/lib/ember_quest.dart @@ -11,10 +11,9 @@ import 'objects/platform_block.dart'; import 'objects/star.dart'; import 'overlays/hud.dart'; -class EmberQuestGame extends FlameGame +class EmberQuestGame() + extends FlameGame with HasCollisionDetection, HasKeyboardHandlerComponents { - EmberQuestGame(); - late EmberPlayer _ember; late double lastBlockXPosition = 0.0; late UniqueKey lastBlockKey; diff --git a/doc/tutorials/platformer/app/lib/managers/segment_manager.dart b/doc/tutorials/platformer/app/lib/managers/segment_manager.dart index e282d57c087..5a53bb6eb9d 100644 --- a/doc/tutorials/platformer/app/lib/managers/segment_manager.dart +++ b/doc/tutorials/platformer/app/lib/managers/segment_manager.dart @@ -5,13 +5,10 @@ import '../objects/ground_block.dart'; import '../objects/platform_block.dart'; import '../objects/star.dart'; -class Block { +class Block(final Vector2 gridPosition, final Type blockType) { // gridPosition position is always segment based X,Y. // 0,0 is the bottom left corner. // 10,10 is the upper right corner. - final Vector2 gridPosition; - final Type blockType; - Block(this.gridPosition, this.blockType); } final segments = [ diff --git a/doc/tutorials/platformer/app/lib/objects/ground_block.dart b/doc/tutorials/platformer/app/lib/objects/ground_block.dart index c3b514970d2..560b7dffa55 100644 --- a/doc/tutorials/platformer/app/lib/objects/ground_block.dart +++ b/doc/tutorials/platformer/app/lib/objects/ground_block.dart @@ -7,17 +7,14 @@ import 'package:material_ui/material_ui.dart'; import '../ember_quest.dart'; import '../managers/segment_manager.dart'; -class GroundBlock extends SpriteComponent with HasGameRef { - final Vector2 gridPosition; - double xOffset; - +class GroundBlock({ + required final Vector2 gridPosition, + required var double xOffset, +}) extends SpriteComponent with HasGameRef { final UniqueKey _blockKey = UniqueKey(); final Vector2 velocity = Vector2.zero(); - GroundBlock({ - required this.gridPosition, - required this.xOffset, - }) : super(size: Vector2.all(64), anchor: Anchor.bottomLeft); + this : super(size: Vector2.all(64), anchor: Anchor.bottomLeft); @override Future onLoad() async { diff --git a/doc/tutorials/platformer/app/lib/objects/platform_block.dart b/doc/tutorials/platformer/app/lib/objects/platform_block.dart index 367b1f0c3a0..ccbaac085bf 100644 --- a/doc/tutorials/platformer/app/lib/objects/platform_block.dart +++ b/doc/tutorials/platformer/app/lib/objects/platform_block.dart @@ -3,16 +3,13 @@ import 'package:flame/components.dart'; import '../ember_quest.dart'; -class PlatformBlock extends SpriteComponent with HasGameRef { - final Vector2 gridPosition; - double xOffset; - +class PlatformBlock({ + required final Vector2 gridPosition, + required var double xOffset, +}) extends SpriteComponent with HasGameRef { final Vector2 velocity = Vector2.zero(); - PlatformBlock({ - required this.gridPosition, - required this.xOffset, - }) : super(size: Vector2.all(64), anchor: Anchor.bottomLeft); + this : super(size: Vector2.all(64), anchor: Anchor.bottomLeft); @override Future onLoad() async { diff --git a/doc/tutorials/platformer/app/lib/objects/star.dart b/doc/tutorials/platformer/app/lib/objects/star.dart index 9831faf7c2c..862594b83c6 100644 --- a/doc/tutorials/platformer/app/lib/objects/star.dart +++ b/doc/tutorials/platformer/app/lib/objects/star.dart @@ -5,16 +5,13 @@ import 'package:material_ui/material_ui.dart'; import '../ember_quest.dart'; -class Star extends SpriteComponent with HasGameRef { - final Vector2 gridPosition; - double xOffset; - +class Star({ + required final Vector2 gridPosition, + required var double xOffset, +}) extends SpriteComponent with HasGameRef { final Vector2 velocity = Vector2.zero(); - Star({ - required this.gridPosition, - required this.xOffset, - }) : super(size: Vector2.all(64), anchor: Anchor.center); + this : super(size: Vector2.all(64), anchor: Anchor.center); @override Future onLoad() async { diff --git a/doc/tutorials/platformer/app/lib/overlays/game_over.dart b/doc/tutorials/platformer/app/lib/overlays/game_over.dart index 8444e6fec8e..2220bd2de82 100644 --- a/doc/tutorials/platformer/app/lib/overlays/game_over.dart +++ b/doc/tutorials/platformer/app/lib/overlays/game_over.dart @@ -2,11 +2,9 @@ import 'package:material_ui/material_ui.dart'; import '../ember_quest.dart'; -class GameOver extends StatelessWidget { +class const GameOver({required final EmberQuestGame game, super.key}) + extends StatelessWidget { // Reference to parent game. - final EmberQuestGame game; - const GameOver({required this.game, super.key}); - @override Widget build(BuildContext context) { const blackTextColor = Color.fromRGBO(0, 0, 0, 1.0); diff --git a/doc/tutorials/platformer/app/lib/overlays/heart.dart b/doc/tutorials/platformer/app/lib/overlays/heart.dart index 626d7a9aa17..6e9caae1947 100644 --- a/doc/tutorials/platformer/app/lib/overlays/heart.dart +++ b/doc/tutorials/platformer/app/lib/overlays/heart.dart @@ -2,25 +2,20 @@ import 'package:flame/components.dart'; import '../ember_quest.dart'; -enum HeartState { +enum HeartState() { available, unavailable, } -class HeartHealthComponent extends SpriteGroupComponent - with HasGameRef { - final int heartNumber; - - HeartHealthComponent({ - required this.heartNumber, - required super.position, - required super.size, - super.scale, - super.angle, - super.anchor, - super.priority, - }); - +class HeartHealthComponent({ + required final int heartNumber, + required super.position, + required super.size, + super.scale, + super.angle, + super.anchor, + super.priority, +}) extends SpriteGroupComponent with HasGameRef { @override Future onLoad() async { await super.onLoad(); diff --git a/doc/tutorials/platformer/app/lib/overlays/hud.dart b/doc/tutorials/platformer/app/lib/overlays/hud.dart index de40f6c9b2e..3e8e9dd090c 100644 --- a/doc/tutorials/platformer/app/lib/overlays/hud.dart +++ b/doc/tutorials/platformer/app/lib/overlays/hud.dart @@ -4,17 +4,15 @@ import 'package:material_ui/material_ui.dart'; import '../ember_quest.dart'; import 'heart.dart'; -class Hud extends PositionComponent with HasGameRef { - Hud({ - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority = 5, - }); - +class Hud({ + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority = 5, +}) extends PositionComponent with HasGameRef { late TextComponent _scoreTextComponent; @override @@ -53,7 +51,7 @@ class Hud extends PositionComponent with HasGameRef { ); } - return super.onLoad(); + await super.onLoad(); } @override diff --git a/doc/tutorials/platformer/app/lib/overlays/main_menu.dart b/doc/tutorials/platformer/app/lib/overlays/main_menu.dart index 315cd413e1f..11479a8aca5 100644 --- a/doc/tutorials/platformer/app/lib/overlays/main_menu.dart +++ b/doc/tutorials/platformer/app/lib/overlays/main_menu.dart @@ -2,12 +2,9 @@ import 'package:material_ui/material_ui.dart'; import '../ember_quest.dart'; -class MainMenu extends StatelessWidget { +class const MainMenu({required final EmberQuestGame game, super.key}) + extends StatelessWidget { // Reference to parent game. - final EmberQuestGame game; - - const MainMenu({required this.game, super.key}); - @override Widget build(BuildContext context) { const blackTextColor = Color.fromRGBO(0, 0, 0, 1.0); diff --git a/doc/tutorials/platformer/app/pubspec.yaml b/doc/tutorials/platformer/app/pubspec.yaml index 90e42a62e4e..bb5f3ea1d8e 100644 --- a/doc/tutorials/platformer/app/pubspec.yaml +++ b/doc/tutorials/platformer/app/pubspec.yaml @@ -5,8 +5,8 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/doc/tutorials/space_shooter/app/lib/step1/main.dart b/doc/tutorials/space_shooter/app/lib/step1/main.dart index c02e791678f..4f28854208f 100644 --- a/doc/tutorials/space_shooter/app/lib/step1/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step1/main.dart @@ -6,7 +6,7 @@ void main() { runApp(GameWidget(game: SpaceShooterGame())); } -class Player extends PositionComponent { +class Player() extends PositionComponent { static final _paint = Paint()..color = Colors.white; @override void render(Canvas canvas) { @@ -14,7 +14,7 @@ class Player extends PositionComponent { } } -class SpaceShooterGame extends FlameGame { +class SpaceShooterGame() extends FlameGame { @override Future onLoad() async { add( diff --git a/doc/tutorials/space_shooter/app/lib/step2/main.dart b/doc/tutorials/space_shooter/app/lib/step2/main.dart index a31245b25cb..a393eafb3e9 100644 --- a/doc/tutorials/space_shooter/app/lib/step2/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step2/main.dart @@ -7,7 +7,7 @@ void main() { runApp(GameWidget(game: SpaceShooterGame())); } -class SpaceShooterGame extends FlameGame with DragCallbacks { +class SpaceShooterGame() extends FlameGame with DragCallbacks { late Player player; @override @@ -22,8 +22,8 @@ class SpaceShooterGame extends FlameGame with DragCallbacks { } } -class Player extends SpriteComponent with HasGameRef { - Player() +class Player() extends SpriteComponent with HasGameRef { + this : super( size: Vector2(100, 150), anchor: Anchor.center, diff --git a/doc/tutorials/space_shooter/app/lib/step3/main.dart b/doc/tutorials/space_shooter/app/lib/step3/main.dart index d08bc59e4c2..270cb53309e 100644 --- a/doc/tutorials/space_shooter/app/lib/step3/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step3/main.dart @@ -8,7 +8,7 @@ void main() { runApp(GameWidget(game: SpaceShooterGame())); } -class SpaceShooterGame extends FlameGame with DragCallbacks { +class SpaceShooterGame() extends FlameGame with DragCallbacks { late Player player; @override @@ -35,9 +35,10 @@ class SpaceShooterGame extends FlameGame with DragCallbacks { } } -class Player extends SpriteAnimationComponent +class Player() + extends SpriteAnimationComponent with HasGameRef { - Player() + this : super( size: Vector2(100, 150), anchor: Anchor.center, diff --git a/doc/tutorials/space_shooter/app/lib/step4/main.dart b/doc/tutorials/space_shooter/app/lib/step4/main.dart index 3c37fd4b997..efcb33bc63f 100644 --- a/doc/tutorials/space_shooter/app/lib/step4/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step4/main.dart @@ -8,7 +8,7 @@ void main() { runApp(GameWidget(game: SpaceShooterGame())); } -class SpaceShooterGame extends FlameGame with DragCallbacks { +class SpaceShooterGame() extends FlameGame with DragCallbacks { late Player player; @override @@ -47,9 +47,10 @@ class SpaceShooterGame extends FlameGame with DragCallbacks { } } -class Player extends SpriteAnimationComponent +class Player() + extends SpriteAnimationComponent with HasGameRef { - Player() + this : super( size: Vector2(100, 150), anchor: Anchor.center, @@ -104,14 +105,14 @@ class Player extends SpriteAnimationComponent } } -class Bullet extends SpriteAnimationComponent - with HasGameRef { - Bullet({ - super.position, - }) : super( - size: Vector2(25, 50), - anchor: Anchor.center, - ); +class Bullet({ + super.position, +}) extends SpriteAnimationComponent with HasGameRef { + this + : super( + size: Vector2(25, 50), + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/doc/tutorials/space_shooter/app/lib/step5/main.dart b/doc/tutorials/space_shooter/app/lib/step5/main.dart index 5e4d2b4efb7..7e77e73ebdb 100644 --- a/doc/tutorials/space_shooter/app/lib/step5/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step5/main.dart @@ -9,7 +9,7 @@ void main() { runApp(GameWidget(game: SpaceShooterGame())); } -class SpaceShooterGame extends FlameGame with DragCallbacks { +class SpaceShooterGame() extends FlameGame with DragCallbacks { late Player player; @override @@ -58,9 +58,10 @@ class SpaceShooterGame extends FlameGame with DragCallbacks { } } -class Player extends SpriteAnimationComponent +class Player() + extends SpriteAnimationComponent with HasGameRef { - Player() + this : super( size: Vector2(100, 150), anchor: Anchor.center, @@ -115,14 +116,14 @@ class Player extends SpriteAnimationComponent } } -class Bullet extends SpriteAnimationComponent - with HasGameRef { - Bullet({ - super.position, - }) : super( - size: Vector2(25, 50), - anchor: Anchor.center, - ); +class Bullet({ + super.position, +}) extends SpriteAnimationComponent with HasGameRef { + this + : super( + size: Vector2(25, 50), + anchor: Anchor.center, + ); @override Future onLoad() async { @@ -150,13 +151,14 @@ class Bullet extends SpriteAnimationComponent } } -class Enemy extends SpriteAnimationComponent with HasGameRef { - Enemy({ - super.position, - }) : super( - size: Vector2.all(enemySize), - anchor: Anchor.center, - ); +class Enemy({ + super.position, +}) extends SpriteAnimationComponent with HasGameRef { + this + : super( + size: Vector2.all(enemySize), + anchor: Anchor.center, + ); static const enemySize = 50.0; diff --git a/doc/tutorials/space_shooter/app/lib/step6/main.dart b/doc/tutorials/space_shooter/app/lib/step6/main.dart index 7b9baa1929c..4d7aebb7d18 100644 --- a/doc/tutorials/space_shooter/app/lib/step6/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step6/main.dart @@ -10,7 +10,8 @@ void main() { runApp(GameWidget(game: SpaceShooterGame())); } -class SpaceShooterGame extends FlameGame +class SpaceShooterGame() + extends FlameGame with DragCallbacks, HasCollisionDetection { late Player player; @@ -60,9 +61,10 @@ class SpaceShooterGame extends FlameGame } } -class Player extends SpriteAnimationComponent +class Player() + extends SpriteAnimationComponent with HasGameRef { - Player() + this : super( size: Vector2(100, 150), anchor: Anchor.center, @@ -117,14 +119,14 @@ class Player extends SpriteAnimationComponent } } -class Bullet extends SpriteAnimationComponent - with HasGameRef { - Bullet({ - super.position, - }) : super( - size: Vector2(25, 50), - anchor: Anchor.center, - ); +class Bullet({ + super.position, +}) extends SpriteAnimationComponent with HasGameRef { + this + : super( + size: Vector2(25, 50), + anchor: Anchor.center, + ); @override Future onLoad() async { @@ -158,14 +160,15 @@ class Bullet extends SpriteAnimationComponent } } -class Enemy extends SpriteAnimationComponent +class Enemy({ + super.position, +}) extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks { - Enemy({ - super.position, - }) : super( - size: Vector2.all(enemySize), - anchor: Anchor.center, - ); + this + : super( + size: Vector2.all(enemySize), + anchor: Anchor.center, + ); static const enemySize = 50.0; @@ -211,15 +214,15 @@ class Enemy extends SpriteAnimationComponent } } -class Explosion extends SpriteAnimationComponent - with HasGameRef { - Explosion({ - super.position, - }) : super( - size: Vector2.all(150), - anchor: Anchor.center, - removeOnFinish: true, - ); +class Explosion({ + super.position, +}) extends SpriteAnimationComponent with HasGameRef { + this + : super( + size: Vector2.all(150), + anchor: Anchor.center, + removeOnFinish: true, + ); @override Future onLoad() async { diff --git a/doc/tutorials/space_shooter/app/pubspec.yaml b/doc/tutorials/space_shooter/app/pubspec.yaml index f77b8d9af29..29efa974361 100644 --- a/doc/tutorials/space_shooter/app/pubspec.yaml +++ b/doc/tutorials/space_shooter/app/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/examples/games/crystal_ball/lib/crystal_ball.dart b/examples/games/crystal_ball/lib/crystal_ball.dart index df9d74630dc..be555f7eb26 100644 --- a/examples/games/crystal_ball/lib/crystal_ball.dart +++ b/examples/games/crystal_ball/lib/crystal_ball.dart @@ -5,9 +5,7 @@ import 'package:crystal_ball/src/game/game.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class CrystalBallWidget extends StatefulWidget { - const CrystalBallWidget({super.key}); - +class const CrystalBallWidget({super.key}) extends StatefulWidget { static const String description = ''' A demonstration of how to leverage the power of Fragment Shaders in Flame. The game is a simple crystal ball that jumps around in a swampy world. @@ -19,7 +17,7 @@ and the glowing effect of the crystal ball. State createState() => _CrystalBallWidgetState(); } -class _CrystalBallWidgetState extends State { +class _CrystalBallWidgetState() extends State { // PreloadedPrograms is a simple data class that holds the preloaded late final Future preloadedPrograms = Future.wait([ diff --git a/examples/games/crystal_ball/lib/src/game/components/camera_target.dart b/examples/games/crystal_ball/lib/src/game/components/camera_target.dart index 1585a493b4e..3c1554e7017 100644 --- a/examples/games/crystal_ball/lib/src/game/components/camera_target.dart +++ b/examples/games/crystal_ball/lib/src/game/components/camera_target.dart @@ -3,7 +3,9 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flutter/animation.dart'; -class CameraTarget extends PositionComponent with HasGameRef { +class CameraTarget() + extends PositionComponent + with HasGameRef { final effectController = CurvedEffectController( 0.1, Curves.easeOut, @@ -26,16 +28,15 @@ class CameraTarget extends PositionComponent with HasGameRef { } } -class MoveCameraTarget extends Effect with EffectTarget { - MoveCameraTarget(this._to, super.controller); - +class MoveCameraTarget(final Vector2 _to, super.controller) + extends Effect + with EffectTarget { @override void onMount() { super.onMount(); _from = target.position; } - final Vector2 _to; late final Vector2 _from; @override diff --git a/examples/games/crystal_ball/lib/src/game/components/input_handler.dart b/examples/games/crystal_ball/lib/src/game/components/input_handler.dart index c8a614ed02d..ab33d2f2317 100644 --- a/examples/games/crystal_ball/lib/src/game/components/input_handler.dart +++ b/examples/games/crystal_ball/lib/src/game/components/input_handler.dart @@ -4,9 +4,10 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flutter/services.dart'; -class InputHandler extends PositionComponent +class InputHandler() + extends PositionComponent with TapCallbacks, HasGameRef { - InputHandler() + this : super( anchor: Anchor.center, size: kCameraSize, @@ -27,7 +28,7 @@ class InputHandler extends PositionComponent ), ); - return super.onLoad(); + await super.onLoad(); } @override diff --git a/examples/games/crystal_ball/lib/src/game/entities/ground.dart b/examples/games/crystal_ball/lib/src/game/entities/ground.dart index 6577aed37ce..6748a39e5d1 100644 --- a/examples/games/crystal_ball/lib/src/game/entities/ground.dart +++ b/examples/games/crystal_ball/lib/src/game/entities/ground.dart @@ -3,17 +3,18 @@ import 'package:crystal_ball/src/game/game.dart'; import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; -class Ground extends Component { - Ground() : super(children: [Rectangle(kPlayerSize.y / 2)]) { +class Ground() extends Component { + this : super(children: [Rectangle(kPlayerSize.y / 2)]) { rectangle = children.first as Rectangle; } late final Rectangle rectangle; } -class Rectangle extends PositionComponent +class Rectangle(double y) + extends PositionComponent with CollisionCallbacks, ParentIsA, HasGameRef { - Rectangle(double y) + this : super( anchor: Anchor.topCenter, position: Vector2(0, y), diff --git a/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart b/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart index 02f499cd8cf..5d4271e4c03 100644 --- a/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart +++ b/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart @@ -11,20 +11,21 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flutter/animation.dart'; -class TheBall extends PositionComponent +class TheBall({ + required Vector2 super.position, +}) extends PositionComponent with CollisionCallbacks, HasGameRef { - TheBall({ - required Vector2 super.position, - }) : super( - anchor: Anchor.center, - priority: 100000, - children: [ - CircleHitbox( - radius: kPlayerRadius, - anchor: Anchor.center, - ), - ], - ); + this + : super( + anchor: Anchor.center, + priority: 100000, + children: [ + CircleHitbox( + radius: kPlayerRadius, + anchor: Anchor.center, + ), + ], + ); final Vector2 velocity = Vector2.zero(); diff --git a/examples/games/crystal_ball/lib/src/game/game.dart b/examples/games/crystal_ball/lib/src/game/game.dart index 3dd60129a4b..6ae0703fcfd 100644 --- a/examples/games/crystal_ball/lib/src/game/game.dart +++ b/examples/games/crystal_ball/lib/src/game/game.dart @@ -15,17 +15,18 @@ import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame/post_process.dart'; -class CrystalBallGame extends FlameGame +class CrystalBallGame({ + required final PreloadedPrograms preloadedPrograms, +}) extends FlameGame with HasKeyboardHandlerComponents, HasCollisionDetection { - CrystalBallGame({ - required this.preloadedPrograms, - }) : super( - camera: CameraComponent.withFixedResolution( - width: kCameraSize.x, - height: kCameraSize.y, - ), - world: CrystalBallGameWorld(), - ) { + this + : super( + camera: CameraComponent.withFixedResolution( + width: kCameraSize.x, + height: kCameraSize.y, + ), + world: CrystalBallGameWorld(), + ) { camera.postProcess = PostProcessGroup( postProcesses: [ PostProcessSequentialGroup( @@ -59,15 +60,14 @@ class CrystalBallGame extends FlameGame return super.onLoad(); } - final PreloadedPrograms preloadedPrograms; late final InputHandler inputHandler; } -class CrystalBallGameWorld extends World { - CrystalBallGameWorld({ - super.children, - super.key, - }) { +class CrystalBallGameWorld({ + super.children, + super.key, +}) extends World { + this { addAll([ BallGlow(), theBall = TheBall(position: Vector2.zero()), diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart b/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart index 4f53aa6814c..bd4843b8177 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart @@ -6,18 +6,18 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/post_process.dart'; -class BallGlow extends PostProcessComponent +class BallGlow({ + super.position, + super.scale, + super.angle, + super.nativeAngle, + super.anchor = Anchor.center, + super.children, + super.priority, + super.key, +}) extends PostProcessComponent with HasGameRef { - BallGlow({ - super.position, - super.scale, - super.angle, - super.nativeAngle, - super.anchor = Anchor.center, - super.children, - super.priority, - super.key, - }) : super(postProcess: BallGlowPostProcess()); + this : super(postProcess: BallGlowPostProcess()); @override Future onLoad() { @@ -40,7 +40,7 @@ class BallGlow extends PostProcessComponent /// /// Also, its shader is not preloaded in the game, but rather loaded /// when the post process is loaded. -class BallGlowPostProcess extends PostProcess { +class BallGlowPostProcess() extends PostProcess { late CrystalBallGameWorld world; late final FragmentProgram fragmentProgram; diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart b/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart index f039058181b..f46223904b7 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart @@ -6,16 +6,11 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/post_process.dart'; -class FireflyPostProcess extends PostProcess { - FireflyPostProcess({ - required this.fragmentProgram, - required this.world, - super.pixelRatio, - }); - - final FragmentProgram fragmentProgram; - final CrystalBallGameWorld world; - +class FireflyPostProcess({ + required final FragmentProgram fragmentProgram, + required final CrystalBallGameWorld world, + super.pixelRatio, +}) extends PostProcess { late final FragmentShader shader = fragmentProgram.fragmentShader(); double time = 0; diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart b/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart index ba7a7385303..bac46f74985 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart @@ -6,16 +6,11 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/post_process.dart'; -class ForegroundFogPostProcess extends PostProcess { - ForegroundFogPostProcess({ - required this.fragmentProgram, - required this.world, - super.pixelRatio, - }); - - final FragmentProgram fragmentProgram; - final CrystalBallGameWorld world; - +class ForegroundFogPostProcess({ + required final FragmentProgram fragmentProgram, + required final CrystalBallGameWorld world, + super.pixelRatio, +}) extends PostProcess { late final FragmentShader shader = fragmentProgram.fragmentShader(); double time = 0; diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/water.dart b/examples/games/crystal_ball/lib/src/game/post_processes/water.dart index 57f37934482..97046e113ea 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/water.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/water.dart @@ -4,16 +4,11 @@ import 'package:crystal_ball/src/game/game.dart'; import 'package:flame/components.dart'; import 'package:flame/post_process.dart'; -class WaterPostProcess extends PostProcess { - WaterPostProcess({ - required this.fragmentProgram, - required this.world, - super.pixelRatio, - }); - - final FragmentProgram fragmentProgram; - final CrystalBallGameWorld world; - +class WaterPostProcess({ + required final FragmentProgram fragmentProgram, + required final CrystalBallGameWorld world, + super.pixelRatio, +}) extends PostProcess { late final FragmentShader shader = fragmentProgram.fragmentShader(); double time = 0; diff --git a/examples/games/crystal_ball/pubspec.yaml b/examples/games/crystal_ball/pubspec.yaml index bf94f04de9b..494e3648041 100644 --- a/examples/games/crystal_ball/pubspec.yaml +++ b/examples/games/crystal_ball/pubspec.yaml @@ -5,8 +5,8 @@ publish_to: 'none' version: "0.1.0" environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/examples/games/padracing/lib/ball.dart b/examples/games/padracing/lib/ball.dart index 50ea9c1a680..619380f41c7 100644 --- a/examples/games/padracing/lib/ball.dart +++ b/examples/games/padracing/lib/ball.dart @@ -9,20 +9,16 @@ import 'package:padracing/game_colors.dart'; import 'package:padracing/padracing_game.dart'; import 'package:padracing/wall.dart'; -class Ball extends BodyComponent with ContactCallbacks { - final double radius; - final Vector2 initialPosition; - final double rotation; - final bool isMovable; +class Ball({ + required final Vector2 initialPosition, + final double radius = 80.0, + final double rotation = 1.0, + final bool isMovable = true, +}) extends BodyComponent with ContactCallbacks { final rng = Random(); late final Paint _shaderPaint; - Ball({ - required this.initialPosition, - this.radius = 80.0, - this.rotation = 1.0, - this.isMovable = true, - }) : super(priority: 3); + this : super(priority: 3); @override Future onLoad() async { diff --git a/examples/games/padracing/lib/car.dart b/examples/games/padracing/lib/car.dart index 3705561fd77..55424d4a057 100644 --- a/examples/games/padracing/lib/car.dart +++ b/examples/games/padracing/lib/car.dart @@ -3,14 +3,17 @@ import 'dart:ui'; import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame_forge2d/flame_forge2d.dart' hide World; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/game_colors.dart'; import 'package:padracing/lap_line.dart'; import 'package:padracing/padracing_game.dart'; import 'package:padracing/tire.dart'; -class Car extends BodyComponent { - Car({required this.playerNumber, required this.cameraComponent}) +class Car({ + required final int playerNumber, + required final CameraComponent cameraComponent, +}) extends BodyComponent { + this : super( priority: 3, paint: Paint()..color = colors[playerNumber], @@ -23,9 +26,7 @@ class Car extends BodyComponent { late final List tires; final ValueNotifier lapNotifier = ValueNotifier(1); - final int playerNumber; final Set passedStartControl = {}; - final CameraComponent cameraComponent; late final Image _image; final size = const Size(6, 10); final scale = 10.0; diff --git a/examples/games/padracing/lib/game_colors.dart b/examples/games/padracing/lib/game_colors.dart index 1e6eb2ce3fe..6ee5bb3cf1e 100644 --- a/examples/games/padracing/lib/game_colors.dart +++ b/examples/games/padracing/lib/game_colors.dart @@ -1,7 +1,7 @@ import 'package:flame/extensions.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; -enum GameColors { +enum GameColors() { green, blue, } diff --git a/examples/games/padracing/lib/game_over.dart b/examples/games/padracing/lib/game_over.dart index b22d4ecd159..4d8c2777f5a 100644 --- a/examples/games/padracing/lib/game_over.dart +++ b/examples/games/padracing/lib/game_over.dart @@ -1,12 +1,9 @@ -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/menu_card.dart'; import 'package:padracing/padracing_game.dart'; -class GameOver extends StatelessWidget { - const GameOver(this.game, {super.key}); - - final PadRacingGame game; - +class const GameOver(final PadRacingGame game, {super.key}) + extends StatelessWidget { @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; diff --git a/examples/games/padracing/lib/lap_line.dart b/examples/games/padracing/lib/lap_line.dart index 83f89cad338..4fa78f8ffba 100644 --- a/examples/games/padracing/lib/lap_line.dart +++ b/examples/games/padracing/lib/lap_line.dart @@ -4,19 +4,19 @@ import 'dart:ui'; import 'package:flame/extensions.dart'; import 'package:flame/palette.dart'; import 'package:flame_forge2d/flame_forge2d.dart' hide World; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/car.dart'; import 'package:padracing/game_colors.dart'; -class LapLine extends BodyComponent with ContactCallbacks { - LapLine(this.id, this.initialPosition, this.size, {required this.isFinish}) - : super(priority: 1); +class LapLine( + final int id, + final Vector2 initialPosition, + final Vector2 size, { + required final bool isFinish, +}) extends BodyComponent with ContactCallbacks { + this : super(priority: 1); - final int id; - final bool isFinish; - final Vector2 initialPosition; - final Vector2 size; late final Rect rect = size.toRect(); Image? _finishOverlay; diff --git a/examples/games/padracing/lib/lap_text.dart b/examples/games/padracing/lib/lap_text.dart index f07509a117a..1b9bc2d6b94 100644 --- a/examples/games/padracing/lib/lap_text.dart +++ b/examples/games/padracing/lib/lap_text.dart @@ -1,15 +1,15 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/car.dart'; import 'package:padracing/padracing_game.dart'; -class LapText extends PositionComponent with HasGameRef { - LapText({required this.car, required Vector2 position}) - : super(position: position); +class LapText({required final Car car, required Vector2 position}) + extends PositionComponent + with HasGameRef { + this : super(position: position); - final Car car; late final ValueNotifier lapNotifier = car.lapNotifier; late final TextComponent _timePassedComponent; diff --git a/examples/games/padracing/lib/main.dart b/examples/games/padracing/lib/main.dart index ea2d7897fb7..b8618817c6d 100644 --- a/examples/games/padracing/lib/main.dart +++ b/examples/games/padracing/lib/main.dart @@ -1,4 +1,4 @@ -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/padracing_widget.dart'; void main() { diff --git a/examples/games/padracing/lib/menu.dart b/examples/games/padracing/lib/menu.dart index f7a4f2d4257..66d59213d84 100644 --- a/examples/games/padracing/lib/menu.dart +++ b/examples/games/padracing/lib/menu.dart @@ -1,15 +1,12 @@ import 'package:flutter/gestures.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/game_colors.dart'; import 'package:padracing/menu_card.dart'; import 'package:padracing/padracing_game.dart'; import 'package:url_launcher/url_launcher.dart'; -class Menu extends StatelessWidget { - const Menu(this.game, {super.key}); - - final PadRacingGame game; - +class const Menu(final PadRacingGame game, {super.key}) + extends StatelessWidget { @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; diff --git a/examples/games/padracing/lib/menu_card.dart b/examples/games/padracing/lib/menu_card.dart index e8405c69e04..ddc3241399a 100644 --- a/examples/games/padracing/lib/menu_card.dart +++ b/examples/games/padracing/lib/menu_card.dart @@ -1,12 +1,9 @@ -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/game_colors.dart'; -class MenuCard extends StatelessWidget { - const MenuCard({required this.children, super.key}); - - final List children; - +class const MenuCard({required final List children, super.key}) + extends StatelessWidget { @override Widget build(BuildContext context) { return Card( diff --git a/examples/games/padracing/lib/padracing_game.dart b/examples/games/padracing/lib/padracing_game.dart index 0ed8203fde6..a6e24e9b45c 100644 --- a/examples/games/padracing/lib/padracing_game.dart +++ b/examples/games/padracing/lib/padracing_game.dart @@ -8,7 +8,7 @@ import 'package:flame/extensions.dart'; import 'package:flame/input.dart'; import 'package:flame_forge2d/flame_forge2d.dart' hide World; import 'package:flutter/services.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/ball.dart'; import 'package:padracing/car.dart'; import 'package:padracing/game_colors.dart'; @@ -31,7 +31,7 @@ final List> playersKeys = [ }, ]; -class PadRacingGame extends Forge2DGame with KeyboardEvents { +class PadRacingGame() extends Forge2DGame with KeyboardEvents { static const String description = ''' This is an example game that uses Forge2D to handle the physics. In this game you should finish 3 laps in as little time as possible, it can @@ -41,7 +41,7 @@ class PadRacingGame extends Forge2DGame with KeyboardEvents { // The game replaces the built-in camera with its own cameras below, which // apply the scaling through their zoom, so one meter is one world unit here. - PadRacingGame() : super(gravity: Vector2.zero(), metersToPixels: 1); + this : super(gravity: Vector2.zero(), metersToPixels: 1); @override Color backgroundColor() => Colors.black; diff --git a/examples/games/padracing/lib/padracing_widget.dart b/examples/games/padracing/lib/padracing_widget.dart index 0bbff35a67e..b521737f0dc 100644 --- a/examples/games/padracing/lib/padracing_widget.dart +++ b/examples/games/padracing/lib/padracing_widget.dart @@ -1,13 +1,11 @@ import 'package:flame/game.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/game_over.dart'; import 'package:padracing/menu.dart'; import 'package:padracing/padracing_game.dart'; -class PadracingWidget extends StatelessWidget { - const PadracingWidget({super.key}); - +class const PadracingWidget({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { final theme = ThemeData( diff --git a/examples/games/padracing/lib/tire.dart b/examples/games/padracing/lib/tire.dart index fa2dd0ed354..6a4116df2ac 100644 --- a/examples/games/padracing/lib/tire.dart +++ b/examples/games/padracing/lib/tire.dart @@ -1,32 +1,32 @@ import 'package:flame/palette.dart'; import 'package:flame_forge2d/flame_forge2d.dart' hide World; import 'package:flutter/services.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:padracing/car.dart'; import 'package:padracing/padracing_game.dart'; import 'package:padracing/trail.dart'; -class Tire extends BodyComponent { - Tire({ - required this.car, - required this.pressedKeys, - required this.isFrontTire, - required this.isLeftTire, - this.isTurnableTire = false, - }) : super( - paint: Paint() - ..color = car.paint.color - ..strokeWidth = 0.2 - ..style = PaintingStyle.stroke, - priority: 2, - ); +class Tire({ + required final Car car, + required final Set pressedKeys, + required final bool isFrontTire, + required final bool isLeftTire, + final bool isTurnableTire = false, +}) extends BodyComponent { + this + : super( + paint: Paint() + ..color = car.paint.color + ..strokeWidth = 0.2 + ..style = PaintingStyle.stroke, + priority: 2, + ); static const double _backTireMaxDriveForce = 300.0; static const double _frontTireMaxDriveForce = 600.0; static const double _backTireMaxLateralImpulse = 8.5; static const double _frontTireMaxLateralImpulse = 7.5; - final Car car; final size = Vector2(0.5, 1.25); late final RRect _renderRect = RRect.fromLTRBR( -size.x, @@ -36,8 +36,6 @@ class Tire extends BodyComponent { const Radius.circular(0.3), ); - final Set pressedKeys; - late final double _maxDriveForce = isFrontTire ? _frontTireMaxDriveForce : _backTireMaxDriveForce; @@ -52,10 +50,6 @@ class Tire extends BodyComponent { final double _maxBackwardSpeed = -40.0; late final RevoluteJoint joint; - final bool isTurnableTire; - final bool isFrontTire; - final bool isLeftTire; - final double _lockAngle = 0.6; final double _turnSpeedPerSecond = 4; diff --git a/examples/games/padracing/lib/trail.dart b/examples/games/padracing/lib/trail.dart index 9492842f75b..d7e66e21a20 100644 --- a/examples/games/padracing/lib/trail.dart +++ b/examples/games/padracing/lib/trail.dart @@ -5,14 +5,11 @@ import 'package:flame/components.dart'; import 'package:padracing/car.dart'; import 'package:padracing/tire.dart'; -class Trail extends Component with HasPaint { - Trail({ - required this.car, - required this.tire, - }) : super(priority: 1); - - final Car car; - final Tire tire; +class Trail({ + required final Car car, + required final Tire tire, +}) extends Component with HasPaint { + this : super(priority: 1); final trail = []; final _trailLength = 30; diff --git a/examples/games/padracing/lib/wall.dart b/examples/games/padracing/lib/wall.dart index 2ed7703cae4..6ff1400dc34 100644 --- a/examples/games/padracing/lib/wall.dart +++ b/examples/games/padracing/lib/wall.dart @@ -32,11 +32,9 @@ List createWalls(Vector2 size) { ]; } -class Wall extends BodyComponent { - Wall(this._position, this.size) : super(priority: 3); - - final Vector2 _position; - final Vector2 size; +class Wall(final Vector2 _position, final Vector2 size) + extends BodyComponent { + this : super(priority: 3); final Random rng = Random(); late final Image _image; diff --git a/examples/games/padracing/pubspec.yaml b/examples/games/padracing/pubspec.yaml index 07f2831e6a7..95fe1b3ebbc 100644 --- a/examples/games/padracing/pubspec.yaml +++ b/examples/games/padracing/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: collection: ^1.17.1 diff --git a/examples/games/rogue_shooter/lib/components/bullet_component.dart b/examples/games/rogue_shooter/lib/components/bullet_component.dart index d1eb44476d8..05b2e8c13b9 100644 --- a/examples/games/rogue_shooter/lib/components/bullet_component.dart +++ b/examples/games/rogue_shooter/lib/components/bullet_component.dart @@ -2,14 +2,14 @@ import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:rogue_shooter/components/enemy_component.dart'; -class BulletComponent extends SpriteAnimationComponent +class BulletComponent({required super.position, super.angle}) + extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks { static const speed = 500.0; late final Vector2 velocity; final Vector2 deltaPosition = Vector2.zero(); - BulletComponent({required super.position, super.angle}) - : super(size: Vector2(10, 20), anchor: Anchor.center); + this : super(size: Vector2(10, 20), anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/games/rogue_shooter/lib/components/enemy_component.dart b/examples/games/rogue_shooter/lib/components/enemy_component.dart index 0a42e8ed307..3060fb7c310 100644 --- a/examples/games/rogue_shooter/lib/components/enemy_component.dart +++ b/examples/games/rogue_shooter/lib/components/enemy_component.dart @@ -3,13 +3,13 @@ import 'package:flame/components.dart'; import 'package:rogue_shooter/components/explosion_component.dart'; import 'package:rogue_shooter/rogue_shooter_game.dart'; -class EnemyComponent extends SpriteAnimationComponent +class EnemyComponent({required super.position}) + extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks { static const speed = 150; static final Vector2 initialSize = Vector2.all(25); - EnemyComponent({required super.position}) - : super(size: initialSize, anchor: Anchor.center); + this : super(size: initialSize, anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/games/rogue_shooter/lib/components/enemy_creator.dart b/examples/games/rogue_shooter/lib/components/enemy_creator.dart index b5f4d1855a8..1b3f8e7f970 100644 --- a/examples/games/rogue_shooter/lib/components/enemy_creator.dart +++ b/examples/games/rogue_shooter/lib/components/enemy_creator.dart @@ -4,11 +4,11 @@ import 'package:flame/components.dart'; import 'package:rogue_shooter/components/enemy_component.dart'; import 'package:rogue_shooter/rogue_shooter_game.dart'; -class EnemyCreator extends TimerComponent with HasGameRef { +class EnemyCreator() extends TimerComponent with HasGameRef { final Random random = Random(); final _halfWidth = EnemyComponent.initialSize.x / 2; - EnemyCreator() : super(period: 0.05, repeat: true) { + this : super(period: 0.05, repeat: true) { timer.onTick = _spawn; } diff --git a/examples/games/rogue_shooter/lib/components/explosion_component.dart b/examples/games/rogue_shooter/lib/components/explosion_component.dart index f0fa5239fce..a09d773bd54 100644 --- a/examples/games/rogue_shooter/lib/components/explosion_component.dart +++ b/examples/games/rogue_shooter/lib/components/explosion_component.dart @@ -1,7 +1,9 @@ import 'package:flame/components.dart'; -class ExplosionComponent extends SpriteAnimationComponent with HasGameRef { - ExplosionComponent({super.position}) +class ExplosionComponent({super.position}) + extends SpriteAnimationComponent + with HasGameRef { + this : super( size: Vector2.all(50), anchor: Anchor.center, diff --git a/examples/games/rogue_shooter/lib/components/player_component.dart b/examples/games/rogue_shooter/lib/components/player_component.dart index 2308e5ac594..84353906f46 100644 --- a/examples/games/rogue_shooter/lib/components/player_component.dart +++ b/examples/games/rogue_shooter/lib/components/player_component.dart @@ -5,11 +5,12 @@ import 'package:rogue_shooter/components/enemy_component.dart'; import 'package:rogue_shooter/components/explosion_component.dart'; import 'package:rogue_shooter/rogue_shooter_game.dart'; -class PlayerComponent extends SpriteAnimationComponent +class PlayerComponent() + extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks { late TimerComponent bulletCreator; - PlayerComponent() : super(size: Vector2(50, 75), anchor: Anchor.center); + this : super(size: Vector2(50, 75), anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/games/rogue_shooter/lib/components/star_background_creator.dart b/examples/games/rogue_shooter/lib/components/star_background_creator.dart index 122973cddc2..0bd59077d76 100644 --- a/examples/games/rogue_shooter/lib/components/star_background_creator.dart +++ b/examples/games/rogue_shooter/lib/components/star_background_creator.dart @@ -5,15 +5,14 @@ import 'package:flame/sprite.dart'; import 'package:rogue_shooter/components/star_component.dart'; import 'package:rogue_shooter/rogue_shooter_game.dart'; -class StarBackGroundCreator extends Component +class StarBackGroundCreator() + extends Component with HasGameRef { final gapSize = 12; late final SpriteSheet spriteSheet; Random random = Random(); - StarBackGroundCreator(); - @override Future onLoad() async { spriteSheet = SpriteSheet.fromColumnsAndRows( diff --git a/examples/games/rogue_shooter/lib/components/star_component.dart b/examples/games/rogue_shooter/lib/components/star_component.dart index 03625257442..eb47fc63d3c 100644 --- a/examples/games/rogue_shooter/lib/components/star_component.dart +++ b/examples/games/rogue_shooter/lib/components/star_component.dart @@ -1,10 +1,11 @@ import 'package:flame/components.dart'; -class StarComponent extends SpriteAnimationComponent with HasGameRef { +class StarComponent({super.animation, super.position}) + extends SpriteAnimationComponent + with HasGameRef { static const speed = 10; - StarComponent({super.animation, super.position}) - : super(size: Vector2.all(20)); + this : super(size: Vector2.all(20)); @override void update(double dt) { diff --git a/examples/games/rogue_shooter/lib/rogue_shooter_game.dart b/examples/games/rogue_shooter/lib/rogue_shooter_game.dart index 2ea97b5a461..9554d339095 100644 --- a/examples/games/rogue_shooter/lib/rogue_shooter_game.dart +++ b/examples/games/rogue_shooter/lib/rogue_shooter_game.dart @@ -6,7 +6,8 @@ import 'package:rogue_shooter/components/enemy_creator.dart'; import 'package:rogue_shooter/components/player_component.dart'; import 'package:rogue_shooter/components/star_background_creator.dart'; -class RogueShooterGame extends FlameGame +class RogueShooterGame() + extends FlameGame with DragCallbacks, HasCollisionDetection, @@ -157,8 +158,10 @@ class RogueShooterGame extends FlameGame } } -class BatchGroup extends PositionComponent with HasAutoBatchedChildren { - BatchGroup({super.priority, bool batchingEnabled = false}) { +class BatchGroup({super.priority, bool batchingEnabled = false}) + extends PositionComponent + with HasAutoBatchedChildren { + this { this.batchingEnabled = batchingEnabled; } } diff --git a/examples/games/rogue_shooter/lib/rogue_shooter_widget.dart b/examples/games/rogue_shooter/lib/rogue_shooter_widget.dart index b9adbade2ac..23e5e34c76b 100644 --- a/examples/games/rogue_shooter/lib/rogue_shooter_widget.dart +++ b/examples/games/rogue_shooter/lib/rogue_shooter_widget.dart @@ -2,9 +2,7 @@ import 'package:flame/game.dart'; import 'package:flutter/widgets.dart'; import 'package:rogue_shooter/rogue_shooter_game.dart'; -class RogueShooterWidget extends StatelessWidget { - const RogueShooterWidget({super.key}); - +class const RogueShooterWidget({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return GameWidget( diff --git a/examples/games/rogue_shooter/pubspec.yaml b/examples/games/rogue_shooter/pubspec.yaml index 47f3ac98116..f257b27c34e 100644 --- a/examples/games/rogue_shooter/pubspec.yaml +++ b/examples/games/rogue_shooter/pubspec.yaml @@ -7,8 +7,8 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/examples/games/trex/lib/background/cloud.dart b/examples/games/trex/lib/background/cloud.dart index 5515eadd1dc..c48e843fd8c 100644 --- a/examples/games/trex/lib/background/cloud.dart +++ b/examples/games/trex/lib/background/cloud.dart @@ -3,9 +3,10 @@ import 'package:flame/extensions.dart'; import 'package:trex_game/background/cloud_manager.dart'; import 'package:trex_game/trex_game.dart'; -class Cloud extends SpriteComponent +class Cloud({required Vector2 position}) + extends SpriteComponent with ParentIsA, HasGameRef { - Cloud({required Vector2 position}) + this : super( position: position, size: initialSize, diff --git a/examples/games/trex/lib/background/cloud_manager.dart b/examples/games/trex/lib/background/cloud_manager.dart index 75b648dc49a..b82478ef24b 100644 --- a/examples/games/trex/lib/background/cloud_manager.dart +++ b/examples/games/trex/lib/background/cloud_manager.dart @@ -3,7 +3,7 @@ import 'package:flame/extensions.dart'; import 'package:trex_game/background/cloud.dart'; import 'package:trex_game/trex_game.dart'; -class CloudManager extends PositionComponent with HasGameRef { +class CloudManager() extends PositionComponent with HasGameRef { final double cloudFrequency = 0.5; final int maxClouds = 20; final double bgCloudSpeed = 0.2; diff --git a/examples/games/trex/lib/background/horizon.dart b/examples/games/trex/lib/background/horizon.dart index ed93dc34588..e9da915fbf8 100644 --- a/examples/games/trex/lib/background/horizon.dart +++ b/examples/games/trex/lib/background/horizon.dart @@ -7,9 +7,7 @@ import 'package:trex_game/background/cloud_manager.dart'; import 'package:trex_game/obstacle/obstacle_manager.dart'; import 'package:trex_game/trex_game.dart'; -class Horizon extends PositionComponent with HasGameRef { - Horizon() : super(); - +class Horizon() extends PositionComponent with HasGameRef { static final Vector2 lineSize = Vector2(1200, 24); final Queue groundLayers = Queue(); late final CloudManager cloudManager = CloudManager(); diff --git a/examples/games/trex/lib/game_over.dart b/examples/games/trex/lib/game_over.dart index e60e77dba17..c7b43e81505 100644 --- a/examples/games/trex/lib/game_over.dart +++ b/examples/games/trex/lib/game_over.dart @@ -3,7 +3,7 @@ import 'dart:ui'; import 'package:flame/components.dart'; import 'package:trex_game/trex_game.dart'; -class GameOverPanel extends Component { +class GameOverPanel() extends Component { bool visible = false; @override @@ -20,8 +20,8 @@ class GameOverPanel extends Component { } } -class GameOverText extends SpriteComponent with HasGameRef { - GameOverText() : super(size: Vector2(382, 25), anchor: Anchor.center); +class GameOverText() extends SpriteComponent with HasGameRef { + this : super(size: Vector2(382, 25), anchor: Anchor.center); @override Future onLoad() async { @@ -40,8 +40,8 @@ class GameOverText extends SpriteComponent with HasGameRef { } } -class GameOverRestart extends SpriteComponent with HasGameRef { - GameOverRestart() : super(size: Vector2(72, 64), anchor: Anchor.center); +class GameOverRestart() extends SpriteComponent with HasGameRef { + this : super(size: Vector2(72, 64), anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/games/trex/lib/obstacle/obstacle.dart b/examples/games/trex/lib/obstacle/obstacle.dart index 3e02c493ad7..f2d4424b307 100644 --- a/examples/games/trex/lib/obstacle/obstacle.dart +++ b/examples/games/trex/lib/obstacle/obstacle.dart @@ -3,20 +3,17 @@ import 'package:flame/extensions.dart'; import 'package:trex_game/obstacle/obstacle_type.dart'; import 'package:trex_game/trex_game.dart'; -class Obstacle extends SpriteComponent with HasGameRef { - Obstacle({ - required this.settings, - required this.groupIndex, - }) : super(size: settings.size); +class Obstacle({ + required final ObstacleTypeSettings settings, + required final int groupIndex, +}) extends SpriteComponent with HasGameRef { + this : super(size: settings.size); final double _gapCoefficient = 0.6; final double _maxGapCoefficient = 1.5; bool followingObstacleCreated = false; late double gap; - final ObstacleTypeSettings settings; - final int groupIndex; - bool get isVisible => (x + width) > 0; @override diff --git a/examples/games/trex/lib/obstacle/obstacle_manager.dart b/examples/games/trex/lib/obstacle/obstacle_manager.dart index a0c0b57d57f..adce3be5054 100644 --- a/examples/games/trex/lib/obstacle/obstacle_manager.dart +++ b/examples/games/trex/lib/obstacle/obstacle_manager.dart @@ -6,9 +6,7 @@ import 'package:trex_game/obstacle/obstacle.dart'; import 'package:trex_game/obstacle/obstacle_type.dart'; import 'package:trex_game/trex_game.dart'; -class ObstacleManager extends Component with HasGameRef { - ObstacleManager(); - +class ObstacleManager() extends Component with HasGameRef { ListQueue history = ListQueue(); static const int maxObstacleDuplication = 2; diff --git a/examples/games/trex/lib/obstacle/obstacle_type.dart b/examples/games/trex/lib/obstacle/obstacle_type.dart index db8414fc320..50c293d5c0e 100644 --- a/examples/games/trex/lib/obstacle/obstacle_type.dart +++ b/examples/games/trex/lib/obstacle/obstacle_type.dart @@ -1,45 +1,30 @@ -// ignore_for_file: unused_element, unused_element_parameter +// ignore_for_file: unused_element_parameter import 'dart:ui'; import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; -enum ObstacleType { +enum ObstacleType() { cactusSmall, cactusLarge, } -class ObstacleTypeSettings { - const ObstacleTypeSettings._internal( - this.type, { - required this.size, - required this.y, - required this.allowedAt, - required this.multipleAt, - required this.minGap, - required this.minSpeed, - required this.generateHitboxes, - this.numFrames, - this.frameRate, - this.speedOffset, - }); - - final ObstacleType type; - final Vector2 size; - final double y; - final int allowedAt; - final int multipleAt; - final double minGap; - final double minSpeed; - final int? numFrames; - final double? frameRate; - final double? speedOffset; - +class const ObstacleTypeSettings._internal( + final ObstacleType type, { + required final Vector2 size, + required final double y, + required final int allowedAt, + required final int multipleAt, + required final double minGap, + required final double minSpeed, + required final List Function() generateHitboxes, + final int? numFrames, + final double? frameRate, + final double? speedOffset, +}) { static const maxGroupSize = 3.0; - final List Function() generateHitboxes; - static final cactusSmall = ObstacleTypeSettings._internal( ObstacleType.cactusSmall, size: Vector2(34.0, 70.0), diff --git a/examples/games/trex/lib/player.dart b/examples/games/trex/lib/player.dart index 471f710fc1e..85838525ad5 100644 --- a/examples/games/trex/lib/player.dart +++ b/examples/games/trex/lib/player.dart @@ -2,11 +2,17 @@ import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:trex_game/trex_game.dart'; -enum PlayerState { crashed, jumping, running, waiting } +enum PlayerState() { + crashed, + jumping, + running, + waiting, +} -class Player extends SpriteAnimationGroupComponent +class Player() + extends SpriteAnimationGroupComponent with HasGameRef, CollisionCallbacks { - Player() : super(size: Vector2(90, 88)); + this : super(size: Vector2(90, 88)); final double gravity = 0.85; diff --git a/examples/games/trex/lib/trex_game.dart b/examples/games/trex/lib/trex_game.dart index b341ecbda9a..da371855ce3 100644 --- a/examples/games/trex/lib/trex_game.dart +++ b/examples/games/trex/lib/trex_game.dart @@ -13,9 +13,14 @@ import 'package:trex_game/background/horizon.dart'; import 'package:trex_game/game_over.dart'; import 'package:trex_game/player.dart'; -enum GameState { playing, intro, gameOver } +enum GameState() { + playing, + intro, + gameOver, +} -class TRexGame extends FlameGame +class TRexGame() + extends FlameGame with KeyboardEvents, TapCallbacks, HasCollisionDetection { static const String description = ''' A game similar to the game in chrome that you get to play while offline. diff --git a/examples/games/trex/lib/trex_widget.dart b/examples/games/trex/lib/trex_widget.dart index c45bac213fe..14170462186 100644 --- a/examples/games/trex/lib/trex_widget.dart +++ b/examples/games/trex/lib/trex_widget.dart @@ -1,10 +1,8 @@ import 'package:flame/game.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Gradient; +import 'package:material_ui/material_ui.dart' hide Gradient, Image; import 'package:trex_game/trex_game.dart'; -class TRexWidget extends StatelessWidget { - const TRexWidget({super.key}); - +class const TRexWidget({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( diff --git a/examples/games/trex/pubspec.yaml b/examples/games/trex/pubspec.yaml index e512de07eea..c0ca02659cf 100644 --- a/examples/games/trex/pubspec.yaml +++ b/examples/games/trex/pubspec.yaml @@ -7,8 +7,8 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.16.0 diff --git a/examples/lib/commons/ember.dart b/examples/lib/commons/ember.dart index 220dd4417fd..e121a76749e 100644 --- a/examples/lib/commons/ember.dart +++ b/examples/lib/commons/ember.dart @@ -2,9 +2,13 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:meta/meta.dart'; -class Ember extends SpriteAnimationComponent - with HasGameRef { - Ember({super.position, Vector2? size, super.priority, super.key}) +class Ember({ + super.position, + Vector2? size, + super.priority, + super.key, +}) extends SpriteAnimationComponent with HasGameRef { + this : super( size: size ?? Vector2.all(50), anchor: Anchor.center, diff --git a/examples/lib/commons/example_app.dart b/examples/lib/commons/example_app.dart index 43963305f40..dbbcd240363 100644 --- a/examples/lib/commons/example_app.dart +++ b/examples/lib/commons/example_app.dart @@ -3,11 +3,8 @@ import 'package:material_ui/material_ui.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:widgetbook/widgetbook.dart'; -class ExampleApp extends StatelessWidget { - const ExampleApp({required this.child, super.key}); - - final Widget child; - +class const ExampleApp({required final Widget child, super.key}) + extends StatelessWidget { @override Widget build(BuildContext context) { final useCase = WidgetbookState.of(context).useCase; @@ -28,11 +25,7 @@ class ExampleApp extends StatelessWidget { } } -class _ExampleBar extends StatelessWidget { - const _ExampleBar(this.useCase); - - final ExampleUseCase useCase; - +class const _ExampleBar(final ExampleUseCase useCase) extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( @@ -67,11 +60,7 @@ class _ExampleBar extends StatelessWidget { } } -class _InfoDialog extends StatelessWidget { - const _InfoDialog(this.useCase); - - final ExampleUseCase useCase; - +class const _InfoDialog(final ExampleUseCase useCase) extends StatelessWidget { static final _paragraphBreak = RegExp(r'\n{2,}'); static final _lineBreak = RegExp(r'\n(?!\d+\. |[-*] )'); diff --git a/examples/lib/commons/example_use_case.dart b/examples/lib/commons/example_use_case.dart index 0dbf91c6ef2..cc2ea00df61 100644 --- a/examples/lib/commons/example_use_case.dart +++ b/examples/lib/commons/example_use_case.dart @@ -1,16 +1,13 @@ import 'package:flutter/widgets.dart'; import 'package:widgetbook/widgetbook.dart'; -class ExampleUseCase extends WidgetbookUseCase { - ExampleUseCase({ - required super.name, - required WidgetBuilder builder, - required this.codeLink, - required this.info, - }) : super(builder: _persistent(builder)); - - final String codeLink; - final String info; +class ExampleUseCase({ + required super.name, + required WidgetBuilder builder, + required final String codeLink, + required final String info, +}) extends WidgetbookUseCase { + this : super(builder: _persistent(builder)); static WidgetBuilder _persistent(WidgetBuilder builder) { final key = GlobalKey(); @@ -22,16 +19,15 @@ class ExampleUseCase extends WidgetbookUseCase { /// of its state changes, for example when typing in the search field. This /// widget only runs the [builder] again when the knobs of the example have /// changed, so that the games are not restarted for unrelated changes. -class _PersistentExample extends StatefulWidget { - const _PersistentExample({required this.builder, super.key}); - - final WidgetBuilder builder; - +class const _PersistentExample({ + required final WidgetBuilder builder, + super.key, +}) extends StatefulWidget { @override State<_PersistentExample> createState() => _PersistentExampleState(); } -class _PersistentExampleState extends State<_PersistentExample> { +class _PersistentExampleState() extends State<_PersistentExample> { Widget? _child; String? _knobValues; Map _knobs = const {}; diff --git a/examples/lib/commons/paths.dart b/examples/lib/commons/paths.dart index ee2c26409e1..328d7ae4b22 100644 --- a/examples/lib/commons/paths.dart +++ b/examples/lib/commons/paths.dart @@ -26,18 +26,14 @@ final pathStroke = Paint() /// /// Paints are expensive to create, so the three of them are created once /// and picked by state with [forState] whenever they are needed. -class InteractiveStatePaints { - InteractiveStatePaints({ - required Color normal, - required Color hovered, - required Color active, - }) : normal = _stroke(normal), - hovered = _stroke(hovered, 1.05), - active = _stroke(active, 1.25); - - final Paint normal; - final Paint hovered; - final Paint active; +class InteractiveStatePaints({ + required Color normal, + required Color hovered, + required Color active, +}) { + final Paint normal = _stroke(normal); + final Paint hovered = _stroke(hovered, 1.05); + final Paint active = _stroke(active, 1.25); Paint forState({required bool isDragging, required bool isHovering}) { if (isDragging) { diff --git a/examples/lib/commons/rounded_rect_component.dart b/examples/lib/commons/rounded_rect_component.dart index e9ac0fcc542..9e90591ae47 100644 --- a/examples/lib/commons/rounded_rect_component.dart +++ b/examples/lib/commons/rounded_rect_component.dart @@ -4,7 +4,7 @@ import 'package:material_ui/material_ui.dart'; /// A rectangle whose corners are rounded with half of its height, so that /// its short sides are semicircles. -class RoundedRectComponent extends PositionComponent with HasPaint { +class RoundedRectComponent() extends PositionComponent with HasPaint { @override void render(Canvas canvas) { canvas.drawRRect( diff --git a/examples/lib/platform/page_provider.dart b/examples/lib/platform/page_provider.dart index b22aaae44d6..88929bb01de 100644 --- a/examples/lib/platform/page_provider.dart +++ b/examples/lib/platform/page_provider.dart @@ -1,3 +1,3 @@ -abstract class PageProvider { +abstract class PageProvider() { String? getPage(); } diff --git a/examples/lib/platform/stub_provider.dart b/examples/lib/platform/stub_provider.dart index 3e04b7a3e2d..32838719198 100644 --- a/examples/lib/platform/stub_provider.dart +++ b/examples/lib/platform/stub_provider.dart @@ -1,6 +1,6 @@ import 'package:examples/platform/page_provider.dart'; -class PageProviderImpl extends PageProvider { +class PageProviderImpl() extends PageProvider { @override String? getPage() { return null; diff --git a/examples/lib/platform/web_provider.dart b/examples/lib/platform/web_provider.dart index fb9dae661bc..e3805d3397a 100644 --- a/examples/lib/platform/web_provider.dart +++ b/examples/lib/platform/web_provider.dart @@ -1,7 +1,7 @@ import 'package:examples/platform/page_provider.dart'; import 'package:web/web.dart'; -class PageProviderImpl extends PageProvider { +class PageProviderImpl() extends PageProvider { @override String? getPage() { var page = window.location.search; diff --git a/examples/lib/stories/animations/animation_group_example.dart b/examples/lib/stories/animations/animation_group_example.dart index d4e95f590ba..f62cabd69ae 100644 --- a/examples/lib/stories/animations/animation_group_example.dart +++ b/examples/lib/stories/animations/animation_group_example.dart @@ -4,12 +4,12 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -enum RobotState { +enum RobotState() { idle, running, } -class AnimationGroupExample extends FlameGame with TapCallbacks { +class AnimationGroupExample() extends FlameGame with TapCallbacks { static const description = ''' This example shows how to create a component that can be switched between different states to change the animation that is playing.\n\n diff --git a/examples/lib/stories/animations/aseprite_example.dart b/examples/lib/stories/animations/aseprite_example.dart index fa2116c486a..871079cb915 100644 --- a/examples/lib/stories/animations/aseprite_example.dart +++ b/examples/lib/stories/animations/aseprite_example.dart @@ -1,7 +1,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; -class AsepriteExample extends FlameGame { +class AsepriteExample() extends FlameGame { static const String description = ''' This example shows how to load animations from an Aseprite json file and a sprite sheet. There is no interaction on this example. diff --git a/examples/lib/stories/animations/basic_animation_example.dart b/examples/lib/stories/animations/basic_animation_example.dart index 2eaa039b246..aaa748366a2 100644 --- a/examples/lib/stories/animations/basic_animation_example.dart +++ b/examples/lib/stories/animations/basic_animation_example.dart @@ -5,7 +5,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class BasicAnimationsExample extends FlameGame { +class BasicAnimationsExample() extends FlameGame { static const description = ''' Basic example of how to use `SpriteAnimation`s in Flame's. @@ -13,10 +13,10 @@ class BasicAnimationsExample extends FlameGame { animations. '''; - BasicAnimationsExample() : super(world: BasicAnimationsWorld()); + this : super(world: BasicAnimationsWorld()); } -class BasicAnimationsWorld extends World with TapCallbacks, HasGameRef { +class BasicAnimationsWorld() extends World with TapCallbacks, HasGameRef { late Image creature; @override diff --git a/examples/lib/stories/animations/benchmark_example.dart b/examples/lib/stories/animations/benchmark_example.dart index 95d07065770..a84e137574f 100644 --- a/examples/lib/stories/animations/benchmark_example.dart +++ b/examples/lib/stories/animations/benchmark_example.dart @@ -5,14 +5,14 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class BenchmarkExample extends FlameGame { +class BenchmarkExample() extends FlameGame { static const description = ''' See how many SpriteAnimationComponent's your platform can handle before it starts to drop in FPS, this is without any sprite batching and such. 100 animation components are added per tap. '''; - BenchmarkExample() : super(world: BenchmarkWorld()); + this : super(world: BenchmarkWorld()); final emberSize = Vector2.all(20); late final TextComponent emberCounter; @@ -43,7 +43,8 @@ starts to drop in FPS, this is without any sprite batching and such. } } -class BenchmarkWorld extends World +class BenchmarkWorld() + extends World with TapCallbacks, HasGameRef { final Random random = Random(); diff --git a/examples/lib/stories/bridge_libraries/audio/basic_audio_example.dart b/examples/lib/stories/bridge_libraries/audio/basic_audio_example.dart index 6e4566f85c2..ff5b038e912 100644 --- a/examples/lib/stories/bridge_libraries/audio/basic_audio_example.dart +++ b/examples/lib/stories/bridge_libraries/audio/basic_audio_example.dart @@ -6,7 +6,7 @@ import 'package:flame/palette.dart'; import 'package:flame_audio/flame_audio.dart'; import 'package:flutter/painting.dart'; -class BasicAudioExample extends FlameGame { +class BasicAudioExample() extends FlameGame { static const String description = ''' This example showcases the most basic Flame Audio functionalities. diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart index 5acbff09c2c..301d5cc8f0d 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart @@ -7,7 +7,7 @@ import 'package:flame/events.dart'; import 'package:flame/flame.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class AnimatedBodyExample extends Forge2DExampleGame { +class AnimatedBodyExample() extends Forge2DExampleGame { static const String description = ''' In this example we show how to add an animated chopper, which is created with a SpriteAnimationComponent, on top of a BodyComponent. @@ -15,14 +15,15 @@ class AnimatedBodyExample extends Forge2DExampleGame { Tap the screen to add more choppers. '''; - AnimatedBodyExample() + this : super( gravity: Vector2.zero(), world: AnimatedBodyWorld(), ); } -class AnimatedBodyWorld extends Forge2DWorld +class AnimatedBodyWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { late Image chopper; late SpriteAnimation animation; @@ -59,14 +60,13 @@ class AnimatedBodyWorld extends Forge2DWorld } } -class ChopperBody extends BodyComponent { - final Vector2 _position; - final Vector2 size; +class ChopperBody( + final Vector2 _position, + PositionComponent component, +) extends BodyComponent { + final Vector2 size = component.size; - ChopperBody( - this._position, - PositionComponent component, - ) : size = component.size { + this { renderBody = false; add(component); } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/camera_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/camera_example.dart index f09cf1b5c5a..2802739809a 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/camera_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/camera_example.dart @@ -3,17 +3,17 @@ import 'package:examples/stories/bridge_libraries/flame_forge2d/sprite_body_exam import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/style.dart'; import 'package:flame/events.dart'; -class CameraExample extends Forge2DExampleGame { +class CameraExample() extends Forge2DExampleGame { static const String description = ''' This example showcases the possibility to follow BodyComponents with the camera. When the screen is tapped a pizza is added, which the camera will follow. Other than that it is the same as the domino example. '''; // The same scale as the domino example, since it shows the same tower. - CameraExample() : super(world: CameraExampleWorld(), metersToPixels: 24); + this : super(world: CameraExampleWorld(), metersToPixels: 24); } -class CameraExampleWorld extends DominoExampleWorld { +class CameraExampleWorld() extends DominoExampleWorld { @override void onTapDown(TapDownEvent info) { final position = info.localPosition; diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart index 5571b84eb62..baebb2d0231 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart @@ -8,13 +8,13 @@ import 'package:material_ui/material_ui.dart'; const TextStyle _textStyle = TextStyle(color: Colors.white, fontSize: 2); -class CompositionExample extends Forge2DExampleGame { +class CompositionExample() extends Forge2DExampleGame { static const description = ''' This example shows how to compose a `BodyComponent` together with a normal Flame component. Click the ball to see the number increment. '''; - CompositionExample() : super(metersToPixels: 20, gravity: Vector2(0, 10.0)); + this : super(metersToPixels: 20, gravity: Vector2(0, 10.0)); @override Future onLoad() async { @@ -26,8 +26,8 @@ class CompositionExample extends Forge2DExampleGame { } } -class TappableText extends TextComponent with TapCallbacks { - TappableText(Vector2 position) +class TappableText(Vector2 position) extends TextComponent with TapCallbacks { + this : super( text: 'A normal tappable Flame component', textRenderer: TextPaint(style: _textStyle), @@ -62,12 +62,12 @@ class TappableText extends TextComponent with TapCallbacks { } } -class TappableBall extends Ball with TapCallbacks { +class TappableBall(super.position) extends Ball with TapCallbacks { late final TextComponent textComponent; int counter = 0; late final TextPaint _textPaint; - TappableBall(super.position) { + this { originalPaint = Paint()..color = Colors.amber; paint = originalPaint; } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart index 9169bbea68f..f51f4bf7128 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart @@ -7,7 +7,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class ContactCallbacksExample extends Forge2DExampleGame { +class ContactCallbacksExample() extends Forge2DExampleGame { static const description = ''' This example shows how `BodyComponent`s can react to collisions with other bodies. @@ -15,11 +15,11 @@ class ContactCallbacksExample extends Forge2DExampleGame { balls that it collides with. '''; - ContactCallbacksExample() - : super(gravity: Vector2(0, 10.0), world: ContactCallbackWorld()); + this : super(gravity: Vector2(0, 10.0), world: ContactCallbackWorld()); } -class ContactCallbackWorld extends Forge2DWorld +class ContactCallbackWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { @override Future onLoad() async { diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart index b932154d4a0..7a37ce8051c 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart @@ -7,7 +7,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class DominoExample extends Forge2DExampleGame { +class DominoExample() extends Forge2DExampleGame { static const description = ''' The classic domino tower: vertical dominoes carry horizontal ones as planks, level by level, with braces at the edges. @@ -16,7 +16,7 @@ class DominoExample extends Forge2DExampleGame { that topples it. '''; - DominoExample() + this : super( gravity: Vector2(0, 10.0), world: DominoExampleWorld(), @@ -24,7 +24,8 @@ class DominoExample extends Forge2DExampleGame { ); } -class DominoExampleWorld extends Forge2DWorld +class DominoExampleWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { static const dominoWidth = 0.2; static const dominoHeight = 1.0; @@ -132,21 +133,17 @@ class DominoExampleWorld extends Forge2DWorld } } -class Domino extends BodyComponent with GlowingBody { - Domino({ - required this.initialPosition, - required this.horizontal, - required this.density, - required Color color, - }) { +class Domino({ + /// Where the domino starts out; [position] tracks the live body position. + required final Vector2 initialPosition, + required final bool horizontal, + required final double density, + required Color color, +}) extends BodyComponent with GlowingBody { + this { paint = Paint()..color = color; } - /// Where the domino starts out; [position] tracks the live body position. - final Vector2 initialPosition; - final bool horizontal; - final double density; - @override double get outlineWidth => 0.04; @@ -170,8 +167,8 @@ class Domino extends BodyComponent with GlowingBody { } } -class Ground extends BodyComponent with GlowingBody { - Ground() { +class Ground() extends BodyComponent with GlowingBody { + this { paint = Paint()..color = ExampleColors.slate; } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/drag_callbacks_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/drag_callbacks_example.dart index 1d58c2209cb..639eca5eb30 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/drag_callbacks_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/drag_callbacks_example.dart @@ -5,14 +5,14 @@ import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:material_ui/material_ui.dart' hide Draggable; -class DragCallbacksExample extends Forge2DExampleGame { +class DragCallbacksExample() extends Forge2DExampleGame { static const description = ''' In this example we use Flame's normal `DragCallbacks` mixin to give impulses to a ball when we are dragging it around. If you are interested in dragging bodies around, also have a look at the MouseJointExample. '''; - DragCallbacksExample() : super(gravity: Vector2.all(0.0)); + this : super(gravity: Vector2.all(0.0)); @override Future onLoad() async { @@ -23,8 +23,8 @@ class DragCallbacksExample extends Forge2DExampleGame { } } -class DraggableBall extends Ball with DragCallbacks { - DraggableBall(super.position) : super(radius: 5) { +class DraggableBall(super.position) extends Ball with DragCallbacks { + this : super(radius: 5) { originalPaint = Paint()..color = Colors.amber; paint = originalPaint; } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/distance_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/distance_joint.dart index 0f7655409d9..a28a3745940 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/distance_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/distance_joint.dart @@ -6,16 +6,17 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class DistanceJointExample extends Forge2DExampleGame { +class DistanceJointExample() extends Forge2DExampleGame { static const description = ''' This example shows how to use a `DistanceJoint`. Tap the screen to add a pair of balls joined with a `DistanceJoint`. '''; - DistanceJointExample() : super(world: DistanceJointWorld()); + this : super(world: DistanceJointWorld()); } -class DistanceJointWorld extends Forge2DWorld +class DistanceJointWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { @override Future onLoad() async { diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/filter_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/filter_joint.dart index a334a7442cf..8c79ec62552 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/filter_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/filter_joint.dart @@ -5,7 +5,7 @@ import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/style.dart import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class FilterJointExample extends Forge2DExampleGame { +class FilterJointExample() extends Forge2DExampleGame { static const description = ''' This example shows how to use a `FilterJoint`, which doesn't constrain the bodies at all: its only purpose is to stop two specific bodies from @@ -15,11 +15,10 @@ class FilterJointExample extends Forge2DExampleGame { through each other, while the pair on the right collides as usual. '''; - FilterJointExample() - : super(gravity: Vector2(0, 10.0), world: FilterJointWorld()); + this : super(gravity: Vector2(0, 10.0), world: FilterJointWorld()); } -class FilterJointWorld extends Forge2DWorld with HasGameRef { +class FilterJointWorld() extends Forge2DWorld with HasGameRef { @override Future onLoad() async { await super.onLoad(); diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart index 9508f22616d..053b8839548 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart @@ -5,17 +5,16 @@ import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/style.dart import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class MotorJointExample extends Forge2DExampleGame { +class MotorJointExample() extends Forge2DExampleGame { static const description = ''' This example shows how to use a `MotorJoint`. The ball spins around the center point. Tap the screen to change the direction. '''; - MotorJointExample() - : super(gravity: Vector2.zero(), world: MotorJointWorld()); + this : super(gravity: Vector2.zero(), world: MotorJointWorld()); } -class MotorJointWorld extends Forge2DWorld with TapCallbacks { +class MotorJointWorld() extends Forge2DWorld with TapCallbacks { late Ball ball; late MotorJoint joint; final motorSpeed = 1; diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart index 6db01776724..7ee0c999c17 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart @@ -6,18 +6,18 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class MouseJointExample extends Forge2DExampleGame { +class MouseJointExample() extends Forge2DExampleGame { static const description = ''' In this example we use a `MouseJoint` to make the ball follow the mouse when you drag it around. The line shows the joint pulling the ball towards the pointer. '''; - MouseJointExample() - : super(gravity: Vector2(0, 10.0), world: MouseJointWorld()); + this : super(gravity: Vector2(0, 10.0), world: MouseJointWorld()); } -class MouseJointWorld extends Forge2DWorld +class MouseJointWorld() + extends Forge2DWorld with DragCallbacks, HasGameRef { late Ball ball; late Body groundBody; diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/prismatic_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/prismatic_joint.dart index 0b85b41484e..be0f81621f9 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/prismatic_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/prismatic_joint.dart @@ -3,7 +3,7 @@ import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/joint_rend import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/style.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class PrismaticJointExample extends Forge2DExampleGame { +class PrismaticJointExample() extends Forge2DExampleGame { static const description = ''' This example shows how to use a `PrismaticJoint`. diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart index 57157e4f637..0ec6e10d579 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart @@ -8,7 +8,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class RevoluteJointExample extends Forge2DExampleGame { +class RevoluteJointExample() extends Forge2DExampleGame { static const description = ''' In this example we use a joint to keep a body with several fixtures stuck to another body. @@ -16,11 +16,11 @@ class RevoluteJointExample extends Forge2DExampleGame { Tap the screen to add more of these combined bodies. '''; - RevoluteJointExample() - : super(gravity: Vector2(0, 10.0), world: RevoluteJointWorld()); + this : super(gravity: Vector2(0, 10.0), world: RevoluteJointWorld()); } -class RevoluteJointWorld extends Forge2DWorld +class RevoluteJointWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { @override Future onLoad() async { @@ -37,11 +37,7 @@ class RevoluteJointWorld extends Forge2DWorld } } -class CircleShuffler extends BodyComponent { - final Ball ball; - - CircleShuffler(this.ball); - +class CircleShuffler(final Ball ball) extends BodyComponent { @override Body createBody() { final bodyDef = BodyDef( diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart index c8c31fc93fd..f772e83dc0d 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart @@ -7,16 +7,17 @@ import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:material_ui/material_ui.dart'; -class WeldJointExample extends Forge2DExampleGame { +class WeldJointExample() extends Forge2DExampleGame { static const description = ''' This example shows how to use a `WeldJoint`. Tap the screen to add a ball to test the bridge built using a `WeldJoint` '''; - WeldJointExample() : super(world: WeldJointWorld()); + this : super(world: WeldJointWorld()); } -class WeldJointWorld extends Forge2DWorld +class WeldJointWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { final pillarHeight = 20.0; final pillarWidth = 5.0; diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/wheel_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/wheel_joint.dart index b5d7e292cd5..63c9aede7ea 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/wheel_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/wheel_joint.dart @@ -7,7 +7,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class WheelJointExample extends Forge2DExampleGame { +class WheelJointExample() extends Forge2DExampleGame { static const description = ''' This example shows how to use a `WheelJoint`, which is the suspension of a vehicle: the wheel can spin and travel along a spring-loaded axis. @@ -15,7 +15,7 @@ class WheelJointExample extends Forge2DExampleGame { Tap the screen to change the direction that the car drives in. '''; - WheelJointExample() + this : super( gravity: Vector2(0, 10.0), world: WheelJointWorld(), @@ -23,7 +23,8 @@ class WheelJointExample extends Forge2DExampleGame { ); } -class WheelJointWorld extends Forge2DWorld +class WheelJointWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { final joints = []; static const _motorSpeed = 20.0; @@ -82,13 +83,11 @@ class WheelJointWorld extends Forge2DWorld } } -class Chassis extends BodyComponent with GlowingBody { - Chassis(this._position) { +class Chassis(final Vector2 _position) extends BodyComponent with GlowingBody { + this { paint = Paint()..color = ExampleColors.indigo; } - final Vector2 _position; - @override Body createBody() { final bodyDef = BodyDef(type: BodyType.dynamic, position: _position); @@ -99,13 +98,11 @@ class Chassis extends BodyComponent with GlowingBody { } } -class Wheel extends BodyComponent with GlowingBody { - Wheel(this._position) { +class Wheel(final Vector2 _position) extends BodyComponent with GlowingBody { + this { paint = Paint()..color = ExampleColors.emerald; } - final Vector2 _position; - @override Body createBody() { final bodyDef = BodyDef(type: BodyType.dynamic, position: _position); @@ -117,8 +114,8 @@ class Wheel extends BodyComponent with GlowingBody { } /// Rolling hills for the car to drive over, built as a one-sided chain. -class Terrain extends BodyComponent with GlowingBody { - Terrain() { +class Terrain() extends BodyComponent with GlowingBody { + this { paint = Paint()..color = ExampleColors.slate; } @@ -147,13 +144,11 @@ class Terrain extends BodyComponent with GlowingBody { } /// A wall at the end of the track that the car bumps into. -class TrackEnd extends BodyComponent with GlowingBody { - TrackEnd(this._x) { +class TrackEnd(final double _x) extends BodyComponent with GlowingBody { + this { paint = Paint()..color = ExampleColors.slate; } - final double _x; - @override Body createBody() { final bodyDef = BodyDef( diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/raycast_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/raycast_example.dart index 3365ae45e29..d12ff74c5f3 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/raycast_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/raycast_example.dart @@ -6,9 +6,9 @@ import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/style.dart import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:material_ui/material_ui.dart' show Colors, Paint, Canvas; +import 'package:material_ui/material_ui.dart' show Canvas, Colors, Paint; -class RaycastExample extends Forge2DExampleGame with MouseMoveCallbacks { +class RaycastExample() extends Forge2DExampleGame with MouseMoveCallbacks { static const String description = ''' This example shows how ray casts can be used to find the nearest and farthest shapes. @@ -23,7 +23,7 @@ class RaycastExample extends Forge2DExampleGame with MouseMoveCallbacks { Box? nearestBox; Box? farthestBox; - RaycastExample() : super(gravity: Vector2.zero()); + this : super(gravity: Vector2.zero()); @override Future onLoad() async { @@ -121,11 +121,8 @@ class RaycastExample extends Forge2DExampleGame with MouseMoveCallbacks { } } -class LineComponent extends Component { - LineComponent(this.points, this.paint); - - final List points; - final Paint paint; +class LineComponent(final List points, final Paint paint) + extends Component { final Path path = Path(); @override @@ -150,11 +147,7 @@ class LineComponent extends Component { } } -class Box extends BodyComponent { - Box(this.initialPosition); - - final Vector2 initialPosition; - +class Box(final Vector2 initialPosition) extends BodyComponent { @override Body createBody() { final bodyDef = BodyDef(position: initialPosition); diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/revolute_joint_with_motor_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/revolute_joint_with_motor_example.dart index fef7b538123..061170e024a 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/revolute_joint_with_motor_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/revolute_joint_with_motor_example.dart @@ -8,7 +8,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class RevoluteJointWithMotorExample extends Forge2DExampleGame { +class RevoluteJointWithMotorExample() extends Forge2DExampleGame { static const String description = ''' This example showcases a revolute joint, which is the spinning balls in the center. @@ -18,10 +18,11 @@ class RevoluteJointWithMotorExample extends Forge2DExampleGame { down the funnel. '''; - RevoluteJointWithMotorExample() : super(world: RevoluteJointWithMotorWorld()); + this : super(world: RevoluteJointWithMotorWorld()); } -class RevoluteJointWithMotorWorld extends Forge2DWorld +class RevoluteJointWithMotorWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { final random = Random(); @@ -47,11 +48,7 @@ class RevoluteJointWithMotorWorld extends Forge2DWorld } } -class CircleShuffler extends BodyComponent { - CircleShuffler(this._center); - - final Vector2 _center; - +class CircleShuffler(final Vector2 _center) extends BodyComponent { @override Body createBody() { final bodyDef = BodyDef( @@ -91,14 +88,13 @@ class CircleShuffler extends BodyComponent { } } -class CornerRamp extends BodyComponent with GlowingBody { - CornerRamp(this._center, {this.isMirrored = false}) { +class CornerRamp(final Vector2 _center, {final bool isMirrored = false}) + extends BodyComponent + with GlowingBody { + this { paint = Paint()..color = ExampleColors.slate; } - final bool isMirrored; - final Vector2 _center; - @override Body createBody() { final mirrorFactor = isMirrored ? -1 : 1; diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart index 7714c7e285d..04e9ecd708f 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart @@ -6,20 +6,21 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class SpriteBodyExample extends Forge2DExampleGame { +class SpriteBodyExample() extends Forge2DExampleGame { static const String description = ''' In this example we show how to add a sprite on top of a `BodyComponent`. Tap the screen to add more pizzas. '''; - SpriteBodyExample() + this : super( gravity: Vector2(0, 10.0), world: SpriteBodyWorld(), ); } -class SpriteBodyWorld extends Forge2DWorld +class SpriteBodyWorld() + extends Forge2DWorld with TapCallbacks, HasGameRef { @override Future onLoad() async { @@ -35,14 +36,11 @@ class SpriteBodyWorld extends Forge2DWorld } } -class Pizza extends BodyComponent { - final Vector2 initialPosition; - final Vector2 size; - - Pizza( - this.initialPosition, { - Vector2? size, - }) : size = size ?? Vector2(2, 3); +class Pizza( + final Vector2 initialPosition, { + Vector2? size, +}) extends BodyComponent { + final Vector2 size = size ?? Vector2(2, 3); @override Future onLoad() async { diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/tap_callbacks_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/tap_callbacks_example.dart index 411314089e9..03331368ca6 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/tap_callbacks_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/tap_callbacks_example.dart @@ -5,14 +5,14 @@ import 'package:flame/events.dart'; import 'package:flame/palette.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class TapCallbacksExample extends Forge2DExampleGame { +class TapCallbacksExample() extends Forge2DExampleGame { static const String description = ''' In this example we show how to use Flame's TapCallbacks mixin to react to taps on `BodyComponent`s. Tap the ball to give it a random impulse, or the text to add an effect to it. '''; - TapCallbacksExample() : super(metersToPixels: 20, gravity: Vector2(0, 10.0)); + this : super(metersToPixels: 20, gravity: Vector2(0, 10.0)); @override Future onLoad() async { @@ -23,8 +23,8 @@ class TapCallbacksExample extends Forge2DExampleGame { } } -class TappableBall extends Ball with TapCallbacks { - TappableBall(super.position) { +class TappableBall(super.position) extends Ball with TapCallbacks { + this { originalPaint = BasicPalette.white.paint(); paint = originalPaint; } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/balls.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/balls.dart index 9940411937c..2ec4eb84914 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/balls.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/balls.dart @@ -4,21 +4,18 @@ import 'package:flame/palette.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:material_ui/material_ui.dart'; -class Ball extends BodyComponent with ContactCallbacks, GlowingBody { +class Ball( + final Vector2 _position, { + final double radius = 2, + final BodyType bodyType = BodyType.dynamic, + Color? color, +}) extends BodyComponent with ContactCallbacks, GlowingBody { late Paint originalPaint; bool giveNudge = false; - final double radius; - final BodyType bodyType; - final Vector2 _position; double _timeSinceNudge = 0.0; static const double _minNudgeRest = 2.0; - Ball( - this._position, { - this.radius = 2, - this.bodyType = BodyType.dynamic, - Color? color, - }) { + this { originalPaint = Paint()..color = color ?? randomColor(); paint = originalPaint; } @@ -84,8 +81,8 @@ class Ball extends BodyComponent with ContactCallbacks, GlowingBody { } } -class WhiteBall extends Ball with ContactCallbacks { - WhiteBall(super.position) { +class WhiteBall(super.position) extends Ball with ContactCallbacks { + this { originalPaint = BasicPalette.white.paint(); paint = originalPaint; } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart index 4038aa80c1b..592a2713b06 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart @@ -18,13 +18,12 @@ List createBoundaries(Forge2DGame game, {double? strokeWidth}) { ]; } -class Wall extends BodyComponent with GlowingBody { - final Vector2 start; - final Vector2 end; - final double strokeWidth; +class Wall(final Vector2 start, final Vector2 end, {double? strokeWidth}) + extends BodyComponent + with GlowingBody { + final double strokeWidth = strokeWidth ?? 0.15; - Wall(this.start, this.end, {double? strokeWidth}) - : strokeWidth = strokeWidth ?? 0.15 { + this { paint = Paint()..color = ExampleColors.slate; } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boxes.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boxes.dart index f9cef84e9b7..c377f79b7d6 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boxes.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boxes.dart @@ -5,19 +5,14 @@ import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/style.dart import 'package:flame/events.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -class Box extends BodyComponent with GlowingBody { - final Vector2 startPosition; - final double width; - final double height; - final BodyType bodyType; - - Box({ - required this.startPosition, - required this.width, - required this.height, - this.bodyType = BodyType.dynamic, - Color? color, - }) { +class Box({ + required final Vector2 startPosition, + required final double width, + required final double height, + final BodyType bodyType = BodyType.dynamic, + Color? color, +}) extends BodyComponent with GlowingBody { + this { paint = Paint()..color = color ?? randomColor(); } @@ -46,18 +41,16 @@ class Box extends BodyComponent with GlowingBody { } } -class DraggableBox extends Box with DragCallbacks { +class DraggableBox({ + required super.startPosition, + required super.width, + required super.height, +}) extends Box with DragCallbacks { MouseJoint? mouseJoint; MouseJointRenderer? _jointRenderer; late final groundBody = world.createBody(BodyDef()); bool _destroyJoint = false; - DraggableBox({ - required super.startPosition, - required super.width, - required super.height, - }); - @override void update(double dt) { if (_destroyJoint && mouseJoint != null) { diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/joint_renderer.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/joint_renderer.dart index 1cefaac695e..b41caa3b5f9 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/joint_renderer.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/joint_renderer.dart @@ -10,12 +10,12 @@ import 'package:flame_forge2d/flame_forge2d.dart'; /// /// The line runs between the two anchor points, with a dot on each anchor. /// The renderer removes itself once the joint is destroyed. -class JointRenderer extends Component { - JointRenderer({required this.joint, Color? color, super.priority = -1}) - : color = color ?? ExampleColors.slate; - - final Joint joint; - final Color color; +class JointRenderer({ + required final Joint joint, + Color? color, + super.priority = -1, +}) extends Component { + final Color color = color ?? ExampleColors.slate; static const _anchorRadius = 0.22; @@ -58,9 +58,8 @@ class JointRenderer extends Component { /// Draws a [MouseJoint] from the body it drags to the target it is pulling /// towards, which is what makes the joint's spring visible. -class MouseJointRenderer extends JointRenderer { - MouseJointRenderer({required MouseJoint super.joint, super.color}); - +class MouseJointRenderer({required MouseJoint super.joint, super.color}) + extends JointRenderer { MouseJoint get mouseJoint => joint as MouseJoint; @override @@ -86,21 +85,17 @@ class MouseJointRenderer extends JointRenderer { /// Draws the axis of a [PrismaticJoint] between its lower and upper limit, so /// that the range the body can travel is visible. -class PrismaticJointRenderer extends JointRenderer { - PrismaticJointRenderer({ - required PrismaticJoint super.joint, - required this.axis, - required this.anchor, - super.color, - }); - - PrismaticJoint get prismaticJoint => joint as PrismaticJoint; +class PrismaticJointRenderer({ + required PrismaticJoint super.joint, /// The axis that the joint moves along, in world coordinates. - final Vector2 axis; + required final Vector2 axis, /// The point that the axis passes through, in world coordinates. - final Vector2 anchor; + required final Vector2 anchor, + super.color, +}) extends JointRenderer { + PrismaticJoint get prismaticJoint => joint as PrismaticJoint; final Vector2 _lower = Vector2.zero(); final Vector2 _upper = Vector2.zero(); diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/style.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/style.dart index 908f743b334..21c890a3e7b 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/style.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/style.dart @@ -5,7 +5,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; /// The palette that the Forge2D examples share, matching the one used by the /// Forge2D package's own examples. -abstract final class ExampleColors { +abstract final class ExampleColors() { static const background = Color(0xFF0B1020); static const indigo = Color(0xFF7C9CFF); static const sky = Color(0xFF38BDF8); @@ -100,17 +100,16 @@ mixin GlowingBody on BodyComponent { /// The base game for the Forge2D examples, which gives them the shared dark /// background. -class Forge2DExampleGame extends Forge2DGame { - /// These examples are laid out for a screen that shows tens of meters, so - /// they pin the rendering scale they were written for rather than following - /// the default. See the package example for a world at the default scale. - Forge2DExampleGame({ - super.world, - super.camera, - super.gravity, - super.metersToPixels = 10, - }); - +/// +/// These examples are laid out for a screen that shows tens of meters, so +/// they pin the rendering scale they were written for rather than following +/// the default. See the package example for a world at the default scale. +class Forge2DExampleGame({ + super.world, + super.camera, + super.gravity, + super.metersToPixels = 10, +}) extends Forge2DGame { @override Color backgroundColor() => ExampleColors.background; } diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/widget_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/widget_example.dart index cf9ceb9af59..4a6c5268879 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/widget_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/widget_example.dart @@ -7,7 +7,7 @@ import 'package:material_ui/material_ui.dart'; /// The body shape that a widget is given, which follows the shape that /// Material draws it with. -enum WidgetShape { +enum WidgetShape() { /// A plain box, for the app bar. box, @@ -20,12 +20,10 @@ enum WidgetShape { } /// One of the widgets of the counter app, carried by a Forge2D body. -class FallingWidget { - FallingWidget(this.shape); - +class FallingWidget( /// The shape of the body underneath the widget. - final WidgetShape shape; - + final WidgetShape shape, +) { Body? _body; /// The body that carries the widget, which only exists once the widget has @@ -38,7 +36,7 @@ class FallingWidget { Size size = Size.zero; } -class WidgetExample extends Forge2DExampleGame { +class WidgetExample() extends Forge2DExampleGame { static const String description = ''' This is the app that `flutter create` gives you, except that every widget rests on a Forge2D body and drops to the floor when the example starts. @@ -51,7 +49,7 @@ class WidgetExample extends Forge2DExampleGame { /// How many pixels one meter of the physics world is rendered as. static const scale = 20.0; - WidgetExample() : super(metersToPixels: scale, gravity: Vector2(0, 10.0)); + this : super(metersToPixels: scale, gravity: Vector2(0, 10.0)); final _random = Random(); @@ -201,9 +199,7 @@ class WidgetExample extends Forge2DExampleGame { } } -class BodyWidgetExample extends StatelessWidget { - const BodyWidgetExample({super.key}); - +class const BodyWidgetExample({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return GameWidget( @@ -218,16 +214,13 @@ class BodyWidgetExample extends StatelessWidget { /// The widget tree of the counter app, with every widget positioned by the /// body that carries it. -class CounterAppOverlay extends StatefulWidget { - const CounterAppOverlay(this.game, {super.key}); - - final WidgetExample game; - +class const CounterAppOverlay(final WidgetExample game, {super.key}) + extends StatefulWidget { @override State createState() => _CounterAppOverlayState(); } -class _CounterAppOverlayState extends State { +class _CounterAppOverlayState() extends State { static const _appBarHeight = 56.0; /// How much of the width the app bar covers. A bar that spans the whole diff --git a/examples/lib/stories/bridge_libraries/flame_isolate/simple_isolate_example.dart b/examples/lib/stories/bridge_libraries/flame_isolate/simple_isolate_example.dart index c056b048ba4..a50429a1c25 100644 --- a/examples/lib/stories/bridge_libraries/flame_isolate/simple_isolate_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_isolate/simple_isolate_example.dart @@ -8,7 +8,7 @@ import 'package:flame/game.dart'; import 'package:flame_isolate/flame_isolate.dart'; import 'package:material_ui/material_ui.dart'; -class SimpleIsolateExample extends FlameGame { +class SimpleIsolateExample() extends FlameGame { static const String description = ''' This example showcases a simple FlameIsolate example, making it easy to continually run heavy load without stutter. @@ -57,18 +57,15 @@ class SimpleIsolateExample extends FlameGame { } } -enum ComputeType { +enum ComputeType(final String description) { isolate('Running in isolate'), - synchronous('Running synchronously'); - - final String description; - - const ComputeType(this.description); + synchronous('Running synchronously'), } -class CalculatePrimeNumber extends PositionComponent +class CalculatePrimeNumber() + extends PositionComponent with TapCallbacks, FlameIsolate { - CalculatePrimeNumber() : super(anchor: Anchor.center); + this : super(anchor: Anchor.center); ComputeType computeType = ComputeType.isolate; late Timer _interval; diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/button_row.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/button_row.dart index 9b24da87ee1..9410273b0c2 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/button_row.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/button_row.dart @@ -2,8 +2,8 @@ import 'package:examples/stories/bridge_libraries/flame_jenny/components/dialogu import 'package:flame/components.dart'; import 'package:jenny/jenny.dart'; -class ButtonRow extends PositionComponent { - ButtonRow({required super.size}) : super(position: Vector2(0, 96)); +class ButtonRow({required super.size}) extends PositionComponent { + this : super(position: Vector2(0, 96)); void removeButtons() { final buttonList = children.query(); @@ -59,11 +59,11 @@ class ButtonRow extends PositionComponent { addAll(optionButtons); } - void showCloseButton(Function() onClose) { + void showCloseButton(void Function() onClose) { final closeButton = DialogueButton( assetPath: 'assets/images/green_button_sqr.png', text: 'Close', - onPressed: () => onClose(), + onPressed: onClose, position: Vector2(size.x / 2, 0), ); add(closeButton); diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart index 746394c21e4..3b2580cf472 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart @@ -3,24 +3,21 @@ import 'dart:async'; import 'package:examples/stories/bridge_libraries/flame_jenny/components/dialogue_controller_component.dart'; import 'package:jenny/jenny.dart'; -class CommandLifecycleDialogueController extends DialogueControllerComponent { - CommandLifecycleDialogueController({ - required this.onCommandOverride, - required this.onCommandFinishOverride, - }); - final FutureOr Function(UserDefinedCommand command) onCommandOverride; - final FutureOr Function(UserDefinedCommand command) - onCommandFinishOverride; - +class CommandLifecycleDialogueController({ + required final FutureOr Function(UserDefinedCommand command) + onCommandOverride, + required final FutureOr Function(UserDefinedCommand command) + onCommandFinishOverride, +}) extends DialogueControllerComponent { @override FutureOr onCommand(UserDefinedCommand command) async { await onCommandOverride(command); - return super.onCommand(command); + await super.onCommand(command); } @override FutureOr onCommandFinish(UserDefinedCommand command) async { await onCommandFinishOverride(command); - return super.onCommandFinish(command); + await super.onCommandFinish(command); } } diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_box.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_box.dart index 654a7b9848e..380ae6bd0a7 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_box.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_box.dart @@ -3,7 +3,7 @@ import 'package:examples/stories/bridge_libraries/flame_jenny/components/dialogu import 'package:flame/components.dart'; import 'package:jenny/jenny.dart'; -class DialogueBoxComponent extends SpriteComponent with HasGameRef { +class DialogueBoxComponent() extends SpriteComponent with HasGameRef { DialogueTextBox textBox = DialogueTextBox(text: ''); final Vector2 spriteSize = Vector2(736, 128); late final ButtonRow buttonRow = ButtonRow(size: spriteSize); @@ -17,7 +17,7 @@ class DialogueBoxComponent extends SpriteComponent with HasGameRef { srcSize: spriteSize, ); addAll([buttonRow, textBox]); - return super.onLoad(); + await super.onLoad(); } void changeText(String newText, Function() goNextLine) { diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_button.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_button.dart index 7d02403c954..503c0fa4272 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_button.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_button.dart @@ -3,18 +3,13 @@ import 'package:flame/components.dart'; import 'package:flame/input.dart'; import 'package:material_ui/material_ui.dart'; -class DialogueButton extends SpriteButtonComponent { - DialogueButton({ - required super.position, - required this.assetPath, - required this.text, - required super.onPressed, - super.anchor = Anchor.center, - }); - - final String text; - final String assetPath; - +class DialogueButton({ + required super.position, + required final String assetPath, + required final String text, + required super.onPressed, + super.anchor = Anchor.center, +}) extends SpriteButtonComponent { @override Future onLoad() async { button = await Sprite.load(assetPath); diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_controller_component.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_controller_component.dart index e5a57d73f40..8f9f7531856 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_controller_component.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_controller_component.dart @@ -1,9 +1,11 @@ import 'dart:async'; + import 'package:examples/stories/bridge_libraries/flame_jenny/components/dialogue_box.dart'; import 'package:flame/components.dart' hide Timer; import 'package:jenny/jenny.dart'; -class DialogueControllerComponent extends Component +class DialogueControllerComponent() + extends Component with DialogueView, HasGameRef { Completer _forwardCompleter = Completer(); Completer _choiceCompleter = Completer(); @@ -24,7 +26,7 @@ class DialogueControllerComponent extends Component @override Future onNodeFinish(Node node) async { _dialogueBoxComponent.showCloseButton(_onClose); - return _closeCompleter.future; + return await _closeCompleter.future; } void _onClose() { @@ -38,7 +40,7 @@ class DialogueControllerComponent extends Component } Future _advance() async { - return _forwardCompleter.future; + return await _forwardCompleter.future; } @override @@ -46,7 +48,7 @@ class DialogueControllerComponent extends Component _forwardCompleter = Completer(); _changeTextAndShowNextButton(line); await _advance(); - return super.onLineStart(line); + return await super.onLineStart(line); } void _changeTextAndShowNextButton(DialogueLine line) { @@ -71,7 +73,7 @@ class DialogueControllerComponent extends Component option2: choice.options[1], ); await _advance(); - return _choiceCompleter.future; + return await _choiceCompleter.future; } void _onChoice(int optionNumber) { diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart index 05fabc788d8..cb02614de1a 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart @@ -2,8 +2,8 @@ import 'package:examples/stories/bridge_libraries/flame_jenny/commons/commons.da import 'package:flame/components.dart'; import 'package:material_ui/material_ui.dart'; -class DialogueTextBox extends TextBoxComponent { - DialogueTextBox({required super.text}) +class DialogueTextBox({required super.text}) extends TextBoxComponent { + this : super( position: Vector2(16, 16), size: Vector2(704, 96), diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/menu_button.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/menu_button.dart index a3e5b82ffd1..54a660ab046 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/menu_button.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/menu_button.dart @@ -4,14 +4,12 @@ import 'package:flame/palette.dart'; import 'package:flame/text.dart'; import 'package:material_ui/material_ui.dart'; -class MenuButton extends ButtonComponent { - MenuButton({ - required super.position, - required super.onPressed, - required this.text, - }) : super(size: Vector2(128, 42)); - - late String text; +class MenuButton({ + required super.position, + required super.onPressed, + required var String text, +}) extends ButtonComponent { + this : super(size: Vector2(128, 42)); final Paint white = BasicPalette.white.paint(); final TextPaint topTextPaint = TextPaint( diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_advanced_example.dart b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_advanced_example.dart index c7686aa2fab..62fbf3735f7 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_advanced_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_advanced_example.dart @@ -9,7 +9,7 @@ import 'package:flame/text.dart'; import 'package:flutter/services.dart'; import 'package:jenny/jenny.dart'; -class JennyAdvancedExample extends FlameGame { +class JennyAdvancedExample() extends FlameGame { static const String description = ''' This is an advanced example of how to use the Jenny Package. It includes implementing dialogue choices, setting custom variables, diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart index 8b4bf075b23..33c1c13241f 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart @@ -6,7 +6,7 @@ import 'package:flame/game.dart'; import 'package:flutter/services.dart'; import 'package:jenny/jenny.dart'; -class JennyCommandLifecycleExample extends FlameGame { +class JennyCommandLifecycleExample() extends FlameGame { static const String description = ''' This is an example of how the lifecycle methods relating to user-defined commands work. diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_simple_example.dart b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_simple_example.dart index 7aacc08316b..05b097d3a9e 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_simple_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_simple_example.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:flutter/services.dart'; import 'package:jenny/jenny.dart'; -class JennySimpleExample extends FlameGame { +class JennySimpleExample() extends FlameGame { static const String description = ''' This is a simple example of how to use the Jenny Package. It includes instantiating YarnProject and parsing a .yarn script. diff --git a/examples/lib/stories/bridge_libraries/flame_lottie/lottie_animation_example.dart b/examples/lib/stories/bridge_libraries/flame_lottie/lottie_animation_example.dart index 2fc4c3d77eb..e59869d2ae5 100644 --- a/examples/lib/stories/bridge_libraries/flame_lottie/lottie_animation_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_lottie/lottie_animation_example.dart @@ -1,7 +1,7 @@ import 'package:flame/game.dart'; import 'package:flame_lottie/flame_lottie.dart'; -class LottieAnimationExample extends FlameGame { +class LottieAnimationExample() extends FlameGame { static const String description = ''' This example shows how to load a Lottie animation. It is configured to continuously loop the animation and restart once its done. diff --git a/examples/lib/stories/bridge_libraries/flame_spine/basic_spine_example.dart b/examples/lib/stories/bridge_libraries/flame_spine/basic_spine_example.dart index a214b5e0c3e..0eba82dc38f 100644 --- a/examples/lib/stories/bridge_libraries/flame_spine/basic_spine_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_spine/basic_spine_example.dart @@ -3,7 +3,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame_spine/flame_spine.dart'; -class FlameSpineExample extends FlameGame with TapCallbacks { +class FlameSpineExample() extends FlameGame with TapCallbacks { static const String description = ''' This example shows how to load a Spine animation. Tap on the screen to try different states of the animation. diff --git a/examples/lib/stories/bridge_libraries/flame_spine/shared_data_spine_example.dart b/examples/lib/stories/bridge_libraries/flame_spine/shared_data_spine_example.dart index dd7c53d3fc9..d2213012af4 100644 --- a/examples/lib/stories/bridge_libraries/flame_spine/shared_data_spine_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_spine/shared_data_spine_example.dart @@ -4,7 +4,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame_spine/flame_spine.dart'; -class SharedDataSpineExample extends FlameGame with TapCallbacks { +class SharedDataSpineExample() extends FlameGame with TapCallbacks { static const String description = ''' This example shows how to preload assets and share data between Spine components. diff --git a/examples/lib/stories/camera_and_viewport/camera_component_example.dart b/examples/lib/stories/camera_and_viewport/camera_component_example.dart index b6aa7c49547..7e28bf14c56 100644 --- a/examples/lib/stories/camera_and_viewport/camera_component_example.dart +++ b/examples/lib/stories/camera_and_viewport/camera_component_example.dart @@ -8,7 +8,7 @@ import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:flutter/painting.dart'; -class CameraComponentExample extends FlameGame with DragCallbacks { +class CameraComponentExample() extends FlameGame with DragCallbacks { static const description = ''' This example shows how a camera can be dynamically added into a game using a CameraComponent. @@ -17,7 +17,7 @@ class CameraComponentExample extends FlameGame with DragCallbacks { look at the world underneath! '''; - CameraComponentExample() : super(world: AntWorld()); + this : super(world: AntWorld()); late final CameraComponent magnifyingGlass; late final Vector2 center; @@ -79,14 +79,13 @@ class CameraComponentExample extends FlameGame with DragCallbacks { } } -class Bezel extends PositionComponent { - Bezel(this.radius) +class Bezel(final double radius) extends PositionComponent { + this : super( size: Vector2.all(2 * radius), position: Vector2.all(radius), ); - final double radius; late final Path rim; late final Path rimBorder; late final Path handle; @@ -164,7 +163,7 @@ class Bezel extends PositionComponent { } } -class AntWorld extends World { +class AntWorld() extends World { late final DragonCurve curve; late final Rect bgRect; final Paint bgPaint = Paint()..color = const Color(0xffeeeeee); @@ -196,7 +195,7 @@ class AntWorld extends World { } } -class DragonCurve extends PositionComponent { +class DragonCurve() extends PositionComponent { late final Paint borderPaint; late final Paint mainPaint; late final Path dragon; @@ -260,8 +259,8 @@ class DragonCurve extends PositionComponent { } } -class Ant extends PositionComponent { - Ant() : random = Random() { +class Ant() extends PositionComponent { + this : random = Random() { size = Vector2(2, 5); anchor = const Anchor(0.5, 0.4); } @@ -481,39 +480,29 @@ class Ant extends PositionComponent { } } -class InsectLeg { - InsectLeg( - this.x0, - this.y0, - this.x1, - this.y1, - this.l1, - this.l2, - this.l3, { - required bool mirrorBendDirection, - }) : dir = mirrorBendDirection ? -1 : 1, - path = Path(), - foot = Vector2.zero() { - final ok = placeFoot(Vector2(x1, y1)); - assert(ok, 'The foot was not properly placed'); - } - +class InsectLeg( /// Place where the leg is attached to the body - final double x0; - final double y0; + final double x0, + final double y0, /// Place on the ground where the ant needs to place its foot - final double x1; - final double y1; + final double x1, + final double y1, /// Lengths of the 3 segments of the leg: [l1] is nearest to the body, [l2] /// is the middle part, and [l3] is the "foot". - final double l1; - final double l2; - final double l3; + final double l1, + final double l2, + final double l3, { + required bool mirrorBendDirection, +}) { + this : path = Path(), foot = Vector2.zero() { + final ok = placeFoot(Vector2(x1, y1)); + assert(ok, 'The foot was not properly placed'); + } /// +1 if the leg bends "forward", or -1 if backwards - final double dir; + final double dir = mirrorBendDirection ? -1 : 1; /// The leg is drawn as a simple [path] polyline consisting of 3 segments. final Path path; diff --git a/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart b/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart index 545b082660a..1c44cb28a6f 100644 --- a/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart +++ b/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart @@ -5,7 +5,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class CameraComponentPropertiesExample extends FlameGame { +class CameraComponentPropertiesExample() extends FlameGame { static const description = ''' This example uses FixedSizeViewport which is dynamically sized and positioned based on the size of the game widget. @@ -21,7 +21,7 @@ class CameraComponentPropertiesExample extends FlameGame { Click at any point within the viewport to create a circle there. '''; - CameraComponentPropertiesExample() + this : super( camera: CameraComponent( @@ -75,7 +75,7 @@ class CameraComponentPropertiesExample extends FlameGame { } } -class ViewportFrame extends Component { +class ViewportFrame() extends Component { final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 3 @@ -94,7 +94,7 @@ class ViewportFrame extends Component { } } -class Background extends Component with TapCallbacks { +class Background() extends Component with TapCallbacks { final bgPaint = Paint()..color = const Color(0xffff0000); final originPaint = Paint()..color = const Color(0xff19bf57); final axisPaint = Paint() @@ -127,8 +127,8 @@ class Background extends Component with TapCallbacks { } } -class ExpandingCircle extends CircleComponent { - ExpandingCircle(Offset center) +class ExpandingCircle(Offset center) extends CircleComponent { + this : super( position: Vector2(center.dx, center.dy), anchor: Anchor.center, diff --git a/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart b/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart index ec1382b8b30..92e3a11c1ab 100644 --- a/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart +++ b/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart @@ -7,7 +7,8 @@ import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flutter/services.dart'; -class CameraFollowAndWorldBoundsExample extends FlameGame +class CameraFollowAndWorldBoundsExample() + extends FlameGame with HasKeyboardHandlerComponents { static const description = ''' This example demonstrates camera following the player, but also obeying the @@ -30,8 +31,8 @@ class CameraFollowAndWorldBoundsExample extends FlameGame } } -class Ground extends PositionComponent { - Ground() : pebbles = [], super(size: Vector2(1000, 30)) { +class Ground() extends PositionComponent { + this : pebbles = [], super(size: Vector2(1000, 30)) { final random = Random(); for (var i = 0; i < 25; i++) { pebbles.add( @@ -63,8 +64,8 @@ class Ground extends PositionComponent { } } -class Player extends PositionComponent with KeyboardHandler { - Player() +class Player() extends PositionComponent with KeyboardHandler { + this : body = Path() ..moveTo(10, 0) ..cubicTo(17, 0, 28, 20, 10, 20) diff --git a/examples/lib/stories/camera_and_viewport/coordinate_systems_example.dart b/examples/lib/stories/camera_and_viewport/coordinate_systems_example.dart index 7a75ec177e3..e92f3520fe4 100644 --- a/examples/lib/stories/camera_and_viewport/coordinate_systems_example.dart +++ b/examples/lib/stories/camera_and_viewport/coordinate_systems_example.dart @@ -11,7 +11,8 @@ import 'package:material_ui/material_ui.dart'; /// A game that allows for camera control and displays Tap, Drag & Scroll /// events information on the screen, to allow exploration of the 3 coordinate /// systems of Flame (global, widget, game). -class CoordinateSystemsExample extends FlameGame +class CoordinateSystemsExample() + extends FlameGame with TapCallbacks, DragCallbacks, ScrollCallbacks, KeyboardEvents { static const String description = ''' Displays event data in all 3 coordinate systems (global, widget and game). @@ -189,16 +190,14 @@ class CoordinateSystemsExample extends FlameGame /// A simple widget that "wraps" a Flame game with some Containers /// on each direction (top, bottom, left and right) and allow adding /// or removing containers. -class CoordinateSystemsWidget extends StatefulWidget { - const CoordinateSystemsWidget({super.key}); - +class const CoordinateSystemsWidget({super.key}) extends StatefulWidget { @override State createState() { return _CoordinateSystemsState(); } } -class _CoordinateSystemsState extends State { +class _CoordinateSystemsState() extends State { /// The number of blocks in each direction (top, left, right, bottom). List blocks = [1, 1, 1, 1]; diff --git a/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart b/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart index 706f64692a7..16b7196877d 100644 --- a/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart +++ b/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart @@ -6,7 +6,7 @@ import 'package:flame/palette.dart'; import 'package:flame/text.dart'; import 'package:material_ui/material_ui.dart'; -class FixedResolutionExample extends FlameGame with ScrollCallbacks { +class FixedResolutionExample() extends FlameGame with ScrollCallbacks { static const description = ''' This example shows how to create a viewport with a fixed resolution. It is useful when you want the visible part of the game to be the same on @@ -20,7 +20,7 @@ class FixedResolutionExample extends FlameGame with ScrollCallbacks { static const zoomPerScrollUnit = 0.05; - FixedResolutionExample() + this : super( camera: CameraComponent.withFixedResolution(width: 600, height: 1024), world: FixedResolutionWorld(), @@ -64,7 +64,8 @@ class FixedResolutionExample extends FlameGame with ScrollCallbacks { } } -class FixedResolutionWorld extends World +class FixedResolutionWorld() + extends World with HasGameRef, TapCallbacks, DoubleTapCallbacks { final red = BasicPalette.red.paint(); @@ -101,14 +102,14 @@ class FixedResolutionWorld extends World } } -class Background extends PositionComponent { +class Background() extends PositionComponent { @override int priority = -1; late Paint white; late final Rect hugeRect; - Background() : super(size: Vector2.all(100000), anchor: Anchor.center); + this : super(size: Vector2.all(100000), anchor: Anchor.center); @override Future onLoad() async { @@ -122,32 +123,33 @@ class Background extends PositionComponent { } } -class TextButton extends ButtonComponent { - TextButton({ - required String text, - required super.position, - super.anchor, - TextRenderer? textRenderer, - }) : super( - button: RectangleComponent( - size: Vector2(200, 100), - paint: Paint() - ..color = Colors.orange - ..strokeWidth = 2 - ..style = PaintingStyle.stroke, - ), - buttonDown: RectangleComponent( - size: Vector2(200, 100), - paint: Paint() - ..color = BasicPalette.orange.color.withValues(alpha: 0.5), - ), - children: [ - TextComponent( - text: text, - textRenderer: textRenderer, - position: Vector2(100, 50), - anchor: Anchor.center, - ), - ], - ); +class TextButton({ + required String text, + required super.position, + super.anchor, + TextRenderer? textRenderer, +}) extends ButtonComponent { + this + : super( + button: RectangleComponent( + size: Vector2(200, 100), + paint: Paint() + ..color = Colors.orange + ..strokeWidth = 2 + ..style = PaintingStyle.stroke, + ), + buttonDown: RectangleComponent( + size: Vector2(200, 100), + paint: Paint() + ..color = BasicPalette.orange.color.withValues(alpha: 0.5), + ), + children: [ + TextComponent( + text: text, + textRenderer: textRenderer, + position: Vector2(100, 50), + anchor: Anchor.center, + ), + ], + ); } diff --git a/examples/lib/stories/camera_and_viewport/follow_component_example.dart b/examples/lib/stories/camera_and_viewport/follow_component_example.dart index 7b922022cbd..10c7eec9d1a 100644 --- a/examples/lib/stories/camera_and_viewport/follow_component_example.dart +++ b/examples/lib/stories/camera_and_viewport/follow_component_example.dart @@ -12,7 +12,8 @@ import 'package:flame/input.dart'; import 'package:flutter/services.dart'; import 'package:material_ui/material_ui.dart'; -class FollowComponentExample extends FlameGame +class FollowComponentExample({required final Vector2 viewportResolution}) + extends FlameGame with HasCollisionDetection, HasKeyboardHandlerComponents { static const String description = ''' Move around with W, A, S, D and notice how the camera follows the ember @@ -23,7 +24,7 @@ class FollowComponentExample extends FlameGame respects the camera transformation. '''; - FollowComponentExample({required this.viewportResolution}) + this : super( camera: CameraComponent.withFixedResolution( width: viewportResolution.x, @@ -32,8 +33,6 @@ class FollowComponentExample extends FlameGame ); late MovableEmber ember; - final Vector2 viewportResolution; - @override Future onLoad() async { world.add(Map()); @@ -47,7 +46,8 @@ class FollowComponentExample extends FlameGame } } -class MovableEmber extends Ember +class MovableEmber() + extends Ember with CollisionCallbacks, KeyboardHandler { static const double speed = 300; static final TextPaint textRenderer = TextPaint( @@ -60,7 +60,7 @@ class MovableEmber extends Ember late final maxPosition = Vector2.all(Map.size - size.x / 2); late final minPosition = -maxPosition; - MovableEmber() : super(priority: 2); + this : super(priority: 2); @override Future onLoad() async { @@ -132,7 +132,7 @@ class MovableEmber extends Ember } } -class Map extends Component { +class Map() extends Component { static const double size = 1500; static const Rect _bounds = Rect.fromLTRB(-size, -size, size, size); static final Rectangle bounds = Rectangle.fromLTRB(-size, -size, size, size); @@ -148,7 +148,7 @@ class Map extends Component { late final List _paintPool; late final List _rectPool; - Map() : super(priority: 0) { + this : super(priority: 0) { _paintPool = List.generate( (size / 50).ceil(), (_) => PaintExtension.random(rng: _rng) @@ -180,8 +180,10 @@ class Map extends Component { } } -class Rock extends SpriteComponent with HasGameRef, TapCallbacks { - Rock(Vector2 position) +class Rock(Vector2 position) + extends SpriteComponent + with HasGameRef, TapCallbacks { + this : super( position: position, size: Vector2.all(50), diff --git a/examples/lib/stories/camera_and_viewport/static_components_example.dart b/examples/lib/stories/camera_and_viewport/static_components_example.dart index 8ea9286d466..e1d17ef3fed 100644 --- a/examples/lib/stories/camera_and_viewport/static_components_example.dart +++ b/examples/lib/stories/camera_and_viewport/static_components_example.dart @@ -7,7 +7,9 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; -class StaticComponentsExample extends FlameGame with ScrollCallbacks { +class StaticComponentsExample({ + required Vector2 viewportResolution, +}) extends FlameGame with ScrollCallbacks { static const description = ''' This example shows a parallax which is attached to the viewport (behind the world), four Flame logos that are added to the world, and a player added to @@ -22,15 +24,14 @@ class StaticComponentsExample extends FlameGame with ScrollCallbacks { late final ParallaxComponent myParallax; - StaticComponentsExample({ - required Vector2 viewportResolution, - }) : super( - camera: CameraComponent.withFixedResolution( - width: viewportResolution.x, - height: viewportResolution.y, - ), - world: _StaticComponentWorld(), - ); + this + : super( + camera: CameraComponent.withFixedResolution( + width: viewportResolution.x, + height: viewportResolution.y, + ), + world: _StaticComponentWorld(), + ); @override void onScroll(ScrollEvent event) { @@ -66,7 +67,8 @@ class StaticComponentsExample extends FlameGame with ScrollCallbacks { } } -class _StaticComponentWorld extends World +class _StaticComponentWorld() + extends World with HasGameRef, TapCallbacks, DoubleTapCallbacks { late SpriteComponent player; @override @@ -124,7 +126,7 @@ class _StaticComponentWorld extends World } } -class MyParallaxComponent extends ParallaxComponent { +class MyParallaxComponent() extends ParallaxComponent { @override Future onLoad() async { parallax = await gameRef.loadParallax( diff --git a/examples/lib/stories/camera_and_viewport/zoom_example.dart b/examples/lib/stories/camera_and_viewport/zoom_example.dart index b8d0306ee29..0561a0ba8e7 100644 --- a/examples/lib/stories/camera_and_viewport/zoom_example.dart +++ b/examples/lib/stories/camera_and_viewport/zoom_example.dart @@ -2,7 +2,8 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class ZoomExample extends FlameGame +class ZoomExample() + extends FlameGame with ScrollCallbacks, ScaleCallbacks, DragCallbacks { static const String description = ''' On web: use scroll to zoom in and out.\n diff --git a/examples/lib/stories/collision_detection/bouncing_ball_example.dart b/examples/lib/stories/collision_detection/bouncing_ball_example.dart index b7b20a18844..f4ca4c4edd9 100644 --- a/examples/lib/stories/collision_detection/bouncing_ball_example.dart +++ b/examples/lib/stories/collision_detection/bouncing_ball_example.dart @@ -6,7 +6,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class BouncingBallExample extends FlameGame with HasCollisionDetection { +class BouncingBallExample() extends FlameGame with HasCollisionDetection { static const description = ''' This example shows how you can use the Collisions detection api to know when a ball collides with the screen boundaries and then update it to bounce off these boundaries. @@ -20,11 +20,12 @@ class BouncingBallExample extends FlameGame with HasCollisionDetection { } } -class Ball extends CircleComponent +class Ball() + extends CircleComponent with HasGameRef, CollisionCallbacks { late Vector2 velocity; - Ball() { + this { paint = Paint()..color = Colors.white; radius = 10; } @@ -83,21 +84,17 @@ class Ball extends CircleComponent // Left Side Collision if (collisionPoint.x == 0) { velocity.x = -velocity.x; - velocity.y = velocity.y; } // Right Side Collision if (collisionPoint.x == gameRef.size.x) { velocity.x = -velocity.x; - velocity.y = velocity.y; } // Top Side Collision if (collisionPoint.y == 0) { - velocity.x = velocity.x; velocity.y = -velocity.y; } // Bottom Side Collision if (collisionPoint.y == gameRef.size.y) { - velocity.x = velocity.x; velocity.y = -velocity.y; } } diff --git a/examples/lib/stories/collision_detection/circles_example.dart b/examples/lib/stories/collision_detection/circles_example.dart index 691485c6679..f48793b6e19 100644 --- a/examples/lib/stories/collision_detection/circles_example.dart +++ b/examples/lib/stories/collision_detection/circles_example.dart @@ -2,24 +2,24 @@ import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Draggable; +import 'package:material_ui/material_ui.dart' hide Draggable, Image; -class CirclesExample extends FlameGame { +class CirclesExample() extends FlameGame { static const description = ''' This example will create a circle every time you tap on the screen. It will have the initial velocity towards the center of the screen and if it touches another circle both of them will change color. '''; - CirclesExample() + this : super( camera: CameraComponent.withFixedResolution(width: 600, height: 400), world: MyWorld(), ); } -class MyWorld extends World with TapCallbacks, HasCollisionDetection { - MyWorld() : super(children: [ScreenHitbox()..debugMode = true]); +class MyWorld() extends World with TapCallbacks, HasCollisionDetection { + this : super(children: [ScreenHitbox()..debugMode = true]); @override void onTapDown(TapDownEvent info) { @@ -27,10 +27,10 @@ class MyWorld extends World with TapCallbacks, HasCollisionDetection { } } -class MyCollidable extends PositionComponent +class MyCollidable({super.position}) + extends PositionComponent with HasGameRef, CollisionCallbacks { - MyCollidable({super.position}) - : super(size: Vector2.all(30), anchor: Anchor.center); + this : super(size: Vector2.all(30), anchor: Anchor.center); late Vector2 velocity; final _collisionColor = Colors.amber; diff --git a/examples/lib/stories/collision_detection/collidable_animation_example.dart b/examples/lib/stories/collision_detection/collidable_animation_example.dart index a8ac3e8c3b8..9021c60afd6 100644 --- a/examples/lib/stories/collision_detection/collidable_animation_example.dart +++ b/examples/lib/stories/collision_detection/collidable_animation_example.dart @@ -6,7 +6,9 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/palette.dart'; -class CollidableAnimationExample extends FlameGame with HasCollisionDetection { +class CollidableAnimationExample() + extends FlameGame + with HasCollisionDetection { static const description = ''' In this example you can see four animated birds which are flying straight along the same route until they hit either another bird or the wall, which @@ -52,21 +54,19 @@ class CollidableAnimationExample extends FlameGame with HasCollisionDetection { } } -class AnimatedComponent extends SpriteAnimationComponent - with CollisionCallbacks, HasGameRef { - final Vector2 velocity; - - AnimatedComponent( - this.velocity, - Vector2 position, - Vector2 size, { - double angle = -pi / 4, - }) : super( - position: position, - size: size, - angle: angle, - anchor: Anchor.center, - ); +class AnimatedComponent( + final Vector2 velocity, + Vector2 position, + Vector2 size, { + double angle = -pi / 4, +}) extends SpriteAnimationComponent with CollisionCallbacks, HasGameRef { + this + : super( + position: position, + size: size, + angle: angle, + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/examples/lib/stories/collision_detection/multiple_shapes_example.dart b/examples/lib/stories/collision_detection/multiple_shapes_example.dart index 846c8a19a2b..1e97459aae4 100644 --- a/examples/lib/stories/collision_detection/multiple_shapes_example.dart +++ b/examples/lib/stories/collision_detection/multiple_shapes_example.dart @@ -7,11 +7,16 @@ import 'package:flame/events.dart'; import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flame/palette.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Draggable; +import 'package:material_ui/material_ui.dart' hide Draggable, Image; -enum Shapes { circle, rectangle, polygon, path } +enum Shapes() { + circle, + rectangle, + polygon, + path, +} -class MultipleShapesExample extends FlameGame with HasCollisionDetection { +class MultipleShapesExample() extends FlameGame with HasCollisionDetection { static const description = ''' An example with many hitboxes that move around on the screen and during collisions they change color depending on what it is that they have collided @@ -25,14 +30,14 @@ class MultipleShapesExample extends FlameGame with HasCollisionDetection { any direction. '''; - MultipleShapesExample() + this : super( world: MultiShapesWorld(), camera: CameraComponent()..viewfinder.anchor = Anchor.topLeft, ); } -class MultiShapesWorld extends World with HasGameRef { +class MultiShapesWorld() extends World with HasGameRef { @override Future onLoad() async { await super.onLoad(); @@ -91,10 +96,14 @@ class MultiShapesWorld extends World with HasGameRef { } } -abstract class MyCollidable extends PositionComponent +abstract class MyCollidable( + Vector2 position, + Vector2 size, + final Vector2 velocity, + final ScreenHitbox screenHitbox, +) extends PositionComponent with DragCallbacks, CollisionCallbacks, GestureHitboxes { double rotationSpeed = 0.0; - final Vector2 velocity; final delta = Vector2.zero(); double angleDelta = 0; final Color defaultColor = Colors.blue.withValues(alpha: 0.8); @@ -102,15 +111,9 @@ abstract class MyCollidable extends PositionComponent final Color screenColor = Colors.purple.withValues(alpha: 0.8); late final Paint dragIndicatorPaint; - final ScreenHitbox screenHitbox; ShapeHitbox? hitbox; - MyCollidable( - Vector2 position, - Vector2 size, - this.velocity, - this.screenHitbox, - ) : super(position: position, size: size, anchor: Anchor.center) { + this : super(position: position, size: size, anchor: Anchor.center) { dragIndicatorPaint = BasicPalette.white.paint(); } @@ -173,13 +176,13 @@ abstract class MyCollidable extends PositionComponent } } -class CollidablePolygon extends MyCollidable { - CollidablePolygon( - Vector2 position, - Vector2 size, - Vector2 velocity, - ScreenHitbox screenHitbox, - ) : super(position, size, velocity, screenHitbox) { +class CollidablePolygon( + Vector2 position, + Vector2 size, + Vector2 velocity, + ScreenHitbox screenHitbox, +) extends MyCollidable { + this : super(position, size, velocity, screenHitbox) { hitbox = PolygonHitbox.relative( [ Vector2(-1.0, 0.0), @@ -197,13 +200,13 @@ class CollidablePolygon extends MyCollidable { } } -class CollidablePath extends MyCollidable { - CollidablePath( - super.position, - super.size, - super.velocity, - super.screenHitbox, - ) { +class CollidablePath( + super.position, + super.size, + super.velocity, + super.screenHitbox, +) extends MyCollidable { + this { // The path keeps its aspect ratio within the size, so the hitbox is // centered in the component. hitbox = PathHitbox( @@ -215,36 +218,34 @@ class CollidablePath extends MyCollidable { } } -class CollidableRectangle extends MyCollidable { - CollidableRectangle( - super.position, - super.size, - super.velocity, - super.screenHitbox, - ) { +class CollidableRectangle( + super.position, + super.size, + super.velocity, + super.screenHitbox, +) extends MyCollidable { + this { hitbox = RectangleHitbox()..renderShape = true; add(hitbox!); } } -class CollidableCircle extends MyCollidable { - CollidableCircle( - super.position, - super.size, - super.velocity, - super.screenHitbox, - ) { +class CollidableCircle( + super.position, + super.size, + super.velocity, + super.screenHitbox, +) extends MyCollidable { + this { hitbox = CircleHitbox()..renderShape = true; add(hitbox!); } } -class SnowmanPart extends CircleHitbox { +class SnowmanPart(double radius, Vector2 position, final Color hitColor) + extends CircleHitbox { final startColor = Colors.white.withValues(alpha: 0.8); - final Color hitColor; - - SnowmanPart(double radius, Vector2 position, this.hitColor) - : super(radius: radius, position: position, anchor: Anchor.center) { + this : super(radius: radius, position: position, anchor: Anchor.center) { paint.color = startColor; renderShape = true; } @@ -269,13 +270,13 @@ class SnowmanPart extends CircleHitbox { } } -class CollidableSnowman extends MyCollidable { - CollidableSnowman( - Vector2 position, - Vector2 size, - Vector2 velocity, - ScreenHitbox screenHitbox, - ) : super(position, size, velocity, screenHitbox) { +class CollidableSnowman( + Vector2 position, + Vector2 size, + Vector2 velocity, + ScreenHitbox screenHitbox, +) extends MyCollidable { + this : super(position, size, velocity, screenHitbox) { rotationSpeed = 0.3; anchor = Anchor.topLeft; final top = SnowmanPart( diff --git a/examples/lib/stories/collision_detection/multiple_worlds_example.dart b/examples/lib/stories/collision_detection/multiple_worlds_example.dart index d511850fda6..349aecb3ec5 100644 --- a/examples/lib/stories/collision_detection/multiple_worlds_example.dart +++ b/examples/lib/stories/collision_detection/multiple_worlds_example.dart @@ -7,7 +7,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class MultipleWorldsExample extends FlameGame { +class MultipleWorldsExample() extends FlameGame { static const description = ''' This example shows how multiple worlds can have discrete collision detection. @@ -34,11 +34,9 @@ class MultipleWorldsExample extends FlameGame { } } -class CollisionDetectionWorld extends World with HasCollisionDetection {} - -class CollidableEmber extends Ember with CollisionCallbacks { - CollidableEmber({super.position}); +class CollisionDetectionWorld() extends World with HasCollisionDetection; +class CollidableEmber({super.position}) extends Ember with CollisionCallbacks { static final Random _rng = Random(); int get index => (position.x.isNegative ? 1 : 0) + (position.y.isNegative ? 2 : 0); diff --git a/examples/lib/stories/collision_detection/quadtree_example.dart b/examples/lib/stories/collision_detection/quadtree_example.dart index 2375569a49f..fe7bc6449c0 100644 --- a/examples/lib/stories/collision_detection/quadtree_example.dart +++ b/examples/lib/stories/collision_detection/quadtree_example.dart @@ -8,14 +8,13 @@ import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame/layers.dart'; import 'package:flutter/services.dart'; -import 'package:material_ui/material_ui.dart' hide Image, Draggable; +import 'package:material_ui/material_ui.dart' hide Draggable, Image; const tileSize = 8.0; -class QuadTreeExample extends FlameGame +class QuadTreeExample() + extends FlameGame with HasQuadTreeCollisionDetection, KeyboardEvents, ScrollCallbacks { - QuadTreeExample(); - static const description = ''' In this example the standard "Sweep and Prune" algorithm is replaced by "Quad Tree". Quad Tree is often a more efficient approach of handling collisions, @@ -199,14 +198,12 @@ Press T button to toggle player to collide with other objects. //#region Player -class Player extends SpriteComponent +class Player({ + required super.position, + required super.size, + required super.priority, +}) extends SpriteComponent with CollisionCallbacks, HasGameRef { - Player({ - required super.position, - required super.size, - required super.priority, - }); - bool canMoveLeft = true; bool canMoveRight = true; bool canMoveTop = true; @@ -263,16 +260,16 @@ class Player extends SpriteComponent } } -class Bullet extends PositionComponent with CollisionCallbacks, HasPaint { - Bullet({required super.position, required this.displacement}) { +class Bullet({required super.position, required final Vector2 displacement}) + extends PositionComponent + with CollisionCallbacks, HasPaint { + this { paint.color = Colors.deepOrange; priority = 10; size = Vector2.all(1); add(RectangleHitbox()); } - final Vector2 displacement; - @override void render(Canvas canvas) { canvas.drawCircle(Offset.zero, 1, paint); @@ -309,14 +306,14 @@ class Bullet extends PositionComponent with CollisionCallbacks, HasPaint { //#region Environment -class Brick extends SpriteComponent +class Brick({ + required super.position, + required super.size, + required super.priority, + required super.sprite, +}) extends SpriteComponent with CollisionCallbacks, GameCollidable, CustomTraversal, UpdateOnce { - Brick({ - required super.position, - required super.size, - required super.priority, - required super.sprite, - }) { + this { initCenter(); initCollision(); } @@ -331,14 +328,14 @@ class Brick extends SpriteComponent } } -class Water extends SpriteComponent +class Water({ + required super.position, + required super.size, + required super.priority, + required super.sprite, +}) extends SpriteComponent with CollisionCallbacks, GameCollidable, CustomTraversal, UpdateOnce { - Water({ - required super.position, - required super.size, - required super.priority, - required super.sprite, - }) { + this { initCenter(); initCollision(); } @@ -375,9 +372,7 @@ mixin UpdateOnce on CustomTraversal { } } -class StaticLayer extends PreRenderedLayer { - StaticLayer(); - +class StaticLayer() extends PreRenderedLayer { List components = []; @override @@ -392,19 +387,17 @@ class StaticLayer extends PreRenderedLayer { } } -class LayerComponent extends PositionComponent { - LayerComponent(this.layer); - - StaticLayer layer; - +class LayerComponent(var StaticLayer layer) extends PositionComponent { @override void render(Canvas canvas) { layer.render(canvas); } } -class QuadTreeDebugComponent extends PositionComponent with HasPaint { - QuadTreeDebugComponent(QuadTreeCollisionDetection cd) { +class QuadTreeDebugComponent(QuadTreeCollisionDetection cd) + extends PositionComponent + with HasPaint { + this { dbg = QuadTreeNodeDebugInfo.init(cd); paint.color = Colors.blue; paint.style = PaintingStyle.stroke; diff --git a/examples/lib/stories/collision_detection/raycast_example.dart b/examples/lib/stories/collision_detection/raycast_example.dart index 67e880b9b14..c2e370761d5 100644 --- a/examples/lib/stories/collision_detection/raycast_example.dart +++ b/examples/lib/stories/collision_detection/raycast_example.dart @@ -7,7 +7,8 @@ import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class RaycastExample extends FlameGame +class RaycastExample() + extends FlameGame with HasCollisionDetection, PathsCreationMixin { static const description = ''' In this example the raycast functionality is showcased. The circle moves around diff --git a/examples/lib/stories/collision_detection/raycast_light_example.dart b/examples/lib/stories/collision_detection/raycast_light_example.dart index 0d3b14b4919..18d09a5e8d3 100644 --- a/examples/lib/stories/collision_detection/raycast_light_example.dart +++ b/examples/lib/stories/collision_detection/raycast_light_example.dart @@ -9,7 +9,8 @@ import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class RaycastLightExample extends FlameGame +class RaycastLightExample() + extends FlameGame with HasCollisionDetection, TapCallbacks, diff --git a/examples/lib/stories/collision_detection/raycast_max_distance_example.dart b/examples/lib/stories/collision_detection/raycast_max_distance_example.dart index dfcafae21df..a90f056b5a9 100644 --- a/examples/lib/stories/collision_detection/raycast_max_distance_example.dart +++ b/examples/lib/stories/collision_detection/raycast_max_distance_example.dart @@ -12,7 +12,7 @@ import 'package:flame_noise/flame_noise.dart'; import 'package:flame_test/test_paths.dart'; import 'package:material_ui/material_ui.dart'; -class RaycastMaxDistanceExample extends FlameGame with HasCollisionDetection { +class RaycastMaxDistanceExample() extends FlameGame with HasCollisionDetection { static const description = ''' This examples showcases how raycast APIs can be used to detect hits within certain range. '''; @@ -107,11 +107,11 @@ This examples showcases how raycast APIs can be used to detect hits within certa } } -class _Character extends PositionComponent { - _Character({required this.maxDistance, super.position, super.anchor}); - - final double maxDistance; - +class _Character({ + required final double maxDistance, + super.position, + super.anchor, +}) extends PositionComponent { final _rayOriginPoint = Offset.zero; late final _rayEndPoint = Offset(maxDistance, 0); final _rayPaint = BasicPalette.gray.paint(); diff --git a/examples/lib/stories/collision_detection/rays_in_shape_example.dart b/examples/lib/stories/collision_detection/rays_in_shape_example.dart index 8d3db4837db..ff41feccafb 100644 --- a/examples/lib/stories/collision_detection/rays_in_shape_example.dart +++ b/examples/lib/stories/collision_detection/rays_in_shape_example.dart @@ -21,7 +21,7 @@ const fontSize = 9.0; typedef ButtonColors = (Color, Color); -class RaysInShapeExample extends FlameGame { +class RaysInShapeExample() extends FlameGame { static const description = ''' In this example we showcase the raytrace functionality where you can see whether the rays are inside the shapes or not. The rays originate from small circles, @@ -52,7 +52,7 @@ casts a new set of rays and the Rotate button rotates the shape. late AdvancedButtonComponent _shapeButton; late AdvancedButtonComponent _raysButton; - RaysInShapeExample() + this : super( world: RaysInShapeWorld(), camera: CameraComponent.withFixedResolution( @@ -148,26 +148,24 @@ casts a new set of rays and the Rotate button rotates the shape. } } -class RayCircleComponent extends CircleComponent +class RayCircleComponent( + final Ray2 ray, { + super.radius, + super.position, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.paint, + super.paintLayers, + super.key, +}) extends CircleComponent with DragCallbacks, HoverCallbacks, TapCallbacks, HasWorldRef { - RayCircleComponent( - this.ray, { - super.radius, - super.position, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.paint, - super.paintLayers, - super.key, - }); - RaycastResult? _raycastResult; bool get _hitScreen { final hitbox = _raycastResult?.hitbox; @@ -211,7 +209,7 @@ class RayCircleComponent extends CircleComponent @override void onMouseMove(MouseMoveEvent event) { - if (worldRef.hasHovering == false || worldRef.isHovering(this)) { + if (!worldRef.hasHovering || worldRef.isHovering(this)) { super.onMouseMove(event); } } @@ -322,8 +320,6 @@ class RayCircleComponent extends CircleComponent } } - final Ray2 ray; - bool get isDragging => _isDragging || isDragged; bool get isHovering => _isHovering || isHovered; @@ -339,7 +335,8 @@ class RayCircleComponent extends CircleComponent } } -class RaysInShapeWorld extends World +class RaysInShapeWorld() + extends World with HasGameRef, HasCollisionDetection { final _rng = Random(); List _rays = []; diff --git a/examples/lib/stories/collision_detection/raytrace_example.dart b/examples/lib/stories/collision_detection/raytrace_example.dart index c04751ffb95..983cb6002f4 100644 --- a/examples/lib/stories/collision_detection/raytrace_example.dart +++ b/examples/lib/stories/collision_detection/raytrace_example.dart @@ -10,7 +10,8 @@ import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class RaytraceExample extends FlameGame +class RaytraceExample() + extends FlameGame with HasCollisionDetection, MouseMoveCallbacks, TapCallbacks { static const description = ''' In this example the raytrace functionality is showcased. diff --git a/examples/lib/stories/components/clip_component_example.dart b/examples/lib/stories/components/clip_component_example.dart index 3a3773e1661..68e11dd8d17 100644 --- a/examples/lib/stories/components/clip_component_example.dart +++ b/examples/lib/stories/components/clip_component_example.dart @@ -3,9 +3,10 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class TappableEmber extends Ember with TapCallbacks { - TappableEmber({required Vector2 position, required Vector2 size}) - : super(position: position, size: size); +class TappableEmber({required Vector2 position, required Vector2 size}) + extends Ember + with TapCallbacks { + this : super(position: position, size: size); @override bool onTapDown(TapDownEvent event) { @@ -14,9 +15,8 @@ class TappableEmber extends Ember with TapCallbacks { } } -class ClipComponentExample extends FlameGame { - static const String description = - '''Tap on the objects to increase their size and see how the clip component +class ClipComponentExample() extends FlameGame { + static const String description = '''Tap on the objects to increase their size and see how the clip component works.'''; late final _embers = [ diff --git a/examples/lib/stories/components/component_pool_example.dart b/examples/lib/stories/components/component_pool_example.dart index d561c6eca6e..fe32443d2af 100644 --- a/examples/lib/stories/components/component_pool_example.dart +++ b/examples/lib/stories/components/component_pool_example.dart @@ -5,7 +5,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class ComponentPoolExample extends FlameGame { +class ComponentPoolExample() extends FlameGame { static const String description = 'Tap on the screen to spawn a burst of pooled balls. ' 'Watch the stats to see active vs pooled balls and observe ' @@ -14,7 +14,7 @@ class ComponentPoolExample extends FlameGame { static const gameWidth = 800.0; static const gameHeight = 600.0; - ComponentPoolExample() + this : super( world: _BallWorld(), camera: CameraComponent.withFixedResolution( @@ -26,7 +26,7 @@ class ComponentPoolExample extends FlameGame { } } -class _BallWorld extends World with TapCallbacks { +class _BallWorld() extends World with TapCallbacks { late final ComponentPool<_PooledBall> ballPool; late final _StatsDisplay statsDisplay; final Random _random = Random(); @@ -90,7 +90,8 @@ class _BallWorld extends World with TapCallbacks { /// Uses two child [CircleComponent]s for visuals: a shadow (rendered first via /// lower priority) and the ball itself on top. A bouncing scale effect /// simulates the ball bouncing up and down as it travels outward. -class _PooledBall extends PositionComponent +class _PooledBall() + extends PositionComponent with HasGameRef, ParentIsA<_BallWorld> { static const _radius = 4.0; static const _bounceSpeed = 8.0; @@ -102,7 +103,7 @@ class _PooledBall extends PositionComponent late final CircleComponent _shadow; late final CircleComponent _ball; - _PooledBall() : super(anchor: Anchor.center); + this : super(anchor: Anchor.center); @override Future onLoad() async { @@ -164,11 +165,12 @@ class _PooledBall extends PositionComponent } /// Displays statistics about the ball pool. -class _StatsDisplay extends TextComponent with ParentIsA<_BallWorld> { - final ComponentPool<_PooledBall> pool; +class _StatsDisplay({required final ComponentPool<_PooledBall> pool}) + extends TextComponent + with ParentIsA<_BallWorld> { int _activeBalls = 0; - _StatsDisplay({required this.pool}) + this : super( position: Vector2(10, 10), textRenderer: TextPaint( diff --git a/examples/lib/stories/components/components_notifier_example.dart b/examples/lib/stories/components/components_notifier_example.dart index c30dac0057e..237ac248f91 100644 --- a/examples/lib/stories/components/components_notifier_example.dart +++ b/examples/lib/stories/components/components_notifier_example.dart @@ -4,9 +4,8 @@ import 'package:flame/game.dart'; import 'package:flame/widgets.dart'; import 'package:material_ui/material_ui.dart'; -class ComponentsNotifierExampleWidget extends StatefulWidget { - const ComponentsNotifierExampleWidget({super.key}); - +class const ComponentsNotifierExampleWidget({super.key}) + extends StatefulWidget { static const String description = ''' Showcases how the components notifier can be used between a flame game instance and widgets. @@ -20,7 +19,7 @@ class ComponentsNotifierExampleWidget extends StatefulWidget { _ComponentsNotifierExampleWidgetState(); } -class _ComponentsNotifierExampleWidgetState +class _ComponentsNotifierExampleWidgetState() extends State { @override void initState() { @@ -58,16 +57,11 @@ class _ComponentsNotifierExampleWidgetState } } -class GameHud extends StatelessWidget { - const GameHud({ - required this.remainingEnemies, - required this.onReplay, - super.key, - }); - - final int remainingEnemies; - final VoidCallback onReplay; - +class const GameHud({ + required final int remainingEnemies, + required final VoidCallback onReplay, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return Card( @@ -84,8 +78,10 @@ class GameHud extends StatelessWidget { } } -class Enemy extends CircleComponent with TapCallbacks, Notifier { - Enemy({super.position}) +class Enemy({super.position}) + extends CircleComponent + with TapCallbacks, Notifier { + this : super( radius: 20, paint: Paint()..color = const Color(0xFFFF0000), @@ -97,7 +93,7 @@ class Enemy extends CircleComponent with TapCallbacks, Notifier { } } -class ComponentNotifierExample extends FlameGame { +class ComponentNotifierExample() extends FlameGame { @override Future onLoad() async { replay(); diff --git a/examples/lib/stories/components/components_notifier_provider_example.dart b/examples/lib/stories/components/components_notifier_provider_example.dart index 8a36baa1092..e80b9c93b5a 100644 --- a/examples/lib/stories/components/components_notifier_provider_example.dart +++ b/examples/lib/stories/components/components_notifier_provider_example.dart @@ -4,9 +4,8 @@ import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; import 'package:provider/provider.dart'; -class ComponentsNotifierProviderExampleWidget extends StatefulWidget { - const ComponentsNotifierProviderExampleWidget({super.key}); - +class const ComponentsNotifierProviderExampleWidget({super.key}) + extends StatefulWidget { static const String description = ''' Similar to the Components Notifier example, but uses provider instead of the built in ComponentsNotifierBuilder widget. @@ -17,7 +16,7 @@ class ComponentsNotifierProviderExampleWidget extends StatefulWidget { _ComponentsNotifierProviderExampleWidgetState(); } -class _ComponentsNotifierProviderExampleWidgetState +class _ComponentsNotifierProviderExampleWidgetState() extends State { @override void initState() { @@ -55,9 +54,7 @@ class _ComponentsNotifierProviderExampleWidgetState } } -class GameHud extends StatelessWidget { - const GameHud({super.key}); - +class const GameHud({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { final enemies = context.watch>().components; @@ -78,8 +75,10 @@ class GameHud extends StatelessWidget { } } -class Enemy extends CircleComponent with TapCallbacks, Notifier { - Enemy({super.position}) +class Enemy({super.position}) + extends CircleComponent + with TapCallbacks, Notifier { + this : super( radius: 20, paint: Paint()..color = const Color(0xFFFF0000), @@ -91,7 +90,7 @@ class Enemy extends CircleComponent with TapCallbacks, Notifier { } } -class ComponentNotifierExample extends FlameGame { +class ComponentNotifierExample() extends FlameGame { @override Future onLoad() async { replay(); diff --git a/examples/lib/stories/components/composability_example.dart b/examples/lib/stories/components/composability_example.dart index c3c001c2ac8..94070d68366 100644 --- a/examples/lib/stories/components/composability_example.dart +++ b/examples/lib/stories/components/composability_example.dart @@ -4,7 +4,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/palette.dart'; -class ComposabilityExample extends FlameGame { +class ComposabilityExample() extends FlameGame { static const String description = ''' In this example we showcase how you can add children to a component and how they transform together with their parent, if the parent is a @@ -30,11 +30,13 @@ class ComposabilityExample extends FlameGame { } } -class ParentSquare extends RectangleComponent with HasGameRef { +class ParentSquare(Vector2 position, Vector2 size) + extends RectangleComponent + with HasGameRef { static final defaultPaint = BasicPalette.white.paint() ..style = PaintingStyle.stroke; - ParentSquare(Vector2 position, Vector2 size) + this : super( position: position, size: size, diff --git a/examples/lib/stories/components/debug_example.dart b/examples/lib/stories/components/debug_example.dart index 331b3da6f23..d24eac2dfb8 100644 --- a/examples/lib/stories/components/debug_example.dart +++ b/examples/lib/stories/components/debug_example.dart @@ -1,7 +1,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; -class DebugExample extends FlameGame { +class DebugExample() extends FlameGame { static const String description = ''' In this example we show what you will see when setting `debugMode = true` and add the `FPSTextComponent` to your game. @@ -37,13 +37,15 @@ class DebugExample extends FlameGame { } } -class LogoComponent extends SpriteComponent with HasGameRef { +class LogoComponent(Sprite sprite) + extends SpriteComponent + with HasGameRef { static const int speed = 150; int xDirection = 1; int yDirection = 1; - LogoComponent(Sprite sprite) : super(sprite: sprite, size: sprite.srcSize); + this : super(sprite: sprite, size: sprite.srcSize); @override void update(double dt) { diff --git a/examples/lib/stories/components/has_visibility_example.dart b/examples/lib/stories/components/has_visibility_example.dart index f9dd10bb514..2aada84994c 100644 --- a/examples/lib/stories/components/has_visibility_example.dart +++ b/examples/lib/stories/components/has_visibility_example.dart @@ -3,7 +3,7 @@ import 'dart:async'; import 'package:flame/components.dart' hide Timer; import 'package:flame/game.dart'; -class HasVisibilityExample extends FlameGame { +class HasVisibilityExample() extends FlameGame { static const String description = ''' In this example we use the `HasVisibility` mixin to toggle the visibility of a component without removing it from the parent @@ -27,6 +27,6 @@ class HasVisibilityExample extends FlameGame { } } -class LogoComponent extends SpriteComponent with HasVisibility { - LogoComponent(Sprite sprite) : super(sprite: sprite, size: sprite.srcSize); +class LogoComponent(Sprite sprite) extends SpriteComponent with HasVisibility { + this : super(sprite: sprite, size: sprite.srcSize); } diff --git a/examples/lib/stories/components/icon_component_example.dart b/examples/lib/stories/components/icon_component_example.dart index 4e83e3d2495..bc216876425 100644 --- a/examples/lib/stories/components/icon_component_example.dart +++ b/examples/lib/stories/components/icon_component_example.dart @@ -6,7 +6,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flutter/widgets.dart' show IconData; -class IconComponentExample extends FlameGame { +class IconComponentExample() extends FlameGame { static const String description = ''' In this example we showcase the `IconComponent`, which renders Flutter `IconData` as Flame components. The icons are rasterized to images on load, diff --git a/examples/lib/stories/components/keys_example.dart b/examples/lib/stories/components/keys_example.dart index 36c01538d59..315a014e733 100644 --- a/examples/lib/stories/components/keys_example.dart +++ b/examples/lib/stories/components/keys_example.dart @@ -4,9 +4,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class KeysExampleWidget extends StatefulWidget { - const KeysExampleWidget({super.key}); - +class const KeysExampleWidget({super.key}) extends StatefulWidget { static const String description = ''' Showcases how component keys can be used to find components from a flame game instance. @@ -18,7 +16,7 @@ class KeysExampleWidget extends StatefulWidget { State createState() => _KeysExampleWidgetState(); } -class _KeysExampleWidgetState extends State { +class _KeysExampleWidgetState() extends State { late final KeysExampleGame game = KeysExampleGame(); void selectHero(ComponentKey key) { @@ -68,7 +66,7 @@ class _KeysExampleWidgetState extends State { } } -class KeysExampleGame extends FlameGame { +class KeysExampleGame() extends FlameGame { @override FutureOr onLoad() async { await super.onLoad(); @@ -100,13 +98,13 @@ class KeysExampleGame extends FlameGame { } } -class SelectableClass extends SpriteComponent { - SelectableClass({ - super.position, - super.size, - super.key, - super.sprite, - }) : super(paint: Paint()..color = Colors.white.withValues(alpha: 0.5)); +class SelectableClass({ + super.position, + super.size, + super.key, + super.sprite, +}) extends SpriteComponent { + this : super(paint: Paint()..color = Colors.white.withValues(alpha: 0.5)); bool _selected = false; bool get selected => _selected; diff --git a/examples/lib/stories/components/look_at_example.dart b/examples/lib/stories/components/look_at_example.dart index a9a5ba01467..dc7d1e4b118 100644 --- a/examples/lib/stories/components/look_at_example.dart +++ b/examples/lib/stories/components/look_at_example.dart @@ -10,7 +10,8 @@ import 'package:flame/sprite.dart'; import 'package:flutter/services.dart'; import 'package:material_ui/material_ui.dart'; -class LookAtExample extends FlameGame<_TapWorld> +class LookAtExample() + extends FlameGame<_TapWorld> with HasKeyboardHandlerComponents { static const description = 'This example demonstrates how a component can be ' @@ -20,7 +21,7 @@ class LookAtExample extends FlameGame<_TapWorld> 'oriented in the desired direction if the image is not facing the ' 'correct direction.'; - LookAtExample() : super(world: _TapWorld()); + this : super(world: _TapWorld()); late List<_ChopperParent> _choppers; @@ -66,7 +67,8 @@ class LookAtExample extends FlameGame<_TapWorld> } } -class _TapWorld extends World +class _TapWorld() + extends World with TapCallbacks, KeyboardHandler, HasGameRef { final CircleComponent target = CircleComponent( radius: 5, @@ -130,14 +132,13 @@ class _TapWorld extends World } } -class _ChopperParent extends PositionComponent with HasGameRef { - final PositionComponent chopper; +class _ChopperParent({ + required super.position, + required final PositionComponent chopper, +}) extends PositionComponent with HasGameRef { late TextBoxComponent textBox; - _ChopperParent({ - required super.position, - required this.chopper, - }) : super(children: [chopper]); + this : super(children: [chopper]); @override FutureOr onLoad() { diff --git a/examples/lib/stories/components/look_at_smooth_example.dart b/examples/lib/stories/components/look_at_smooth_example.dart index f04da8f60d5..be9a5d21343 100644 --- a/examples/lib/stories/components/look_at_smooth_example.dart +++ b/examples/lib/stories/components/look_at_smooth_example.dart @@ -9,7 +9,7 @@ import 'package:flame/palette.dart'; import 'package:flame/sprite.dart'; import 'package:material_ui/material_ui.dart'; -class LookAtSmoothExample extends FlameGame { +class LookAtSmoothExample() extends FlameGame { static const description = 'This example demonstrates how a component can be ' 'made to smoothly rotate towards a target using the angleTo method. ' @@ -18,7 +18,7 @@ class LookAtSmoothExample extends FlameGame { 'oriented in the desired direction if the image is not facing the ' 'correct direction.'; - LookAtSmoothExample() : super(world: _TapWorld()); + this : super(world: _TapWorld()); late SpriteAnimationComponent _chopper1; late SpriteAnimationComponent _chopper2; @@ -94,7 +94,7 @@ class LookAtSmoothExample extends FlameGame { } } -class _TapWorld extends World with TapCallbacks { +class _TapWorld() extends World with TapCallbacks { bool _isRotating = false; final CircleComponent _targetComponent = CircleComponent( diff --git a/examples/lib/stories/components/priority_example.dart b/examples/lib/stories/components/priority_example.dart index d73f8075427..695b4283961 100644 --- a/examples/lib/stories/components/priority_example.dart +++ b/examples/lib/stories/components/priority_example.dart @@ -3,13 +3,13 @@ import 'package:flame/events.dart'; import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; -class PriorityExample extends FlameGame { +class PriorityExample() extends FlameGame { static const String description = ''' On this example, click on the square to bring them to the front by changing the priority. '''; - PriorityExample() + this : super( children: [ Square(Vector2(100, 100)), @@ -20,9 +20,10 @@ class PriorityExample extends FlameGame { ); } -class Square extends RectangleComponent +class Square(Vector2 position) + extends RectangleComponent with HasGameRef, TapCallbacks { - Square(Vector2 position) + this : super( position: position, size: Vector2.all(100), diff --git a/examples/lib/stories/components/skip_text_box_component_example.dart b/examples/lib/stories/components/skip_text_box_component_example.dart index 21cfca57eb3..19955bfeed9 100644 --- a/examples/lib/stories/components/skip_text_box_component_example.dart +++ b/examples/lib/stories/components/skip_text_box_component_example.dart @@ -4,7 +4,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; -class SkipTextBoxComponentExample extends FlameGame { +class SkipTextBoxComponentExample() extends FlameGame { static const String description = ''' On this example, click on the "Skip" button to display all the text at once. '''; diff --git a/examples/lib/stories/components/spawn_component_example.dart b/examples/lib/stories/components/spawn_component_example.dart index 4590e73f2f1..0ebf07a7588 100644 --- a/examples/lib/stories/components/spawn_component_example.dart +++ b/examples/lib/stories/components/spawn_component_example.dart @@ -6,14 +6,14 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flame/math.dart'; -class SpawnComponentExample extends FlameGame { +class SpawnComponentExample() extends FlameGame { static const String description = 'Tap on the screen to start spawning Embers within different shapes.'; - SpawnComponentExample() : super(world: SpawnComponentWorld()); + this : super(world: SpawnComponentWorld()); } -class SpawnComponentWorld extends World with TapCallbacks { +class SpawnComponentWorld() extends World with TapCallbacks { @override void onTapDown(TapDownEvent info) { final shapeType = Shapes.values.random(); @@ -54,7 +54,7 @@ class SpawnComponentWorld extends World with TapCallbacks { } } -enum Shapes { +enum Shapes() { rectangle, circle, polygon, diff --git a/examples/lib/stories/components/time_scale_example.dart b/examples/lib/stories/components/time_scale_example.dart index 43fe14f7b31..84745176046 100644 --- a/examples/lib/stories/components/time_scale_example.dart +++ b/examples/lib/stories/components/time_scale_example.dart @@ -9,12 +9,13 @@ import 'package:flame/palette.dart'; import 'package:flame/sprite.dart'; import 'package:flutter/rendering.dart'; -class TimeScaleExample extends FlameGame +class TimeScaleExample() + extends FlameGame with HasTimeScale, HasCollisionDetection { static const description = 'This example shows how time scale can be used to control game speed.'; - TimeScaleExample() + this : super( camera: CameraComponent.withFixedResolution( width: 640, @@ -64,7 +65,7 @@ class TimeScaleExample extends FlameGame ), gameSpeedText, ]); - return super.onLoad(); + await super.onLoad(); } @override @@ -74,20 +75,17 @@ class TimeScaleExample extends FlameGame } } -class _Chopper extends SpriteAnimationComponent +class _Chopper({ + super.animation, + super.position, + super.size, + super.angle, + super.anchor, +}) extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks { - _Chopper({ - super.animation, - super.position, - super.size, - super.angle, - super.anchor, - }) : _moveDirection = Vector2(0, 1)..rotate(angle ?? 0), - _initialPosition = position?.clone() ?? Vector2.zero(); - - final Vector2 _moveDirection; + final Vector2 _moveDirection = Vector2(0, 1)..rotate(angle ?? 0); final _speed = 80.0; - final Vector2 _initialPosition; + final Vector2 _initialPosition = position?.clone() ?? Vector2.zero(); late final _timer = TimerComponent( period: 2, onTick: _reset, @@ -98,7 +96,7 @@ class _Chopper extends SpriteAnimationComponent Future onLoad() async { add(CircleHitbox()); add(_timer); - return super.onLoad(); + await super.onLoad(); } @override diff --git a/examples/lib/stories/components/widget_component_example.dart b/examples/lib/stories/components/widget_component_example.dart index c5b13749e13..7af9a8c5dc8 100644 --- a/examples/lib/stories/components/widget_component_example.dart +++ b/examples/lib/stories/components/widget_component_example.dart @@ -6,7 +6,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flutter/material.dart'; -class WidgetComponentExample extends FlameGame { +class WidgetComponentExample() extends FlameGame { static const String description = ''' In this example we showcase the `WidgetComponent`, which hosts a Flutter widget inside the Flame component tree. The widgets are real parts of the @@ -117,15 +117,13 @@ class WidgetComponentExample extends FlameGame { /// An Ember rendered behind the card, to show that widgets are rendered in /// between other components according to their priority. -class _BackgroundEmber extends Ember { - _BackgroundEmber({required super.position}) - : super(size: Vector2.all(160), priority: 0); +class _BackgroundEmber({required super.position}) extends Ember { + this : super(size: Vector2.all(160), priority: 0); } /// An Ember rendered in front of the card, orbiting around it. -class _ForegroundEmber extends Ember { - _ForegroundEmber({required super.position}) - : super(size: Vector2.all(40), priority: 2); +class _ForegroundEmber({required super.position}) extends Ember { + this : super(size: Vector2.all(40), priority: 2); @override Future onLoad() async { @@ -139,11 +137,8 @@ class _ForegroundEmber extends Ember { } } -class _LabelCard extends StatelessWidget { - const _LabelCard({required this.label}); - - final ValueNotifier label; - +class const _LabelCard({required final ValueNotifier label}) + extends StatelessWidget { @override Widget build(BuildContext context) { return Card( diff --git a/examples/lib/stories/effects/color_effect_example.dart b/examples/lib/stories/effects/color_effect_example.dart index 5d22c62426f..8ad4c11a797 100644 --- a/examples/lib/stories/effects/color_effect_example.dart +++ b/examples/lib/stories/effects/color_effect_example.dart @@ -4,7 +4,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class ColorEffectExample extends FlameGame { +class ColorEffectExample() extends FlameGame { static const String description = ''' In this example we show how the `ColorEffect` can be used. Ember will constantly pulse in and out of a blue color. diff --git a/examples/lib/stories/effects/combined_effect_example.dart b/examples/lib/stories/effects/combined_effect_example.dart index d2841bea5b8..4d065978c3a 100644 --- a/examples/lib/stories/effects/combined_effect_example.dart +++ b/examples/lib/stories/effects/combined_effect_example.dart @@ -5,7 +5,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; -class CombinedEffectExample extends FlameGame { +class CombinedEffectExample() extends FlameGame { static const String description = ''' A combination of effects, consisting of a move effect, a rotate effect, and a scale effect. The combination of effects then runs in the opposite order @@ -33,8 +33,8 @@ class CombinedEffectExample extends FlameGame { } } -class Player extends PositionComponent { - Player() +class Player() extends PositionComponent { + this : path = Path() ..lineTo(40, 20) ..lineTo(0, 40) diff --git a/examples/lib/stories/effects/dual_effect_removal_example.dart b/examples/lib/stories/effects/dual_effect_removal_example.dart index 6da7209efca..a516054f6ba 100644 --- a/examples/lib/stories/effects/dual_effect_removal_example.dart +++ b/examples/lib/stories/effects/dual_effect_removal_example.dart @@ -4,7 +4,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class DualEffectRemovalExample extends FlameGame with TapCallbacks { +class DualEffectRemovalExample() extends FlameGame with TapCallbacks { static const String description = ''' In this example we show how a dual effect can be used and removed. To remove an effect, tap anywhere on the screen and the first tap will diff --git a/examples/lib/stories/effects/effect_controllers_example.dart b/examples/lib/stories/effects/effect_controllers_example.dart index 97482d693b9..4197258799c 100644 --- a/examples/lib/stories/effects/effect_controllers_example.dart +++ b/examples/lib/stories/effects/effect_controllers_example.dart @@ -5,7 +5,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; -class EffectControllersExample extends FlameGame { +class EffectControllersExample() extends FlameGame { static const description = ''' This page demonstrates application of various non-standard effect controllers. @@ -20,7 +20,7 @@ class EffectControllersExample extends FlameGame { delayed. '''; - EffectControllersExample() + this : super( camera: CameraComponent.withFixedResolution( width: 400, @@ -30,7 +30,7 @@ class EffectControllersExample extends FlameGame { ); } -class _EffectControllerWorld extends World { +class _EffectControllerWorld() extends World { @override void onLoad() { add( diff --git a/examples/lib/stories/effects/function_effect_example.dart b/examples/lib/stories/effects/function_effect_example.dart index c5b0ad47e56..597d6aef1fe 100644 --- a/examples/lib/stories/effects/function_effect_example.dart +++ b/examples/lib/stories/effects/function_effect_example.dart @@ -3,12 +3,12 @@ import 'package:flame/effects.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -enum RobotState { +enum RobotState() { idle, running, } -class FunctionEffectExample extends FlameGame with TapCallbacks { +class FunctionEffectExample() extends FlameGame with TapCallbacks { static const String description = ''' This example shows how to use the FunctionEffect to create custom effects. diff --git a/examples/lib/stories/effects/glow_effect_example.dart b/examples/lib/stories/effects/glow_effect_example.dart index 4926da2d2ee..1575475ed7e 100644 --- a/examples/lib/stories/effects/glow_effect_example.dart +++ b/examples/lib/stories/effects/glow_effect_example.dart @@ -8,7 +8,7 @@ void main() { runApp(GameWidget(game: GlowEffectExample())); } -class GlowEffectExample extends FlameGame with TapCallbacks { +class GlowEffectExample() extends FlameGame with TapCallbacks { static const String description = ''' In this example we show how the `GlowEffect` can be used. '''; diff --git a/examples/lib/stories/effects/hue_effect_example.dart b/examples/lib/stories/effects/hue_effect_example.dart index ccd7a91e019..a40f7c32bf4 100644 --- a/examples/lib/stories/effects/hue_effect_example.dart +++ b/examples/lib/stories/effects/hue_effect_example.dart @@ -4,7 +4,7 @@ import 'package:examples/commons/ember.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; -class HueEffectExample extends FlameGame { +class HueEffectExample() extends FlameGame { static const String description = ''' In this example we show how the `HueEffect` can be used. Ember will shift its hue over time. diff --git a/examples/lib/stories/effects/move_effect_example.dart b/examples/lib/stories/effects/move_effect_example.dart index aebac7a2aed..224b99e8cf7 100644 --- a/examples/lib/stories/effects/move_effect_example.dart +++ b/examples/lib/stories/effects/move_effect_example.dart @@ -7,7 +7,7 @@ import 'package:flame/geometry.dart'; import 'package:flame_noise/flame_noise.dart'; import 'package:material_ui/material_ui.dart'; -class MoveEffectExample extends FlameGame { +class MoveEffectExample() extends FlameGame { static const description = ''' Top square has `MoveEffect.to` effect that makes the component move along a straight line back and forth. The effect uses a non-linear progression @@ -22,7 +22,7 @@ class MoveEffectExample extends FlameGame { an arbitrary path using `MoveEffect.along`. '''; - MoveEffectExample() + this : super( camera: CameraComponent.withFixedResolution( width: 400, @@ -32,7 +32,7 @@ class MoveEffectExample extends FlameGame { ); } -class _MoveEffectWorld extends World { +class _MoveEffectWorld() extends World { @override void onLoad() { final paint1 = Paint() diff --git a/examples/lib/stories/effects/opacity_effect_example.dart b/examples/lib/stories/effects/opacity_effect_example.dart index 2986b0dacd0..29dfdb08e84 100644 --- a/examples/lib/stories/effects/opacity_effect_example.dart +++ b/examples/lib/stories/effects/opacity_effect_example.dart @@ -4,7 +4,7 @@ import 'package:flame/effects.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class OpacityEffectExample extends FlameGame with TapCallbacks { +class OpacityEffectExample() extends FlameGame with TapCallbacks { static const String description = ''' In this example we show how the `OpacityEffect` can be used in two ways. The left Ember will constantly pulse in and out of opacity and the right diff --git a/examples/lib/stories/effects/remove_effect_example.dart b/examples/lib/stories/effects/remove_effect_example.dart index cbcb5538864..b25edcb3602 100644 --- a/examples/lib/stories/effects/remove_effect_example.dart +++ b/examples/lib/stories/effects/remove_effect_example.dart @@ -6,13 +6,13 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class RemoveEffectExample extends FlameGame { +class RemoveEffectExample() extends FlameGame { static const description = ''' Click on any circle to apply a RemoveEffect, which will make the circle disappear after a 0.5 second delay. '''; - RemoveEffectExample() + this : super( camera: CameraComponent.withFixedResolution( width: 400, @@ -22,7 +22,7 @@ class RemoveEffectExample extends FlameGame { ); } -class _RemoveEffectWorld extends World { +class _RemoveEffectWorld() extends World { @override void onLoad() { super.onLoad(); @@ -33,9 +33,10 @@ class _RemoveEffectWorld extends World { } } -class _RandomCircle extends CircleComponent with TapCallbacks { - _RandomCircle(double radius, {super.position, super.paint}) - : super(radius: radius); +class _RandomCircle(double radius, {super.position, super.paint}) + extends CircleComponent + with TapCallbacks { + this : super(radius: radius); factory _RandomCircle.random(Random rng) { final radius = rng.nextDouble() * 30 + 10; diff --git a/examples/lib/stories/effects/rotate_around_effect_example.dart b/examples/lib/stories/effects/rotate_around_effect_example.dart index 0fb590672e8..45569644b6a 100644 --- a/examples/lib/stories/effects/rotate_around_effect_example.dart +++ b/examples/lib/stories/effects/rotate_around_effect_example.dart @@ -8,13 +8,13 @@ import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:material_ui/material_ui.dart' as material; -class RotateAroundEffectExample extends FlameGame { +class RotateAroundEffectExample() extends FlameGame { static const description = ''' This example shows how to use the RotateAroundEffect to rotate a component around a fixed point. '''; - RotateAroundEffectExample() + this : super( camera: CameraComponent.withFixedResolution( width: 400, @@ -24,7 +24,7 @@ around a fixed point. ); } -class _RotateAroundEffectWorld extends World { +class _RotateAroundEffectWorld() extends World { @override void onLoad() { add(_GlowingBall(position: Vector2.zero(), radius: 30)); @@ -49,11 +49,11 @@ class _RotateAroundEffectWorld extends World { } } -class _GlowingBall extends CircleComponent { - _GlowingBall({ - required super.position, - required super.radius, - }) : super(anchor: Anchor.center); +class _GlowingBall({ + required super.position, + required super.radius, +}) extends CircleComponent { + this : super(anchor: Anchor.center); static final random = Random(6); diff --git a/examples/lib/stories/effects/rotate_effect_example.dart b/examples/lib/stories/effects/rotate_effect_example.dart index 115b5f24f9e..856e92dadd9 100644 --- a/examples/lib/stories/effects/rotate_effect_example.dart +++ b/examples/lib/stories/effects/rotate_effect_example.dart @@ -7,7 +7,7 @@ import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:flutter/animation.dart'; -class RotateEffectExample extends FlameGame { +class RotateEffectExample() extends FlameGame { static const description = ''' The outer rim rotates at a different speed forward and reverse, and uses the "ease" animation curve. @@ -17,7 +17,7 @@ class RotateEffectExample extends FlameGame { add small amounts of wobble, creating quasi-chaotic movement. '''; - RotateEffectExample() + this : super( camera: CameraComponent.withFixedResolution( width: 400, @@ -27,7 +27,7 @@ class RotateEffectExample extends FlameGame { ); } -class _RotateEffectWorld extends World { +class _RotateEffectWorld() extends World { @override void onLoad() { final compass = Compass(size: 200); @@ -77,10 +77,9 @@ class _RotateEffectWorld extends World { } } -class Compass extends PositionComponent { - Compass({required double size}) - : _radius = size / 2, - super( +class Compass({required double size}) extends PositionComponent { + this + : super( size: Vector2.all(size), anchor: Anchor.center, ); @@ -88,7 +87,7 @@ class Compass extends PositionComponent { late PositionComponent arrow; late PositionComponent rim; - final double _radius; + final double _radius = size / 2; final _bgPaint = Paint()..color = const Color(0xffeacb31); final _marksPaint = Paint() ..color = const Color(0xFF7F6D36) @@ -128,15 +127,14 @@ class Compass extends PositionComponent { } } -class CompassArrow extends PositionComponent { - CompassArrow({required double width, required double radius}) - : assert(width <= radius, 'The width is larger than the radius'), - _radius = radius, - _width = width, - super(size: Vector2(width, 2 * radius), anchor: Anchor.center); +class CompassArrow({ + required final double _width, + required final double _radius, +}) extends PositionComponent { + this + : assert(_width <= _radius, 'The width is larger than the radius'), + super(size: Vector2(_width, 2 * _radius), anchor: Anchor.center); - final double _radius; - final double _width; late final Path _northPath; late final Path _southPath; final _northPaint = Paint()..color = const Color(0xff387fcb); @@ -163,19 +161,16 @@ class CompassArrow extends PositionComponent { } } -class CompassRim extends PositionComponent { - CompassRim({required double radius, required double width}) - : assert(radius > width, 'The width is larger than the radius'), - _radius = radius, - _width = width, +class CompassRim({required final double _radius, required final double _width}) + extends PositionComponent { + this + : assert(_radius > _width, 'The width is larger than the radius'), super( - size: Vector2.all(2 * radius), + size: Vector2.all(2 * _radius), anchor: Anchor.center, ); static const int numberOfNotches = 144; - final double _radius; - final double _width; late final Path _marksPath; final _bgPaint = Paint() ..style = PaintingStyle.stroke diff --git a/examples/lib/stories/effects/scale_effect_example.dart b/examples/lib/stories/effects/scale_effect_example.dart index 6808412147e..a256d55fc0e 100644 --- a/examples/lib/stories/effects/scale_effect_example.dart +++ b/examples/lib/stories/effects/scale_effect_example.dart @@ -9,7 +9,7 @@ import 'package:flame/geometry.dart'; import 'package:flame/palette.dart'; import 'package:flutter/animation.dart'; -class ScaleEffectExample extends FlameGame with TapCallbacks { +class ScaleEffectExample() extends FlameGame with TapCallbacks { static const String description = ''' In this example you can tap the screen and the component will scale up or down, depending on its current state. @@ -73,8 +73,8 @@ class ScaleEffectExample extends FlameGame with TapCallbacks { } } -class Star extends PositionComponent { - Star() { +class Star() extends PositionComponent { + this { const smallR = 15.0; const bigR = 30.0; shape = Path()..moveTo(bigR, 0); diff --git a/examples/lib/stories/effects/sequence_effect_example.dart b/examples/lib/stories/effects/sequence_effect_example.dart index 6da951d26ca..96a90e01411 100644 --- a/examples/lib/stories/effects/sequence_effect_example.dart +++ b/examples/lib/stories/effects/sequence_effect_example.dart @@ -5,7 +5,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; -class SequenceEffectExample extends FlameGame { +class SequenceEffectExample() extends FlameGame { static const String description = ''' Sequence of effects, consisting of a move effect, a rotate effect, another move effect, a scale effect, and then one more move effect. The sequence @@ -36,8 +36,8 @@ class SequenceEffectExample extends FlameGame { } } -class Player extends PositionComponent { - Player() +class Player() extends PositionComponent { + this : path = Path() ..lineTo(40, 20) ..lineTo(0, 40) diff --git a/examples/lib/stories/effects/size_effect_example.dart b/examples/lib/stories/effects/size_effect_example.dart index b0bdec601a3..d7a2ef1a522 100644 --- a/examples/lib/stories/effects/size_effect_example.dart +++ b/examples/lib/stories/effects/size_effect_example.dart @@ -7,7 +7,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:flutter/animation.dart'; -class SizeEffectExample extends FlameGame with TapCallbacks { +class SizeEffectExample() extends FlameGame with TapCallbacks { static const String description = ''' The `SizeEffect` changes the size of the component, the sizes of the children will stay the same. diff --git a/examples/lib/stories/experimental/layout_component_example_1.dart b/examples/lib/stories/experimental/layout_component_example_1.dart index ac88953b381..da7fedea63a 100644 --- a/examples/lib/stories/experimental/layout_component_example_1.dart +++ b/examples/lib/stories/experimental/layout_component_example_1.dart @@ -7,33 +7,22 @@ import 'package:flame/experimental.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class LayoutComponentExample1 extends FlameGame with DragCallbacks { - LayoutComponentExample1({ - required this.direction, - required this.mainAxisAlignment, - required this.crossAxisAlignment, - required this.gap, - required this.demoSize, - required this.padding, - required this.expandedMode, - required this.paddingInflateChild, - }); - +class LayoutComponentExample1({ + required final Direction direction, + required final MainAxisAlignment mainAxisAlignment, + required final CrossAxisAlignment crossAxisAlignment, + required final double gap, + required final LayoutComponentExampleSize demoSize, + required final EdgeInsets padding, + required final bool expandedMode, + required final bool paddingInflateChild, +}) extends FlameGame with DragCallbacks { static const String description = ''' This example demonstrates the various behaviors of LayoutComponents. Press the pen button on the floating group of icons on the upper right to see the various ways you can change this layout. '''; - final Direction direction; - final MainAxisAlignment mainAxisAlignment; - final CrossAxisAlignment crossAxisAlignment; - final double gap; - final LayoutComponentExampleSize demoSize; - final EdgeInsets padding; - final bool expandedMode; - final bool paddingInflateChild; - @override FutureOr onLoad() { camera.viewfinder.anchor = Anchor.topLeft; @@ -77,21 +66,19 @@ the various ways you can change this layout. bool get debugMode => true; } -class LayoutDemo1 extends LinearLayoutComponent { - LayoutDemo1({ - required super.direction, - required super.crossAxisAlignment, - required super.mainAxisAlignment, - required super.gap, - required super.position, - required this._padding, - required this._expandedMode, - required this.paddingInflateChild, - super.size, - super.key, - }) : super(anchor: Anchor.topLeft, priority: 0, children: []); - - bool _expandedMode = false; +class LayoutDemo1({ + required super.direction, + required super.crossAxisAlignment, + required super.mainAxisAlignment, + required super.gap, + required super.position, + required var EdgeInsets _padding, + required var bool _expandedMode, + required final bool paddingInflateChild, + super.size, + super.key, +}) extends LinearLayoutComponent { + this : super(anchor: Anchor.topLeft, priority: 0, children: []); bool get expandedMode => _expandedMode; @@ -107,8 +94,6 @@ class LayoutDemo1 extends LinearLayoutComponent { ); } - EdgeInsets _padding = EdgeInsets.zero; - EdgeInsets get padding => _padding; set padding(EdgeInsets value) { @@ -116,8 +101,6 @@ class LayoutDemo1 extends LinearLayoutComponent { paddingComponent?.padding = padding; } - final bool paddingInflateChild; - @override FutureOr onLoad() { super.onLoad(); diff --git a/examples/lib/stories/experimental/layout_component_example_2.dart b/examples/lib/stories/experimental/layout_component_example_2.dart index 06406d3ddb3..54449b236f1 100644 --- a/examples/lib/stories/experimental/layout_component_example_2.dart +++ b/examples/lib/stories/experimental/layout_component_example_2.dart @@ -7,27 +7,19 @@ import 'package:flame/experimental.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class LayoutComponentExample2 extends FlameGame with DragCallbacks { - LayoutComponentExample2({ - required this.direction, - required this.mainAxisAlignment, - required this.crossAxisAlignment, - required this.gap, - required this.demoSize, - }); - +class LayoutComponentExample2({ + required final Direction direction, + required final MainAxisAlignment mainAxisAlignment, + required final CrossAxisAlignment crossAxisAlignment, + required final double gap, + required final LayoutComponentExampleSize demoSize, +}) extends FlameGame with DragCallbacks { static const String description = ''' This example demonstrates the various behaviors of LayoutComponents. Press the pen button on the floating group of icons on the upper right to see the various ways you can change this layout. '''; - final Direction direction; - final MainAxisAlignment mainAxisAlignment; - final CrossAxisAlignment crossAxisAlignment; - final double gap; - final LayoutComponentExampleSize demoSize; - @override FutureOr onLoad() { camera.viewfinder.anchor = Anchor.topLeft; @@ -67,16 +59,16 @@ the various ways you can change this layout. bool get debugMode => true; } -class LayoutDemo2 extends LinearLayoutComponent { - LayoutDemo2({ - required super.direction, - required super.crossAxisAlignment, - required super.mainAxisAlignment, - required super.gap, - required super.position, - super.size, - super.key, - }) : super(anchor: Anchor.topLeft, priority: 0, children: []); +class LayoutDemo2({ + required super.direction, + required super.crossAxisAlignment, + required super.mainAxisAlignment, + required super.gap, + required super.position, + super.size, + super.key, +}) extends LinearLayoutComponent { + this : super(anchor: Anchor.topLeft, priority: 0, children: []); @override FutureOr onLoad() { diff --git a/examples/lib/stories/experimental/layout_component_example_3.dart b/examples/lib/stories/experimental/layout_component_example_3.dart index 98299b84665..eb99504aa3c 100644 --- a/examples/lib/stories/experimental/layout_component_example_3.dart +++ b/examples/lib/stories/experimental/layout_component_example_3.dart @@ -7,19 +7,15 @@ import 'package:flame/experimental.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class LayoutComponentExample3 extends FlameGame with DragCallbacks { - LayoutComponentExample3({ - required this.demoSize, - }); - +class LayoutComponentExample3({ + required final LayoutComponentExampleSize demoSize, +}) extends FlameGame with DragCallbacks { static const String description = ''' When ColumnComponent has a TextBoxComponent as a child, and its crossAxisAlignment is stretch, it will also set the maxWidth of the TextBoxComponent. '''; - final LayoutComponentExampleSize demoSize; - @override FutureOr onLoad() { camera.viewfinder.anchor = Anchor.topLeft; @@ -55,19 +51,20 @@ TextBoxComponent. bool get debugMode => true; } -class LayoutDemo3 extends ColumnComponent { - LayoutDemo3({ - required super.position, - super.size, - super.key, - }) : super( - anchor: Anchor.topLeft, - priority: 0, - children: [], - gap: 16, - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.stretch, - ); +class LayoutDemo3({ + required super.position, + super.size, + super.key, +}) extends ColumnComponent { + this + : super( + anchor: Anchor.topLeft, + priority: 0, + children: [], + gap: 16, + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.stretch, + ); @override FutureOr onLoad() { diff --git a/examples/lib/stories/experimental/layout_component_example_size.dart b/examples/lib/stories/experimental/layout_component_example_size.dart index 6116e2213d4..300df16f568 100644 --- a/examples/lib/stories/experimental/layout_component_example_size.dart +++ b/examples/lib/stories/experimental/layout_component_example_size.dart @@ -1,17 +1,13 @@ import 'package:flame/components.dart'; -enum LayoutComponentExampleSize { +enum LayoutComponentExampleSize( + final double? x, + final double? y, +) { shrinkWrap(null, null), small(640, 480), large(1080, 720); - const LayoutComponentExampleSize( - this.x, - this.y, - ); - final double? x; - final double? y; - Vector2? toVector2() { final x = this.x; final y = this.y; diff --git a/examples/lib/stories/experimental/shapes.dart b/examples/lib/stories/experimental/shapes.dart index f49e39992c0..4765b279138 100644 --- a/examples/lib/stories/experimental/shapes.dart +++ b/examples/lib/stories/experimental/shapes.dart @@ -9,7 +9,7 @@ import 'package:flame/extensions.dart' show Aabb2Extension, PathExtension; import 'package:flame/game.dart'; import 'package:flame/palette.dart'; -class ShapesExample extends FlameGame { +class ShapesExample() extends FlameGame { static const description = ''' This example shows multiple raw `Shape`s, and random points whose color should match the colors of the shapes that they fall in. Points that are @@ -86,23 +86,22 @@ class ShapesExample extends FlameGame { } } -class ShapesComponent extends Component { - ShapesComponent(this.shapes, List colors) +class ShapesComponent(final List shapes, List colors) + extends Component { + this : assert( shapes.length == colors.length, 'The shapes and colors lists have to be of the same length', - ), - paints = colors - .map( - (color) => Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 1 - ..color = color, - ) - .toList(); + ); - final List shapes; - final List paints; + final List paints = colors + .map( + (color) => Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = color, + ) + .toList(); @override void render(Canvas canvas) { @@ -112,16 +111,14 @@ class ShapesComponent extends Component { } } -class DotsComponent extends Component { - DotsComponent(this.shapes, this.shapeColors) +class DotsComponent(final List shapes, final List shapeColors) + extends Component { + this : assert( shapes.length == shapeColors.length, 'The shapes and shapeColors lists have to be of the same length', ); - final List shapes; - final List shapeColors; - final Random random = Random(); final List points = []; final List pointColors = []; diff --git a/examples/lib/stories/image/brighten.dart b/examples/lib/stories/image/brighten.dart index a74da7ae05d..7869ef07263 100644 --- a/examples/lib/stories/image/brighten.dart +++ b/examples/lib/stories/image/brighten.dart @@ -2,13 +2,9 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; -class ImageBrightnessExample extends FlameGame { - ImageBrightnessExample({ - required this.brightness, - }); - - final double brightness; - +class ImageBrightnessExample({ + required final double brightness, +}) extends FlameGame { static const String description = ''' Shows how a dart:ui `Image` can be brightened using Flame Image extensions. Use the properties on the side to change the brightness of the image. diff --git a/examples/lib/stories/image/darken.dart b/examples/lib/stories/image/darken.dart index 52a2724c78f..24053e9b921 100644 --- a/examples/lib/stories/image/darken.dart +++ b/examples/lib/stories/image/darken.dart @@ -2,13 +2,9 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; -class ImageDarknessExample extends FlameGame { - ImageDarknessExample({ - required this.darkness, - }); - - final double darkness; - +class ImageDarknessExample({ + required final double darkness, +}) extends FlameGame { static const String description = ''' Shows how a dart:ui `Image` can be darkened using Flame Image extensions. Use the properties on the side to change the darkness of the image. diff --git a/examples/lib/stories/image/resize.dart b/examples/lib/stories/image/resize.dart index 2c0b9b20ff1..67c4b7b7e45 100644 --- a/examples/lib/stories/image/resize.dart +++ b/examples/lib/stories/image/resize.dart @@ -2,16 +2,12 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; -class ImageResizeExample extends FlameGame { - ImageResizeExample(this.sizeTarget); - +class ImageResizeExample(final Vector2 sizeTarget) extends FlameGame { static const String description = ''' Shows how a dart:ui `Image` can be resized using Flame Image extensions. Use the properties on the side to change the size of the image. '''; - final Vector2 sizeTarget; - @override Future onLoad() async { final image = await images.load('assets/images/flame.png'); diff --git a/examples/lib/stories/input/advanced_button_example.dart b/examples/lib/stories/input/advanced_button_example.dart index e74b0fbc700..5d9d1d58562 100644 --- a/examples/lib/stories/input/advanced_button_example.dart +++ b/examples/lib/stories/input/advanced_button_example.dart @@ -3,7 +3,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:flutter/painting.dart'; -class AdvancedButtonExample extends FlameGame { +class AdvancedButtonExample() extends FlameGame { static const String description = '''This example shows how you can use a button with different states'''; @@ -27,7 +27,7 @@ class AdvancedButtonExample extends FlameGame { } } -class ToggleButton extends ToggleButtonComponent { +class ToggleButton() extends ToggleButtonComponent { @override Future onLoad() async { super.onLoad(); @@ -72,7 +72,7 @@ class ToggleButton extends ToggleButtonComponent { } } -class DefaultButton extends AdvancedButtonComponent { +class DefaultButton() extends AdvancedButtonComponent { @override Future onLoad() async { super.onLoad(); @@ -90,7 +90,7 @@ class DefaultButton extends AdvancedButtonComponent { } } -class DisableButton extends AdvancedButtonComponent { +class DisableButton() extends AdvancedButtonComponent { @override Future onLoad() async { super.onLoad(); @@ -105,7 +105,7 @@ class DisableButton extends AdvancedButtonComponent { } } -class RoundedRectComponent extends PositionComponent with HasPaint { +class RoundedRectComponent() extends PositionComponent with HasPaint { @override void render(Canvas canvas) { canvas.drawRRect( diff --git a/examples/lib/stories/input/double_tap_callbacks_example.dart b/examples/lib/stories/input/double_tap_callbacks_example.dart index a32ac90faf6..697c9b87555 100644 --- a/examples/lib/stories/input/double_tap_callbacks_example.dart +++ b/examples/lib/stories/input/double_tap_callbacks_example.dart @@ -4,7 +4,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class DoubleTapCallbacksExample extends FlameGame with DoubleTapCallbacks { +class DoubleTapCallbacksExample() extends FlameGame with DoubleTapCallbacks { static const String description = ''' In this example, we show how you can use the `DoubleTapCallbacks` mixin on a `Component`. Double tap Ember and see her color changing. @@ -38,11 +38,13 @@ class DoubleTapCallbacksExample extends FlameGame with DoubleTapCallbacks { } } -class DoubleTappableEmber extends Ember with DoubleTapCallbacks { +class DoubleTappableEmber({Vector2? position}) + extends Ember + with DoubleTapCallbacks { @override bool debugMode = true; - DoubleTappableEmber({Vector2? position}) + this : super( position: position ?? Vector2.all(100), size: Vector2.all(100), diff --git a/examples/lib/stories/input/drag_callbacks_example.dart b/examples/lib/stories/input/drag_callbacks_example.dart index ccd815ed04e..daebcdfabd8 100644 --- a/examples/lib/stories/input/drag_callbacks_example.dart +++ b/examples/lib/stories/input/drag_callbacks_example.dart @@ -3,16 +3,13 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart' show Colors; -class DragCallbacksExample extends FlameGame { +class DragCallbacksExample({required final double zoom}) extends FlameGame { static const String description = ''' In this example we show you can use the `DragCallbacks` mixin on `PositionComponent`s. Drag around the Embers and see their position changing. '''; - DragCallbacksExample({required this.zoom}); - - final double zoom; late final DraggableEmber square; @override @@ -25,11 +22,11 @@ class DragCallbacksExample extends FlameGame { // Note: this component does not consider the possibility of multiple // simultaneous drags with different pointerIds. -class DraggableEmber extends Ember with DragCallbacks { +class DraggableEmber({super.position}) extends Ember with DragCallbacks { @override bool debugMode = true; - DraggableEmber({super.position}) : super(size: Vector2.all(100)); + this : super(size: Vector2.all(100)); @override void update(double dt) { diff --git a/examples/lib/stories/input/dynamic_scale_drag_example.dart b/examples/lib/stories/input/dynamic_scale_drag_example.dart index 61c444c4a61..f4696ac4ec7 100644 --- a/examples/lib/stories/input/dynamic_scale_drag_example.dart +++ b/examples/lib/stories/input/dynamic_scale_drag_example.dart @@ -5,7 +5,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class DynamicScaleDragExample extends FlameGame { +class DynamicScaleDragExample() extends FlameGame { static const String description = ''' Demonstrates dynamically adding draggable and scalable components at runtime. Use the buttons to spawn components with different interaction @@ -104,17 +104,13 @@ class DynamicScaleDragExample extends FlameGame { } } -class _Button extends PositionComponent with TapCallbacks { - _Button({ - required this._text, - required super.position, - required this._color, - required this._onPressed, - }) : super(size: Vector2(100, 30)); - - final Color _color; - final VoidCallback _onPressed; - final String _text; +class _Button({ + required final String _text, + required super.position, + required final Color _color, + required final VoidCallback _onPressed, +}) extends PositionComponent with TapCallbacks { + this : super(size: Vector2(100, 30)); @override Future onLoad() async { @@ -145,20 +141,18 @@ class _Button extends PositionComponent with TapCallbacks { } /// A rectangle that only responds to drag. -class _DragBox extends RectangleComponent - with DragCallbacks, HasGameRef { - _DragBox({ - required this._label, - required Vector2 position, - required Color color, - }) : super( - position: position, - size: Vector2.all(120), - anchor: Anchor.center, - paint: Paint()..color = color, - ); - - final String _label; +class _DragBox({ + required final String _label, + required Vector2 position, + required Color color, +}) extends RectangleComponent with DragCallbacks, HasGameRef { + this + : super( + position: position, + size: Vector2.all(120), + anchor: Anchor.center, + paint: Paint()..color = color, + ); @override Future onLoad() async { @@ -181,19 +175,19 @@ class _DragBox extends RectangleComponent } /// A rectangle that only responds to scale (pinch/zoom). -class _ScaleBox extends RectangleComponent with ScaleCallbacks { - _ScaleBox({ - required this._label, - required Vector2 position, - required Color color, - }) : super( - position: position, - size: Vector2.all(120), - anchor: Anchor.center, - paint: Paint()..color = color, - ); +class _ScaleBox({ + required final String _label, + required Vector2 position, + required Color color, +}) extends RectangleComponent with ScaleCallbacks { + this + : super( + position: position, + size: Vector2.all(120), + anchor: Anchor.center, + paint: Paint()..color = color, + ); - final String _label; double _initialAngle = 0; double _lastScale = 1.0; @@ -231,20 +225,20 @@ class _ScaleBox extends RectangleComponent with ScaleCallbacks { } /// A rectangle that responds to both drag and scale. -class _DragScaleBox extends RectangleComponent +class _DragScaleBox({ + required final String _label, + required Vector2 position, + required Color color, +}) extends RectangleComponent with ScaleCallbacks, DragCallbacks, HasGameRef { - _DragScaleBox({ - required this._label, - required Vector2 position, - required Color color, - }) : super( - position: position, - size: Vector2.all(120), - anchor: Anchor.center, - paint: Paint()..color = color, - ); + this + : super( + position: position, + size: Vector2.all(120), + anchor: Anchor.center, + paint: Paint()..color = color, + ); - final String _label; double _initialAngle = 0; double _lastScale = 1.0; diff --git a/examples/lib/stories/input/gesture_hitboxes_example.dart b/examples/lib/stories/input/gesture_hitboxes_example.dart index 25c8c6556e6..637eadea031 100644 --- a/examples/lib/stories/input/gesture_hitboxes_example.dart +++ b/examples/lib/stories/input/gesture_hitboxes_example.dart @@ -8,9 +8,14 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -enum Shapes { circle, rectangle, polygon, path } +enum Shapes() { + circle, + rectangle, + polygon, + path, +} -class GestureHitboxesExample extends FlameGame { +class GestureHitboxesExample() extends FlameGame { static const description = ''' Tap to create a PositionComponent with a randomly shaped hitbox. You can then hover over to shapes to see that they receive the hover events @@ -18,10 +23,11 @@ class GestureHitboxesExample extends FlameGame { it is removed. '''; - GestureHitboxesExample() : super(world: _GestureHitboxesWorld()); + this : super(world: _GestureHitboxesWorld()); } -class _GestureHitboxesWorld extends World +class _GestureHitboxesWorld() + extends World with TapCallbacks, HasGameRef { final _rng = Random(); @@ -82,16 +88,15 @@ class _GestureHitboxesWorld extends World } } -class MyPathComponent extends PathComponent - with TapCallbacks, HoverCallbacks, GestureHitboxes { +class MyPathComponent({ + required super.path, + super.position, + super.scale, + super.angle, +}) extends PathComponent with TapCallbacks, HoverCallbacks, GestureHitboxes { late final Color baseColor; - MyPathComponent({ - required super.path, - super.position, - super.scale, - super.angle, - }) : super(anchor: .center) { + this : super(anchor: .center) { // The hitbox follows the same path, and it is rendered so that you can // see the polygons that receive the gestures. add( @@ -124,17 +129,16 @@ class MyPathComponent extends PathComponent } } -class MyShapeComponent extends PositionComponent +class MyShapeComponent({ + required final ShapeHitbox hitbox, + super.position, + super.size, + super.angle, +}) extends PositionComponent with TapCallbacks, HoverCallbacks, GestureHitboxes { - final ShapeHitbox hitbox; late final Color baseColor; - MyShapeComponent({ - required this.hitbox, - super.position, - super.size, - super.angle, - }) : super(anchor: Anchor.center); + this : super(anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/lib/stories/input/hardware_keyboard_example.dart b/examples/lib/stories/input/hardware_keyboard_example.dart index 53993f82ce5..2f3fe109ac4 100644 --- a/examples/lib/stories/input/hardware_keyboard_example.dart +++ b/examples/lib/stories/input/hardware_keyboard_example.dart @@ -5,7 +5,7 @@ import 'package:flame/text.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; -class HardwareKeyboardExample extends FlameGame { +class HardwareKeyboardExample() extends FlameGame { static const String description = ''' This example uses the HardwareKeyboardDetector mixin in order to keep track of which keys on a keyboard are currently pressed. @@ -45,7 +45,8 @@ class HardwareKeyboardExample extends FlameGame { } } -class MyKeyboardDetector extends HardwareKeyboardDetector +class MyKeyboardDetector() + extends HardwareKeyboardDetector with HasGameRef { @override void onKeyEvent(KeyEvent event) { @@ -205,8 +206,9 @@ class MyKeyboardDetector extends HardwareKeyboardDetector }; } -class KeyboardKey extends PositionComponent { - KeyboardKey({required this.text, super.position}) { +class KeyboardKey({required final String text, super.position}) + extends PositionComponent { + this { textElement = textRenderer.format(text); width = textElement.metrics.width + padding.x; height = textElement.metrics.height + padding.y; @@ -217,7 +219,6 @@ class KeyboardKey extends PositionComponent { rect = RRect.fromLTRBR(0, 0, width, height, const Radius.circular(8)); } - final String text; late final InlineTextElement textElement; late final RRect rect; diff --git a/examples/lib/stories/input/hover_callbacks_example.dart b/examples/lib/stories/input/hover_callbacks_example.dart index 47fac42b94b..19fc4dc3e80 100644 --- a/examples/lib/stories/input/hover_callbacks_example.dart +++ b/examples/lib/stories/input/hover_callbacks_example.dart @@ -4,13 +4,13 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class HoverCallbacksExample extends FlameGame { +class HoverCallbacksExample() extends FlameGame { static const String description = ''' This example shows how to use `HoverCallbacks`s.\n\n Add more squares by clicking and hover them to change their color. '''; - HoverCallbacksExample() : super(world: HoverCallbacksWorld()); + this : super(world: HoverCallbacksWorld()); @override Future onLoad() async { @@ -19,7 +19,7 @@ class HoverCallbacksExample extends FlameGame { } } -class HoverCallbacksWorld extends World with TapCallbacks { +class HoverCallbacksWorld() extends World with TapCallbacks { @override Future onLoad() async { add(HoverSquare(Vector2(200, 500))); @@ -32,11 +32,13 @@ class HoverCallbacksWorld extends World with TapCallbacks { } } -class HoverSquare extends RectangleComponent with HoverCallbacks { +class HoverSquare(Vector2 position) + extends RectangleComponent + with HoverCallbacks { static final Paint _white = Paint()..color = const Color(0xFFFFFFFF); static final Paint _grey = Paint()..color = const Color(0xFFA5A5A5); - HoverSquare(Vector2 position) + this : super( position: position, size: Vector2.all(100), diff --git a/examples/lib/stories/input/joystick_advanced_example.dart b/examples/lib/stories/input/joystick_advanced_example.dart index 056bd88d5c6..d4c2a5640eb 100644 --- a/examples/lib/stories/input/joystick_advanced_example.dart +++ b/examples/lib/stories/input/joystick_advanced_example.dart @@ -9,7 +9,7 @@ import 'package:flame/palette.dart'; import 'package:flame/sprite.dart'; import 'package:material_ui/material_ui.dart'; -class JoystickAdvancedExample extends FlameGame with HasCollisionDetection { +class JoystickAdvancedExample() extends FlameGame with HasCollisionDetection { static const String description = ''' In this example we showcase how to use the joystick by creating `SpriteComponent`s that serve as the joystick's knob and background. @@ -20,7 +20,7 @@ class JoystickAdvancedExample extends FlameGame with HasCollisionDetection { the buttons. '''; - JoystickAdvancedExample() + this : super( camera: CameraComponent.withFixedResolution(width: 1200, height: 800), ); diff --git a/examples/lib/stories/input/joystick_example.dart b/examples/lib/stories/input/joystick_example.dart index aac3dc4e022..4dbb16e4a50 100644 --- a/examples/lib/stories/input/joystick_example.dart +++ b/examples/lib/stories/input/joystick_example.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:flutter/painting.dart'; -class JoystickExample extends FlameGame { +class JoystickExample() extends FlameGame { static const String description = ''' In this example we showcase how to use the joystick by creating simple `CircleComponent`s that serve as the joystick's knob and background. diff --git a/examples/lib/stories/input/joystick_player.dart b/examples/lib/stories/input/joystick_player.dart index db1eb275b46..8a86f4ab7b5 100644 --- a/examples/lib/stories/input/joystick_player.dart +++ b/examples/lib/stories/input/joystick_player.dart @@ -2,17 +2,15 @@ import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/game.dart'; -class JoystickPlayer extends SpriteComponent +class JoystickPlayer(final JoystickComponent joystick) + extends SpriteComponent with HasGameRef, CollisionCallbacks { /// Pixels/s double maxSpeed = 300.0; late final Vector2 _lastSize = size.clone(); late final Transform2D _lastTransform = transform.clone(); - final JoystickComponent joystick; - - JoystickPlayer(this.joystick) - : super(size: Vector2.all(100.0), anchor: Anchor.center); + this : super(size: Vector2.all(100.0), anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/lib/stories/input/keyboard_example.dart b/examples/lib/stories/input/keyboard_example.dart index 6a9e337ee9d..552f80d5b7c 100644 --- a/examples/lib/stories/input/keyboard_example.dart +++ b/examples/lib/stories/input/keyboard_example.dart @@ -5,7 +5,7 @@ import 'package:flame/input.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; -class KeyboardExample extends FlameGame with KeyboardEvents { +class KeyboardExample() extends FlameGame with KeyboardEvents { static const String description = ''' Example showcasing how to act on keyboard events. It also briefly showcases how to create a game without the FlameGame. diff --git a/examples/lib/stories/input/keyboard_listener_component_example.dart b/examples/lib/stories/input/keyboard_listener_component_example.dart index ee7b74d1075..3bc4b974769 100644 --- a/examples/lib/stories/input/keyboard_listener_component_example.dart +++ b/examples/lib/stories/input/keyboard_listener_component_example.dart @@ -4,7 +4,8 @@ import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flutter/services.dart'; -class KeyboardListenerComponentExample extends FlameGame +class KeyboardListenerComponentExample() + extends FlameGame with HasKeyboardHandlerComponents { static const String description = ''' Similar to the default Keyboard example, but shows a different diff --git a/examples/lib/stories/input/long_press_example.dart b/examples/lib/stories/input/long_press_example.dart index 327ed9f1cbe..cad55af8226 100644 --- a/examples/lib/stories/input/long_press_example.dart +++ b/examples/lib/stories/input/long_press_example.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class LongPressExample extends FlameGame { +class LongPressExample() extends FlameGame { static const String description = ''' In this example we show how to use `LongPressCallbacks`.\n\n The colored squares will turn red when a long press is recognized, @@ -28,17 +28,18 @@ class LongPressExample extends FlameGame { } } -class LongPressSquare extends RectangleComponent with LongPressCallbacks { - LongPressSquare({required Paint paint, required Vector2 position}) - : _originalPaint = paint, - super( +class LongPressSquare({required Paint paint, required Vector2 position}) + extends RectangleComponent + with LongPressCallbacks { + this + : super( position: position, size: Vector2.all(100), paint: paint, anchor: Anchor.center, ); - final Paint _originalPaint; + final Paint _originalPaint = paint; @override void onLongPressStart(LongPressStartEvent event) { diff --git a/examples/lib/stories/input/mouse_cursor_example.dart b/examples/lib/stories/input/mouse_cursor_example.dart index e86933c60c5..c47dfb09897 100644 --- a/examples/lib/stories/input/mouse_cursor_example.dart +++ b/examples/lib/stories/input/mouse_cursor_example.dart @@ -5,7 +5,7 @@ import 'package:flame/palette.dart'; import 'package:flutter/widgets.dart'; import 'package:material_ui/material_ui.dart'; -class MouseCursorExample extends FlameGame with MouseMoveCallbacks { +class MouseCursorExample() extends FlameGame with MouseMoveCallbacks { static const String description = ''' Example showcasing the ability to change the game cursor in runtime hover the little square to see the cursor changing diff --git a/examples/lib/stories/input/mouse_movement_example.dart b/examples/lib/stories/input/mouse_movement_example.dart index 87bffd0c208..872426cf2ab 100644 --- a/examples/lib/stories/input/mouse_movement_example.dart +++ b/examples/lib/stories/input/mouse_movement_example.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class MouseMovementExample extends FlameGame with MouseMoveCallbacks { +class MouseMovementExample() extends FlameGame with MouseMoveCallbacks { static const String description = ''' In this example we show how you can use `MouseMoveCallbacks`.\n\n Move around the mouse on the canvas and the white square will follow it and diff --git a/examples/lib/stories/input/multitap_advanced_example.dart b/examples/lib/stories/input/multitap_advanced_example.dart index d10f4deb112..affefe6aa44 100644 --- a/examples/lib/stories/input/multitap_advanced_example.dart +++ b/examples/lib/stories/input/multitap_advanced_example.dart @@ -4,7 +4,8 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; /// Showcases how to mix tap and drag callbacks -class MultitapAdvancedExample extends FlameGame +class MultitapAdvancedExample() + extends FlameGame with TapCallbacks, DragCallbacks { static const String description = ''' This showcases the use of both `TapCallbacks` and `DragCallbacks` diff --git a/examples/lib/stories/input/multitap_example.dart b/examples/lib/stories/input/multitap_example.dart index 3332c67fb72..e418f1f14be 100644 --- a/examples/lib/stories/input/multitap_example.dart +++ b/examples/lib/stories/input/multitap_example.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; /// Includes an example including advanced detectors -class MultitapExample extends FlameGame with TapCallbacks { +class MultitapExample() extends FlameGame with TapCallbacks { static const String description = ''' In this example we showcase the multi touch capabilities Touch multiple places on the screen and you will see multiple squares drawn, diff --git a/examples/lib/stories/input/overlapping_tap_callbacks_example.dart b/examples/lib/stories/input/overlapping_tap_callbacks_example.dart index c23f1c38fdf..80eb71317c7 100644 --- a/examples/lib/stories/input/overlapping_tap_callbacks_example.dart +++ b/examples/lib/stories/input/overlapping_tap_callbacks_example.dart @@ -4,7 +4,7 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class OverlappingTapCallbacksExample extends FlameGame { +class OverlappingTapCallbacksExample() extends FlameGame { static const String description = ''' In this example we show you that events can choose to continue propagating to underlying components. The middle green square continue to propagate the @@ -24,8 +24,11 @@ class OverlappingTapCallbacksExample extends FlameGame { } } -class TapCallbacksSquare extends RectangleComponent with TapCallbacks { - TapCallbacksSquare({Vector2? position, this.continuePropagation = false}) +class TapCallbacksSquare({ + Vector2? position, + final bool continuePropagation = false, +}) extends RectangleComponent with TapCallbacks { + this : super( position: position ?? Vector2.all(100), size: Vector2.all(100), @@ -34,8 +37,6 @@ class TapCallbacksSquare extends RectangleComponent with TapCallbacks { : PaintExtension.random(withAlpha: 0.9, base: 100), ); - final bool continuePropagation; - @override void onTapDown(TapDownEvent event) { event.continuePropagation = continuePropagation; diff --git a/examples/lib/stories/input/scroll_example.dart b/examples/lib/stories/input/scroll_example.dart index 6d27071fd1d..55e66bd101e 100644 --- a/examples/lib/stories/input/scroll_example.dart +++ b/examples/lib/stories/input/scroll_example.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class ScrollExample extends FlameGame with ScrollCallbacks { +class ScrollExample() extends FlameGame with ScrollCallbacks { static const String description = ''' In this example we show how to use `ScrollCallbacks`.\n\n Scroll over the colored squares to scale them. Scroll anywhere else on the @@ -35,8 +35,10 @@ class ScrollExample extends FlameGame with ScrollCallbacks { } } -class ScrollableSquare extends RectangleComponent with ScrollCallbacks { - ScrollableSquare({required Paint paint, required Vector2 position}) +class ScrollableSquare({required Paint paint, required Vector2 position}) + extends RectangleComponent + with ScrollCallbacks { + this : super( position: position, size: Vector2.all(100), diff --git a/examples/lib/stories/input/secondary_tap_callbacks_example.dart b/examples/lib/stories/input/secondary_tap_callbacks_example.dart index d45df5a35de..69ddb873225 100644 --- a/examples/lib/stories/input/secondary_tap_callbacks_example.dart +++ b/examples/lib/stories/input/secondary_tap_callbacks_example.dart @@ -5,7 +5,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class SecondaryTapCallbacksExample extends FlameGame { +class SecondaryTapCallbacksExample() extends FlameGame { static const String description = ''' In this example we show how to listen to both primary (left) and secondary (right) tap events using the `TapCallbacks` and @@ -20,7 +20,8 @@ class SecondaryTapCallbacksExample extends FlameGame { } } -class TappableSquare extends RectangleComponent +class TappableSquare({Vector2? position}) + extends RectangleComponent with TapCallbacks, SecondaryTapCallbacks { static final Paint _red = BasicPalette.red.paint(); static final Paint _blue = BasicPalette.blue.paint(); @@ -30,7 +31,7 @@ class TappableSquare extends RectangleComponent int counter = 0; - TappableSquare({Vector2? position}) + this : super( position: position ?? Vector2.all(100), size: Vector2.all(100), diff --git a/examples/lib/stories/input/tap_callbacks_example.dart b/examples/lib/stories/input/tap_callbacks_example.dart index a8a8741e0b9..5c734f51413 100644 --- a/examples/lib/stories/input/tap_callbacks_example.dart +++ b/examples/lib/stories/input/tap_callbacks_example.dart @@ -4,7 +4,7 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class TapCallbacksExample extends FlameGame { +class TapCallbacksExample() extends FlameGame { static const String description = ''' In this example we show the `TapCallbacks` mixin functionality. You can add the `TapCallbacks` mixin to any `PositionComponent`.\n\n @@ -18,13 +18,15 @@ class TapCallbacksExample extends FlameGame { } } -class TappableSquare extends RectangleComponent with TapCallbacks { +class TappableSquare({Vector2? position}) + extends RectangleComponent + with TapCallbacks { static final Paint _white = Paint()..color = const Color(0xFFFFFFFF); static final Paint _grey = Paint()..color = const Color(0xFFA5A5A5); bool _beenPressed = false; - TappableSquare({Vector2? position}) + this : super( position: position ?? Vector2.all(100), size: Vector2.all(100), diff --git a/examples/lib/stories/input/tertiary_tap_callbacks_example.dart b/examples/lib/stories/input/tertiary_tap_callbacks_example.dart index e0f989c5cec..77c24f09d5f 100644 --- a/examples/lib/stories/input/tertiary_tap_callbacks_example.dart +++ b/examples/lib/stories/input/tertiary_tap_callbacks_example.dart @@ -5,7 +5,7 @@ import 'package:flame/game.dart'; import 'package:flame/palette.dart'; import 'package:material_ui/material_ui.dart'; -class TertiaryTapCallbacksExample extends FlameGame { +class TertiaryTapCallbacksExample() extends FlameGame { static const String description = ''' In this example we show how to listen to primary (left), secondary (right), and tertiary (middle) tap events at the same time using the `TapCallbacks`, @@ -20,7 +20,8 @@ The squares will change color depending on which button was used to tap them. } } -class TappableSquare extends RectangleComponent +class TappableSquare({Vector2? position}) + extends RectangleComponent with TapCallbacks, SecondaryTapCallbacks, TertiaryTapCallbacks { static final Paint _red = BasicPalette.red.paint(); static final Paint _blue = BasicPalette.blue.paint(); @@ -31,7 +32,7 @@ class TappableSquare extends RectangleComponent int counter = 0; - TappableSquare({Vector2? position}) + this : super( position: position ?? Vector2.all(100), size: Vector2.all(100), diff --git a/examples/lib/stories/layout/align_component.dart b/examples/lib/stories/layout/align_component.dart index e4296441ba9..cb27ba87d35 100644 --- a/examples/lib/stories/layout/align_component.dart +++ b/examples/lib/stories/layout/align_component.dart @@ -3,7 +3,7 @@ import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/layout.dart'; -class AlignComponentExample extends FlameGame { +class AlignComponentExample() extends FlameGame { static const String description = ''' In this example the AlignComponent is used to arrange the circles so that there is one in the middle and 8 more surrounding it in diff --git a/examples/lib/stories/parallax/advanced_parallax_example.dart b/examples/lib/stories/parallax/advanced_parallax_example.dart index 0a6d8852514..c1d14b54b7e 100644 --- a/examples/lib/stories/parallax/advanced_parallax_example.dart +++ b/examples/lib/stories/parallax/advanced_parallax_example.dart @@ -4,7 +4,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; -class AdvancedParallaxExample extends FlameGame { +class AdvancedParallaxExample() extends FlameGame { static const String description = ''' Shows how to create a parallax with different velocity deltas on each layer. '''; diff --git a/examples/lib/stories/parallax/animation_parallax_example.dart b/examples/lib/stories/parallax/animation_parallax_example.dart index eeafef3900e..95194284b28 100644 --- a/examples/lib/stories/parallax/animation_parallax_example.dart +++ b/examples/lib/stories/parallax/animation_parallax_example.dart @@ -3,7 +3,7 @@ import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; import 'package:flutter/painting.dart'; -class AnimationParallaxExample extends FlameGame { +class AnimationParallaxExample() extends FlameGame { static const String description = ''' Shows how to use animations in a `ParallaxComponent`. '''; diff --git a/examples/lib/stories/parallax/basic_parallax_example.dart b/examples/lib/stories/parallax/basic_parallax_example.dart index 874edb045fb..3b7ee88979d 100644 --- a/examples/lib/stories/parallax/basic_parallax_example.dart +++ b/examples/lib/stories/parallax/basic_parallax_example.dart @@ -4,7 +4,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; -class BasicParallaxExample extends FlameGame { +class BasicParallaxExample() extends FlameGame { static const String description = ''' Shows the simplest way to use a fullscreen `ParallaxComponent`. '''; diff --git a/examples/lib/stories/parallax/component_parallax_example.dart b/examples/lib/stories/parallax/component_parallax_example.dart index 88fc5e993f0..1d52552dd36 100644 --- a/examples/lib/stories/parallax/component_parallax_example.dart +++ b/examples/lib/stories/parallax/component_parallax_example.dart @@ -5,7 +5,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; -class ComponentParallaxExample extends FlameGame { +class ComponentParallaxExample() extends FlameGame { static const String description = ''' Shows how to do initiation and loading of assets from within an extended `ParallaxComponent`. This example uses a `FixedResolutionViewport` which @@ -21,7 +21,8 @@ class ComponentParallaxExample extends FlameGame { } } -class MyParallaxComponent extends ParallaxComponent { +class MyParallaxComponent() + extends ParallaxComponent { @override Future onLoad() async { parallax = await gameRef.loadParallax( diff --git a/examples/lib/stories/parallax/no_fcs_parallax_example.dart b/examples/lib/stories/parallax/no_fcs_parallax_example.dart index 0c288b03e00..c3dce615bdb 100644 --- a/examples/lib/stories/parallax/no_fcs_parallax_example.dart +++ b/examples/lib/stories/parallax/no_fcs_parallax_example.dart @@ -4,7 +4,7 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; -class NoFCSParallaxExample extends Game { +class NoFCSParallaxExample() extends Game { static const String description = ''' This examples serves to test the Parallax feature outside of the Flame Component System (FCS), use the other files in this folder for examples on diff --git a/examples/lib/stories/parallax/sandbox_layer_parallax_example.dart b/examples/lib/stories/parallax/sandbox_layer_parallax_example.dart index eb1c6ab28a4..ec566d5fd58 100644 --- a/examples/lib/stories/parallax/sandbox_layer_parallax_example.dart +++ b/examples/lib/stories/parallax/sandbox_layer_parallax_example.dart @@ -3,25 +3,18 @@ import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; import 'package:flutter/painting.dart'; -class SandboxLayerParallaxExample extends FlameGame { +class SandboxLayerParallaxExample({ + required final Vector2 planeSpeed, + required final ImageRepeat planeRepeat, + required final LayerFill planeFill, + required final Alignment planeAlignment, +}) extends FlameGame { static const String description = ''' In this example, properties of a layer can be changed to preview the different combination of values. You can change the properties by pressing the pen in the upper right corner. '''; - final Vector2 planeSpeed; - final ImageRepeat planeRepeat; - final LayerFill planeFill; - final Alignment planeAlignment; - - SandboxLayerParallaxExample({ - required this.planeSpeed, - required this.planeRepeat, - required this.planeFill, - required this.planeAlignment, - }); - @override Future onLoad() async { final bgLayer = await loadParallaxLayer( diff --git a/examples/lib/stories/parallax/small_parallax_example.dart b/examples/lib/stories/parallax/small_parallax_example.dart index 75a8bdbde4a..1c4446fee30 100644 --- a/examples/lib/stories/parallax/small_parallax_example.dart +++ b/examples/lib/stories/parallax/small_parallax_example.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; -class SmallParallaxExample extends FlameGame { +class SmallParallaxExample() extends FlameGame { static const String description = ''' Shows how to create a smaller parallax in the center of the screen. '''; diff --git a/examples/lib/stories/rendering/decorator_hue_example.dart b/examples/lib/stories/rendering/decorator_hue_example.dart index 38bd71c8b92..1bf2eb47f1a 100644 --- a/examples/lib/stories/rendering/decorator_hue_example.dart +++ b/examples/lib/stories/rendering/decorator_hue_example.dart @@ -6,7 +6,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; -class DecoratorHueExample extends FlameGame with TapCallbacks { +class DecoratorHueExample() extends FlameGame with TapCallbacks { static const String description = ''' This example demonstrates the usage of `HueDecorator` to shift the colors of a component. diff --git a/examples/lib/stories/rendering/decorator_vs_effect_example.dart b/examples/lib/stories/rendering/decorator_vs_effect_example.dart index ac2a6643d73..a7cf8ba59c6 100644 --- a/examples/lib/stories/rendering/decorator_vs_effect_example.dart +++ b/examples/lib/stories/rendering/decorator_vs_effect_example.dart @@ -6,7 +6,7 @@ import 'package:flame/game.dart'; import 'package:flame/rendering.dart'; import 'package:flutter/widgets.dart'; -class DecoratorVsEffectExample extends FlameGame { +class DecoratorVsEffectExample() extends FlameGame { static const String description = ''' This example demonstrates the difference between using an `Effect` and a `Decorator` for group transparency. @@ -79,11 +79,8 @@ Note how the overlapping area is uniform. } /// A simple decorator that applies opacity to the entire decorated subtree. -class _GroupOpacityDecorator extends Decorator { - _GroupOpacityDecorator(double opacity) - : _paint = Paint()..color = Color.fromRGBO(255, 255, 255, opacity); - - final Paint _paint; +class _GroupOpacityDecorator(double opacity) extends Decorator { + final Paint _paint = Paint()..color = Color.fromRGBO(255, 255, 255, opacity); @override void apply(void Function(Canvas) draw, Canvas canvas) { diff --git a/examples/lib/stories/rendering/flip_sprite_example.dart b/examples/lib/stories/rendering/flip_sprite_example.dart index 4308d0f460d..ada3f6a3294 100644 --- a/examples/lib/stories/rendering/flip_sprite_example.dart +++ b/examples/lib/stories/rendering/flip_sprite_example.dart @@ -1,7 +1,7 @@ import 'package:examples/commons/ember.dart'; import 'package:flame/game.dart'; -class FlipSpriteExample extends FlameGame { +class FlipSpriteExample() extends FlameGame { static const String description = ''' In this example we show how you can flip components horizontally and vertically. diff --git a/examples/lib/stories/rendering/isometric_tile_map_example.dart b/examples/lib/stories/rendering/isometric_tile_map_example.dart index b5989b9b970..28e5be5dc6c 100644 --- a/examples/lib/stories/rendering/isometric_tile_map_example.dart +++ b/examples/lib/stories/rendering/isometric_tile_map_example.dart @@ -6,7 +6,9 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flame/sprite.dart'; -class IsometricTileMapExample extends FlameGame with MouseMoveCallbacks { +class IsometricTileMapExample({required final bool halfSize}) + extends FlameGame + with MouseMoveCallbacks { static const String description = ''' Shows an example of how to use the `IsometricTileMapComponent`.\n\n Move the mouse over the board to see a selector appearing on the tiles. @@ -21,15 +23,12 @@ class IsometricTileMapExample extends FlameGame with MouseMoveCallbacks { final originColor = Paint()..color = const Color(0xFFFF00FF); final originColor2 = Paint()..color = const Color(0xFFAA55FF); - final bool halfSize; late final tileHeight = scale * (halfSize ? 8.0 : 16.0); late final suffix = halfSize ? '-short' : ''; late IsometricTileMapComponent base; late Selector selector; - IsometricTileMapExample({required this.halfSize}); - @override Future onLoad() async { final tilesetImage = await images.load( @@ -83,10 +82,10 @@ class IsometricTileMapExample extends FlameGame with MouseMoveCallbacks { } } -class Selector extends SpriteComponent { +class Selector(double s, Image image) extends SpriteComponent { bool show = true; - Selector(double s, Image image) + this : super( sprite: Sprite(image, srcSize: Vector2.all(32.0)), size: Vector2.all(s), diff --git a/examples/lib/stories/rendering/layers_example.dart b/examples/lib/stories/rendering/layers_example.dart index 8ef6a31b708..d6564eabf24 100644 --- a/examples/lib/stories/rendering/layers_example.dart +++ b/examples/lib/stories/rendering/layers_example.dart @@ -4,7 +4,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/layers.dart'; -class LayerExample extends FlameGame { +class LayerExample() extends FlameGame { static const String description = ''' In this example we show how layers can be used to produce a shadow effect. '''; @@ -39,11 +39,9 @@ class LayerExample extends FlameGame { Color backgroundColor() => const Color(0xFF38607C); } -class GameLayer extends DynamicLayer { - final Sprite playerSprite; - final Sprite enemySprite; - - GameLayer(this.playerSprite, this.enemySprite) { +class GameLayer(final Sprite playerSprite, final Sprite enemySprite) + extends DynamicLayer { + this { preProcessors.add(ShadowProcessor()); } @@ -62,10 +60,8 @@ class GameLayer extends DynamicLayer { } } -class BackgroundLayer extends PreRenderedLayer { - final Sprite sprite; - - BackgroundLayer(this.sprite) { +class BackgroundLayer(final Sprite sprite) extends PreRenderedLayer { + this { preProcessors.add(ShadowProcessor()); } diff --git a/examples/lib/stories/rendering/nine_tile_box_custom_grid_example.dart b/examples/lib/stories/rendering/nine_tile_box_custom_grid_example.dart index 49212bae8c2..895b94a4bb3 100644 --- a/examples/lib/stories/rendering/nine_tile_box_custom_grid_example.dart +++ b/examples/lib/stories/rendering/nine_tile_box_custom_grid_example.dart @@ -2,7 +2,8 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class NineTileBoxCustomGridExample extends FlameGame +class NineTileBoxCustomGridExample() + extends FlameGame with TapCallbacks, DoubleTapCallbacks { static const String description = ''' If you want to create a background for something that can stretch you can diff --git a/examples/lib/stories/rendering/nine_tile_box_example.dart b/examples/lib/stories/rendering/nine_tile_box_example.dart index 2a594dc92d4..f3ef98c0a3c 100644 --- a/examples/lib/stories/rendering/nine_tile_box_example.dart +++ b/examples/lib/stories/rendering/nine_tile_box_example.dart @@ -2,7 +2,8 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class NineTileBoxExample extends FlameGame +class NineTileBoxExample() + extends FlameGame with TapCallbacks, DoubleTapCallbacks { static const String description = ''' If you want to create a background for something that can stretch you can diff --git a/examples/lib/stories/rendering/particles_example.dart b/examples/lib/stories/rendering/particles_example.dart index 2be1c995338..1ee1df9e34c 100644 --- a/examples/lib/stories/rendering/particles_example.dart +++ b/examples/lib/stories/rendering/particles_example.dart @@ -7,7 +7,7 @@ import 'package:flame/geometry.dart'; import 'package:flame/particles.dart'; import 'package:material_ui/material_ui.dart' hide Image; -class ParticlesExample extends FlameGame { +class ParticlesExample() extends FlameGame { static const String description = ''' Showcases the declarative particle system. Every effect is built from ParticleEmitterComponents: reusable ParticleEmitter presets describe what @@ -369,12 +369,14 @@ class ParticlesExample extends FlameGame { } /// Moves its emitter child along a Lissajous-like path. -class _OrbitingEmitter extends PositionComponent { - _OrbitingEmitter({required this.orbit, required PositionComponent child}) { +class _OrbitingEmitter({ + required final Vector2 orbit, + required PositionComponent child, +}) extends PositionComponent { + this { add(child); } - final Vector2 orbit; late final Vector2 _center = position.clone(); double _time = 0; @@ -391,8 +393,10 @@ class _OrbitingEmitter extends PositionComponent { /// Displays the frame rate and the total number of live particles across /// all emitters, refreshed a few times per second. -class _StatsText extends TextComponent with HasGameRef { - _StatsText({super.position, super.anchor}) +class _StatsText({super.position, super.anchor}) + extends TextComponent + with HasGameRef { + this : super( textRenderer: TextPaint( style: const TextStyle(color: Colors.white70, fontSize: 13), diff --git a/examples/lib/stories/rendering/particles_interactive_example.dart b/examples/lib/stories/rendering/particles_interactive_example.dart index 4df17024096..7b46a226987 100644 --- a/examples/lib/stories/rendering/particles_interactive_example.dart +++ b/examples/lib/stories/rendering/particles_interactive_example.dart @@ -8,7 +8,7 @@ import 'package:flame/particles.dart'; import 'package:material_ui/material_ui.dart' hide Image; /// The effect presets selectable in the knobs panel. -enum ParticleEffect { +enum ParticleEffect() { sparkles, fire, smoke, @@ -19,7 +19,11 @@ enum ParticleEffect { bubbles, } -class ParticlesInteractiveExample extends FlameGame with DragCallbacks { +class ParticlesInteractiveExample({ + /// The selected effect preset. + required final ParticleEffect effect, + required double zoom, +}) extends FlameGame with DragCallbacks { static const description = 'Drag around the canvas to paint with particles, and pick an effect in ' 'the knobs panel to try the different emitter presets and renderers. ' @@ -28,18 +32,13 @@ class ParticlesInteractiveExample extends FlameGame with DragCallbacks { 'releases more from the preallocated buffer, so no objects are ' 'allocated while you draw.'; - ParticlesInteractiveExample({ - required this.effect, - required double zoom, - }) : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - )..viewfinder.zoom = zoom, - ); - - /// The selected effect preset. - final ParticleEffect effect; + this + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + )..viewfinder.zoom = zoom, + ); late ParticleEmitterComponent _emitter; diff --git a/examples/lib/stories/rendering/rich_text_example.dart b/examples/lib/stories/rendering/rich_text_example.dart index 7dd5e3d2e83..9cdf92e3e3d 100644 --- a/examples/lib/stories/rendering/rich_text_example.dart +++ b/examples/lib/stories/rendering/rich_text_example.dart @@ -3,12 +3,10 @@ import 'package:flame/game.dart'; import 'package:flame/text.dart'; import 'package:flutter/painting.dart'; -class RichTextExample extends FlameGame { - final TextAlign textAlign; - final double width; - - RichTextExample({this.textAlign = TextAlign.left, this.width = 400}); - +class RichTextExample({ + final TextAlign textAlign = TextAlign.left, + final double width = 400, +}) extends FlameGame { static const String description = 'A non-interactive example of how to render rich text in Flame.'; diff --git a/examples/lib/stories/rendering/text_box_example.dart b/examples/lib/stories/rendering/text_box_example.dart index 913a0c71164..ce4152d865b 100644 --- a/examples/lib/stories/rendering/text_box_example.dart +++ b/examples/lib/stories/rendering/text_box_example.dart @@ -5,16 +5,12 @@ import 'package:flame/experimental.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; -enum TextBoxConfigMaxWidth { +enum TextBoxConfigMaxWidth(final double value) { small(200), - large(640); - - const TextBoxConfigMaxWidth(this.value); - - final double value; + large(640), } -class TextBoxExample extends FlameGame { +class TextBoxExample() extends FlameGame { static const String description = 'TextBoxComponent reflows text when boxConfig.maxWidth is changed'; diff --git a/examples/lib/stories/rendering/text_example.dart b/examples/lib/stories/rendering/text_example.dart index 2b3eef7366c..ee3a0c2b8e5 100644 --- a/examples/lib/stories/rendering/text_example.dart +++ b/examples/lib/stories/rendering/text_example.dart @@ -7,7 +7,7 @@ import 'package:flame/palette.dart'; import 'package:flame/text.dart'; import 'package:material_ui/material_ui.dart'; -class TextExample extends FlameGame { +class TextExample() extends FlameGame { static const String description = ''' In this example we show different ways of rendering text. '''; @@ -145,26 +145,27 @@ final _shaded = TextPaint( ), ); -class MyTextBox extends TextBoxComponent { +class MyTextBox( + String text, { + super.align, + super.size, + double? timePerChar, + double? margins, +}) extends TextBoxComponent { late Paint bgPaint; late Rect bgRect; - MyTextBox( - String text, { - super.align, - super.size, - double? timePerChar, - double? margins, - }) : super( - text: text, - textRenderer: _box, - boxConfig: TextBoxConfig( - maxWidth: 400, - timePerChar: timePerChar ?? 0.05, - growingBox: true, - margins: EdgeInsets.all(margins ?? 25), - ), - ); + this + : super( + text: text, + textRenderer: _box, + boxConfig: TextBoxConfig( + maxWidth: 400, + timePerChar: timePerChar ?? 0.05, + growingBox: true, + margins: EdgeInsets.all(margins ?? 25), + ), + ); @override Future onLoad() { @@ -185,17 +186,17 @@ class MyTextBox extends TextBoxComponent { } } -class MyScrollTextBox extends ScrollTextBoxComponent { +class MyScrollTextBox( + String text, { + required super.size, + super.boxConfig, + super.position, + super.anchor, +}) extends ScrollTextBoxComponent { late Paint bgPaint; late Rect backgroundRect; - MyScrollTextBox( - String text, { - required super.size, - super.boxConfig, - super.position, - super.anchor, - }) : super(text: text, textRenderer: _box); + this : super(text: text, textRenderer: _box); @override FutureOr onLoad() { diff --git a/examples/lib/stories/router/router_world_example.dart b/examples/lib/stories/router/router_world_example.dart index 284735749aa..1c1249b8fe1 100644 --- a/examples/lib/stories/router/router_world_example.dart +++ b/examples/lib/stories/router/router_world_example.dart @@ -7,7 +7,7 @@ import 'package:flame/rendering.dart'; import 'package:flutter/rendering.dart'; import 'package:material_ui/material_ui.dart' show Colors; -class RouterWorldExample extends FlameGame { +class RouterWorldExample() extends FlameGame { static const description = ''' This example shows how to use the RouterComponent to navigate between different worlds and pages. @@ -31,8 +31,8 @@ different worlds and pages. } } -class StartPage extends Component with HasGameRef { - StartPage() { +class StartPage() extends Component with HasGameRef { + this { addAll([ _logo = TextComponent( text: 'Your Game', @@ -73,31 +73,22 @@ class StartPage extends Component with HasGameRef { } } -class Background extends Component { - Background(this.color); - final Color color; - +class Background(final Color color) extends Component { @override void render(Canvas canvas) { canvas.drawColor(color, BlendMode.srcATop); } } -class RoundedButton extends PositionComponent with TapCallbacks { - RoundedButton({ - required this.text, - required this.action, - required Color color, - required Color borderColor, - super.position, - super.anchor = Anchor.center, - }) : _textDrawable = TextPaint( - style: const TextStyle( - fontSize: 20, - color: Color(0xFF000000), - fontWeight: FontWeight.w800, - ), - ).toTextPainter(text) { +class RoundedButton({ + required final String text, + required final void Function() action, + required Color color, + required Color borderColor, + super.position, + super.anchor = Anchor.center, +}) extends PositionComponent with TapCallbacks { + this { size = Vector2(150, 40); _textOffset = Offset( (size.x - _textDrawable.width) / 2, @@ -111,9 +102,13 @@ class RoundedButton extends PositionComponent with TapCallbacks { ..color = borderColor; } - final String text; - final void Function() action; - final TextPainter _textDrawable; + final TextPainter _textDrawable = TextPaint( + style: const TextStyle( + fontSize: 20, + color: Color(0xFF000000), + fontWeight: FontWeight.w800, + ), + ).toTextPainter(text); late final Offset _textOffset; late final RRect _rrect; late final Paint _borderPaint; @@ -143,8 +138,10 @@ class RoundedButton extends PositionComponent with TapCallbacks { } } -abstract class SimpleButton extends PositionComponent with TapCallbacks { - SimpleButton(this._iconPath, {super.position}) : super(size: Vector2.all(40)); +abstract class SimpleButton(final Path _iconPath, {super.position}) + extends PositionComponent + with TapCallbacks { + this : super(size: Vector2.all(40)); final Paint _borderPaint = Paint() ..style = PaintingStyle.stroke @@ -153,8 +150,6 @@ abstract class SimpleButton extends PositionComponent with TapCallbacks { ..style = PaintingStyle.stroke ..color = const Color(0xffaaaaaa) ..strokeWidth = 7; - final Path _iconPath; - void action(); @override @@ -183,8 +178,8 @@ abstract class SimpleButton extends PositionComponent with TapCallbacks { } } -class BackButton extends SimpleButton with HasGameRef { - BackButton() +class BackButton() extends SimpleButton with HasGameRef { + this : super( Path() ..moveTo(22, 8) @@ -199,8 +194,8 @@ class BackButton extends SimpleButton with HasGameRef { void action() => gameRef.router.pop(); } -class PauseButton extends SimpleButton with HasGameRef { - PauseButton() +class PauseButton() extends SimpleButton with HasGameRef { + this : super( Path() ..moveTo(14, 10) @@ -223,7 +218,7 @@ class PauseButton extends SimpleButton with HasGameRef { } } -class Level1Page extends DecoratedWorld with HasGameRef { +class Level1Page() extends DecoratedWorld with HasGameRef { @override Future onLoad() async { addAll([ @@ -270,7 +265,7 @@ class Level1Page extends DecoratedWorld with HasGameRef { } } -class Level2Page extends DecoratedWorld with HasGameRef { +class Level2Page() extends DecoratedWorld with HasGameRef { @override Future onLoad() async { addAll([ @@ -327,13 +322,12 @@ class Level2Page extends DecoratedWorld with HasGameRef { } } -class Planet extends CircleComponent - with TapCallbacks, HasGameRef { - Planet({ - required super.radius, - required Color color, - super.children, - }) : super(paint: Paint()..color = color, anchor: Anchor.center); +class Planet({ + required super.radius, + required Color color, + super.children, +}) extends CircleComponent with TapCallbacks, HasGameRef { + this : super(paint: Paint()..color = color, anchor: Anchor.center); @override void onTapDown(TapDownEvent event) { @@ -345,21 +339,19 @@ class Planet extends CircleComponent } } -class Orbit extends CircleComponent { - Orbit({ - required super.radius, - required this.planet, - required this.revolutionPeriod, - }) : super( - children: [planet], - anchor: Anchor.center, - paint: Paint() - ..style = PaintingStyle.stroke - ..color = const Color(0x888888aa), - ); - - final double revolutionPeriod; - final Planet planet; +class Orbit({ + required super.radius, + required final Planet planet, + required final double revolutionPeriod, +}) extends CircleComponent { + this + : super( + children: [planet], + anchor: Anchor.center, + paint: Paint() + ..style = PaintingStyle.stroke + ..color = const Color(0x888888aa), + ); @override Future onLoad() async { @@ -379,8 +371,8 @@ class Orbit extends CircleComponent { } } -class PauseRoute extends Route { - PauseRoute() : super(PausePage.new, transparent: true); +class PauseRoute() extends Route { + this : super(PausePage.new, transparent: true); @override void onPush(Route? previousRoute) { @@ -400,7 +392,8 @@ class PauseRoute extends Route { } } -class PausePage extends Component +class PausePage() + extends Component with TapCallbacks, HasGameRef { @override Future onLoad() async { @@ -431,7 +424,7 @@ class PausePage extends Component void onTapUp(TapUpEvent event) => gameRef.router.pop(); } -class DecoratedWorld extends World with CustomTraversal, HasTimeScale { +class DecoratedWorld() extends World with CustomTraversal, HasTimeScale { PaintDecorator? decorator; @override @@ -444,8 +437,8 @@ class DecoratedWorld extends World with CustomTraversal, HasTimeScale { } } -class YesNoDialog extends ValueRoute { - YesNoDialog() : super(value: false); +class YesNoDialog() extends ValueRoute { + this : super(value: false); @override Component build() { diff --git a/examples/lib/stories/sprites/base64_sprite_example.dart b/examples/lib/stories/sprites/base64_sprite_example.dart index 22cf6702d9b..9e483758139 100644 --- a/examples/lib/stories/sprites/base64_sprite_example.dart +++ b/examples/lib/stories/sprites/base64_sprite_example.dart @@ -1,7 +1,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; -class Base64SpriteExample extends FlameGame { +class Base64SpriteExample() extends FlameGame { static const String description = ''' In this example we load a sprite from the a base64 string and put it into a `SpriteComponent`. diff --git a/examples/lib/stories/sprites/basic_sprite_example.dart b/examples/lib/stories/sprites/basic_sprite_example.dart index 0cb03f40144..c53d0b9118c 100644 --- a/examples/lib/stories/sprites/basic_sprite_example.dart +++ b/examples/lib/stories/sprites/basic_sprite_example.dart @@ -1,7 +1,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; -class BasicSpriteExample extends FlameGame { +class BasicSpriteExample() extends FlameGame { static const String description = ''' In this example we load a sprite from the assets folder and put it into a `SpriteComponent`. diff --git a/examples/lib/stories/sprites/sprite_batch_bleed_example.dart b/examples/lib/stories/sprites/sprite_batch_bleed_example.dart index 71e8680bf79..35f0b4c0c74 100644 --- a/examples/lib/stories/sprites/sprite_batch_bleed_example.dart +++ b/examples/lib/stories/sprites/sprite_batch_bleed_example.dart @@ -5,7 +5,7 @@ import 'package:flame/game.dart'; import 'package:flame/sprite.dart'; import 'package:material_ui/material_ui.dart'; -class SpriteBatchBleedExample extends FlameGame { +class SpriteBatchBleedExample() extends FlameGame { static const String description = ''' In this example we show how `bleed` can be used to prevent edge artifacts (seams) between tiles when rendering with `SpriteBatch`. diff --git a/examples/lib/stories/sprites/sprite_batch_example.dart b/examples/lib/stories/sprites/sprite_batch_example.dart index f81cee3e2df..c02f18fe935 100644 --- a/examples/lib/stories/sprites/sprite_batch_example.dart +++ b/examples/lib/stories/sprites/sprite_batch_example.dart @@ -5,7 +5,7 @@ import 'package:flame/game.dart'; import 'package:flame/sprite.dart'; import 'package:material_ui/material_ui.dart'; -class SpriteBatchExample extends FlameGame { +class SpriteBatchExample() extends FlameGame { static const String description = ''' In this example we show how to render many sprites in a batch for efficiency, this is done with `SpriteBatch` and the `SpriteBatchComponent`. diff --git a/examples/lib/stories/sprites/sprite_batch_load_example.dart b/examples/lib/stories/sprites/sprite_batch_load_example.dart index cc7b5daf352..d97ec295b7f 100644 --- a/examples/lib/stories/sprites/sprite_batch_load_example.dart +++ b/examples/lib/stories/sprites/sprite_batch_load_example.dart @@ -5,7 +5,7 @@ import 'package:flame/game.dart'; import 'package:flame/sprite.dart'; import 'package:material_ui/material_ui.dart'; -class SpriteBatchLoadExample extends FlameGame { +class SpriteBatchLoadExample() extends FlameGame { static const String description = ''' In this example we do the same thing as in the normal sprite batch example, but in this example the logic and loading is moved into a component that @@ -18,9 +18,10 @@ class SpriteBatchLoadExample extends FlameGame { } } -class MySpriteBatchComponent extends SpriteBatchComponent +class MySpriteBatchComponent() + extends SpriteBatchComponent with HasGameRef { - MySpriteBatchComponent() + this : super( blendMode: BlendMode.srcOver, ); diff --git a/examples/lib/stories/sprites/sprite_group_example.dart b/examples/lib/stories/sprites/sprite_group_example.dart index 29295652755..389a3b7bbec 100644 --- a/examples/lib/stories/sprites/sprite_group_example.dart +++ b/examples/lib/stories/sprites/sprite_group_example.dart @@ -2,9 +2,12 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -enum ButtonState { unpressed, pressed } +enum ButtonState() { + unpressed, + pressed, +} -class SpriteGroupExample extends FlameGame { +class SpriteGroupExample() extends FlameGame { static const String description = ''' In this example we show how a `SpriteGroupComponent` can be used to create a button which displays different sprites depending on whether it is pressed @@ -22,7 +25,8 @@ class SpriteGroupExample extends FlameGame { } } -class ButtonComponent extends SpriteGroupComponent +class ButtonComponent() + extends SpriteGroupComponent with HasGameRef, TapCallbacks { @override Future onLoad() async { diff --git a/examples/lib/stories/sprites/sprite_sheet_example.dart b/examples/lib/stories/sprites/sprite_sheet_example.dart index dd724d15aee..db671b63983 100644 --- a/examples/lib/stories/sprites/sprite_sheet_example.dart +++ b/examples/lib/stories/sprites/sprite_sheet_example.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/sprite.dart'; -class SpriteSheetExample extends FlameGame { +class SpriteSheetExample() extends FlameGame { static const String description = ''' In this example we show how to load images and how to create animations from sprite sheets. diff --git a/examples/lib/stories/structure/levels.dart b/examples/lib/stories/structure/levels.dart index 21cd9af3563..d182352af88 100644 --- a/examples/lib/stories/structure/levels.dart +++ b/examples/lib/stories/structure/levels.dart @@ -6,7 +6,7 @@ import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:material_ui/material_ui.dart'; -class LevelsExample extends FlameGame { +class LevelsExample() extends FlameGame { static const String description = ''' In this example we showcase how you can utilize World components as levels. Press the different buttons in the bottom to change levels and press in the @@ -14,7 +14,7 @@ class LevelsExample extends FlameGame { meanwhile the one called Resettable always resets. '''; - LevelsExample() : super(world: ResettableLevel()); + this : super(world: ResettableLevel()); late final TextComponent header; @@ -58,7 +58,7 @@ class LevelsExample extends FlameGame { } } -class ResettableLevel extends Level { +class ResettableLevel() extends Level { @override Future onLoad() async { add( @@ -73,7 +73,7 @@ class ResettableLevel extends Level { } } -class Level1 extends Level { +class Level1() extends Level { @override Future onLoad() async { add(Ember()); @@ -81,7 +81,7 @@ class Level1 extends Level { } } -class Level2 extends Level { +class Level2() extends Level { @override Future onLoad() async { add(Ember(position: Vector2(-100, 0))); @@ -90,7 +90,7 @@ class Level2 extends Level { } } -class Level3 extends Level { +class Level3() extends Level { @override Future onLoad() async { add(Ember(position: Vector2(-100, -50))); @@ -100,15 +100,16 @@ class Level3 extends Level { } } -class Level extends World with HasGameRef, TapCallbacks { +class Level() extends World with HasGameRef, TapCallbacks { @override void onTapDown(TapDownEvent event) { add(Ember(position: event.localPosition)); } } -class LevelButton extends ButtonComponent { - LevelButton(String text, {super.onPressed, super.position}) +class LevelButton(String text, {super.onPressed, super.position}) + extends ButtonComponent { + this : super( button: ButtonBackground(Colors.white), buttonDown: ButtonBackground(Colors.orangeAccent), @@ -124,8 +125,10 @@ class LevelButton extends ButtonComponent { ); } -class ButtonBackground extends PositionComponent with HasAncestor { - ButtonBackground(Color color) { +class ButtonBackground(Color color) + extends PositionComponent + with HasAncestor { + this { _paint.color = color; } diff --git a/examples/lib/stories/svg/svg_component.dart b/examples/lib/stories/svg/svg_component.dart index 0855e5cbde2..b8628cb23fb 100644 --- a/examples/lib/stories/svg/svg_component.dart +++ b/examples/lib/stories/svg/svg_component.dart @@ -5,8 +5,8 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flame_svg/flame_svg.dart'; -class Player extends SvgComponent with HasGameRef { - Player() : super(priority: 3, size: Vector2(106, 146), anchor: Anchor.center); +class Player() extends SvgComponent with HasGameRef { + this : super(priority: 3, size: Vector2(106, 146), anchor: Anchor.center); Vector2? destination; @@ -33,8 +33,8 @@ class Player extends SvgComponent with HasGameRef { } } -class Background extends SvgComponent with HasGameRef { - Background() +class Background() extends SvgComponent with HasGameRef { + this : super( priority: 1, size: Vector2(745, 415), @@ -49,8 +49,10 @@ class Background extends SvgComponent with HasGameRef { } } -class Balloons extends SvgComponent with HasGameRef { - Balloons({super.position}) +class Balloons({super.position}) + extends SvgComponent + with HasGameRef { + this : super( priority: 2, size: Vector2(75, 125), @@ -67,7 +69,7 @@ class Balloons extends SvgComponent with HasGameRef { } } -class SvgComponentExample extends FlameGame { +class SvgComponentExample() extends FlameGame { static const description = ''' Simple game showcasing how to use SVGs inside a flame game. This game uses several SVGs for its graphics. Click or touch the screen to make the @@ -75,7 +77,7 @@ class SvgComponentExample extends FlameGame { clicked position. '''; - SvgComponentExample() + this : super( camera: CameraComponent.withFixedResolution( width: 400, @@ -85,7 +87,7 @@ class SvgComponentExample extends FlameGame { ); } -class _SvgComponentWorld extends World with TapCallbacks, DoubleTapCallbacks { +class _SvgComponentWorld() extends World with TapCallbacks, DoubleTapCallbacks { late Player player; @override diff --git a/examples/lib/stories/system/overlays_example.dart b/examples/lib/stories/system/overlays_example.dart index 7401f3ef840..c1264f4151e 100644 --- a/examples/lib/stories/system/overlays_example.dart +++ b/examples/lib/stories/system/overlays_example.dart @@ -3,7 +3,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class OverlaysExample extends FlameGame with TapCallbacks { +class OverlaysExample() extends FlameGame with TapCallbacks { static const String description = ''' In this example we show how the overlays system can be used.\n\n If you tap the canvas the game will start and if you tap it again it will @@ -94,9 +94,7 @@ Widget _secondaryMenuBuilder(BuildContext buildContext, OverlaysExample game) { ); } -class OverlaysExampleWidget extends StatelessWidget { - const OverlaysExampleWidget({super.key}); - +class const OverlaysExampleWidget({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return GameWidget.managed( diff --git a/examples/lib/stories/system/pause_resume_example.dart b/examples/lib/stories/system/pause_resume_example.dart index 1fb26048743..0e3ceb7b126 100644 --- a/examples/lib/stories/system/pause_resume_example.dart +++ b/examples/lib/stories/system/pause_resume_example.dart @@ -2,7 +2,8 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flame/game.dart'; -class PauseResumeExample extends FlameGame +class PauseResumeExample() + extends FlameGame with TapCallbacks, DoubleTapCallbacks { static const description = ''' Demonstrate how to use the pause and resume engine methods and isPaused diff --git a/examples/lib/stories/system/resize_example.dart b/examples/lib/stories/system/resize_example.dart index 664d1e68fc3..90a95e1add4 100644 --- a/examples/lib/stories/system/resize_example.dart +++ b/examples/lib/stories/system/resize_example.dart @@ -3,8 +3,8 @@ import 'dart:ui'; import 'package:flame/components.dart'; import 'package:flame/game.dart'; -class ResizingRectangle extends RectangleComponent { - ResizingRectangle() +class ResizingRectangle() extends RectangleComponent { + this : super( paint: Paint()..color = const Color(0xFFFE4813), ); @@ -17,8 +17,8 @@ class ResizingRectangle extends RectangleComponent { } } -class ResizeExampleGame extends FlameGame { - ResizeExampleGame() : super(children: [ResizingRectangle()]); +class ResizeExampleGame() extends FlameGame { + this : super(children: [ResizingRectangle()]); static const description = ''' This example shows how to react to the game being resized. diff --git a/examples/lib/stories/system/step_engine_example.dart b/examples/lib/stories/system/step_engine_example.dart index 5f838c720b4..5ff949dfe0d 100644 --- a/examples/lib/stories/system/step_engine_example.dart +++ b/examples/lib/stories/system/step_engine_example.dart @@ -10,7 +10,8 @@ import 'package:flame/palette.dart'; import 'package:flutter/services.dart'; import 'package:material_ui/material_ui.dart'; -class StepEngineExample extends FlameGame +class StepEngineExample() + extends FlameGame with HasCollisionDetection, HasKeyboardHandlerComponents { static const description = ''' This example demonstrates how the game can be advanced frame by frame using @@ -122,14 +123,12 @@ class StepEngineExample extends FlameGame ); } -class _DetectorComponents extends CircleComponent with CollisionCallbacks { - _DetectorComponents({ - super.radius, - super.position, - super.anchor, - super.children, - }); - +class _DetectorComponents({ + super.radius, + super.position, + super.anchor, + super.children, +}) extends CircleComponent with CollisionCallbacks { @override void onCollisionStart( List intersectionPoints, diff --git a/examples/lib/stories/system/without_flame_game_example.dart b/examples/lib/stories/system/without_flame_game_example.dart index 19686d3100a..33e363dd8d3 100644 --- a/examples/lib/stories/system/without_flame_game_example.dart +++ b/examples/lib/stories/system/without_flame_game_example.dart @@ -4,7 +4,7 @@ import 'package:flame/palette.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; -class NoFlameGameExample extends Game with KeyboardEvents { +class NoFlameGameExample() extends Game with KeyboardEvents { static const String description = ''' This example showcases how to create a game without the FlameGame. It also briefly showcases how to act on keyboard events. diff --git a/examples/lib/stories/tiled/flame_tiled_animation_example.dart b/examples/lib/stories/tiled/flame_tiled_animation_example.dart index 92054ed1e49..12dfff2db56 100644 --- a/examples/lib/stories/tiled/flame_tiled_animation_example.dart +++ b/examples/lib/stories/tiled/flame_tiled_animation_example.dart @@ -1,7 +1,7 @@ import 'package:flame/game.dart'; import 'package:flame_tiled/flame_tiled.dart'; -class FlameTiledAnimationExample extends FlameGame { +class FlameTiledAnimationExample() extends FlameGame { static const String description = ''' Loads and displays an animated Tiled map. '''; diff --git a/examples/lib/stories/utils/timer_component_example.dart b/examples/lib/stories/utils/timer_component_example.dart index e27281a7f65..7e8f7a866cf 100644 --- a/examples/lib/stories/utils/timer_component_example.dart +++ b/examples/lib/stories/utils/timer_component_example.dart @@ -3,7 +3,8 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class TimerComponentExample extends FlameGame +class TimerComponentExample() + extends FlameGame with TapCallbacks, DoubleTapCallbacks { static const String description = ''' This examples showcases the `TimerComponent`.\n\n @@ -29,14 +30,13 @@ class TimerComponentExample extends FlameGame } } -class RenderedTimeComponent extends TimerComponent { +class RenderedTimeComponent(double period, {final double yOffset = 150}) + extends TimerComponent { final TextPaint textPaint = TextPaint( style: const TextStyle(color: Colors.white, fontSize: 20), ); - final double yOffset; - - RenderedTimeComponent(double period, {this.yOffset = 150}) + this : super( period: period, removeOnFinish: true, diff --git a/examples/lib/stories/utils/timer_example.dart b/examples/lib/stories/utils/timer_example.dart index 274fa12e8fa..9b2e230c651 100644 --- a/examples/lib/stories/utils/timer_example.dart +++ b/examples/lib/stories/utils/timer_example.dart @@ -3,7 +3,7 @@ import 'package:flame/game.dart'; import 'package:flame/timer.dart'; import 'package:material_ui/material_ui.dart'; -class TimerExample extends FlameGame with TapCallbacks { +class TimerExample() extends FlameGame with TapCallbacks { static const String description = ''' This example shows how to use the `Timer`.\n\n Tap down to start the countdown timer, it will then count to 5 and then stop diff --git a/examples/lib/stories/widgets/custom_painter_example.dart b/examples/lib/stories/widgets/custom_painter_example.dart index 9cd23da72ef..a637a1791f3 100644 --- a/examples/lib/stories/widgets/custom_painter_example.dart +++ b/examples/lib/stories/widgets/custom_painter_example.dart @@ -3,7 +3,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class CustomPainterExample extends FlameGame with TapCallbacks { +class CustomPainterExample() extends FlameGame with TapCallbacks { static const description = ''' Example demonstration of how to use the CustomPainterComponent. @@ -27,9 +27,7 @@ class CustomPainterExample extends FlameGame with TapCallbacks { } } -class CustomPainterExampleWidget extends StatelessWidget { - const CustomPainterExampleWidget({super.key}); - +class const CustomPainterExampleWidget({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return GameWidget.managed( @@ -65,7 +63,7 @@ class CustomPainterExampleWidget extends StatelessWidget { } } -class PlayerCustomPainter extends CustomPainter { +class PlayerCustomPainter() extends CustomPainter { late final facePaint = Paint()..color = Colors.yellow; late final eyesPaint = Paint()..color = Colors.black; @@ -110,7 +108,8 @@ class PlayerCustomPainter extends CustomPainter { } } -class Player extends CustomPainterComponent +class Player() + extends CustomPainterComponent with HasGameRef { static const speed = 150; diff --git a/examples/lib/stories/widgets/nine_tile_box_example.dart b/examples/lib/stories/widgets/nine_tile_box_example.dart index 42ce3ce4eda..0c7e904731e 100644 --- a/examples/lib/stories/widgets/nine_tile_box_example.dart +++ b/examples/lib/stories/widgets/nine_tile_box_example.dart @@ -1,16 +1,11 @@ import 'package:flame/widgets.dart'; import 'package:flutter/widgets.dart'; -class NineTileBoxWidgetExample extends StatelessWidget { - const NineTileBoxWidgetExample({ - required this.width, - required this.height, - super.key, - }); - - final double width; - final double height; - +class const NineTileBoxWidgetExample({ + required final double width, + required final double height, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return Container( diff --git a/examples/lib/stories/widgets/nine_tile_box_example_with_animation.dart b/examples/lib/stories/widgets/nine_tile_box_example_with_animation.dart index 6133271226b..bfc2f7d5404 100644 --- a/examples/lib/stories/widgets/nine_tile_box_example_with_animation.dart +++ b/examples/lib/stories/widgets/nine_tile_box_example_with_animation.dart @@ -1,15 +1,14 @@ import 'package:flame/widgets.dart'; import 'package:material_ui/material_ui.dart'; -class AnimatedNineTileBoxWidgetExample extends StatefulWidget { - const AnimatedNineTileBoxWidgetExample({super.key}); - +class const AnimatedNineTileBoxWidgetExample({super.key}) + extends StatefulWidget { @override State createState() => _AnimatedNineTileBoxWidgetExampleState(); } -class _AnimatedNineTileBoxWidgetExampleState +class _AnimatedNineTileBoxWidgetExampleState() extends State { var _opacity = 1.0; diff --git a/examples/lib/stories/widgets/partial_sprite_widget_example.dart b/examples/lib/stories/widgets/partial_sprite_widget_example.dart index 1f7a9d26fc2..ec2d89969f4 100644 --- a/examples/lib/stories/widgets/partial_sprite_widget_example.dart +++ b/examples/lib/stories/widgets/partial_sprite_widget_example.dart @@ -2,22 +2,14 @@ import 'package:flame/extensions.dart'; import 'package:flame/widgets.dart'; import 'package:material_ui/material_ui.dart'; -class PartialSpriteWidgetExample extends StatelessWidget { - const PartialSpriteWidgetExample({ - required this.width, - required this.height, - required this.srcPosition, - required this.srcSize, - required this.anchor, - super.key, - }); - - final double width; - final double height; - final Vector2 srcPosition; - final Vector2 srcSize; - final Anchor anchor; - +class const PartialSpriteWidgetExample({ + required final double width, + required final double height, + required final Vector2 srcPosition, + required final Vector2 srcSize, + required final Anchor anchor, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return Container( diff --git a/examples/lib/stories/widgets/sprite_animation_widget_example.dart b/examples/lib/stories/widgets/sprite_animation_widget_example.dart index cd589f75ffa..22e35a04124 100644 --- a/examples/lib/stories/widgets/sprite_animation_widget_example.dart +++ b/examples/lib/stories/widgets/sprite_animation_widget_example.dart @@ -2,22 +2,14 @@ import 'package:flame/extensions.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/widgets.dart'; -class SpriteAnimationWidgetExample extends StatelessWidget { - const SpriteAnimationWidgetExample({ - required this.width, - required this.height, - required this.playing, - required this.anchor, - required this.paint, - super.key, - }); - - final double width; - final double height; - final bool playing; - final Anchor anchor; - final Paint? paint; - +class const SpriteAnimationWidgetExample({ + required final double width, + required final double height, + required final bool playing, + required final Anchor anchor, + required final Paint? paint, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return SizedBox( @@ -38,20 +30,13 @@ class SpriteAnimationWidgetExample extends StatelessWidget { } } -class SizedSpriteAnimationWidgetExample extends StatelessWidget { - const SizedSpriteAnimationWidgetExample({ - required this.size, - required this.playing, - required this.anchor, - required this.paint, - super.key, - }); - - final Size size; - final bool playing; - final Anchor anchor; - final Paint? paint; - +class const SizedSpriteAnimationWidgetExample({ + required final Size size, + required final bool playing, + required final Anchor anchor, + required final Paint? paint, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return SpriteAnimationWidget.asset( diff --git a/examples/lib/stories/widgets/sprite_button_example.dart b/examples/lib/stories/widgets/sprite_button_example.dart index 62e8dc4829b..6a8c8b4d5ae 100644 --- a/examples/lib/stories/widgets/sprite_button_example.dart +++ b/examples/lib/stories/widgets/sprite_button_example.dart @@ -2,16 +2,11 @@ import 'package:flame/extensions.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/widgets.dart'; -class SpriteButtonExample extends StatelessWidget { - const SpriteButtonExample({ - required this.width, - required this.height, - super.key, - }); - - final double width; - final double height; - +class const SpriteButtonExample({ + required final double width, + required final double height, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return Container( diff --git a/examples/lib/stories/widgets/sprite_widget_example.dart b/examples/lib/stories/widgets/sprite_widget_example.dart index 770f2d381f2..b0b248d2958 100644 --- a/examples/lib/stories/widgets/sprite_widget_example.dart +++ b/examples/lib/stories/widgets/sprite_widget_example.dart @@ -1,22 +1,14 @@ import 'package:flame/widgets.dart'; import 'package:material_ui/material_ui.dart'; -class SpriteWidgetExample extends StatelessWidget { - const SpriteWidgetExample({ - required this.width, - required this.height, - required this.angle, - required this.anchor, - required this.paint, - super.key, - }); - - final double width; - final double height; - final double angle; - final Anchor anchor; - final Paint? paint; - +class const SpriteWidgetExample({ + required final double width, + required final double height, + required final double angle, + required final Anchor anchor, + required final Paint? paint, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return Container( @@ -33,20 +25,13 @@ class SpriteWidgetExample extends StatelessWidget { } } -class SizedSpriteWidgetExample extends StatelessWidget { - const SizedSpriteWidgetExample({ - required this.size, - required this.angle, - required this.anchor, - required this.paint, - super.key, - }); - - final Size size; - final double angle; - final Anchor anchor; - final Paint? paint; - +class const SizedSpriteWidgetExample({ + required final Size size, + required final double angle, + required final Anchor anchor, + required final Paint? paint, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return DecoratedBox( diff --git a/examples/pubspec.yaml b/examples/pubspec.yaml index 433bb19b9ac..e0e58530427 100644 --- a/examples/pubspec.yaml +++ b/examples/pubspec.yaml @@ -7,8 +7,8 @@ publish_to: "none" version: 0.1.0 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.18.0 diff --git a/packages/flame/benchmark/children_traversal_benchmark.dart b/packages/flame/benchmark/children_traversal_benchmark.dart index 71af46e11a4..4cd4d777ebe 100644 --- a/packages/flame/benchmark/children_traversal_benchmark.dart +++ b/packages/flame/benchmark/children_traversal_benchmark.dart @@ -27,15 +27,11 @@ const _dt = 1.0 / 60; /// /// Each run performs roughly one million component visits, so the reported /// times are comparable across shapes and between the two passes. -abstract class _TraversalBenchmark extends AsyncBenchmarkBase { - _TraversalBenchmark( - super.name, { - required this.ticks, - required this.renderPass, - }); - - final int ticks; - final bool renderPass; +abstract class _TraversalBenchmark( + super.name, { + required final int ticks, + required final bool renderPass, +}) extends AsyncBenchmarkBase { late final FlameGame _game; late final Canvas _canvas; @@ -67,10 +63,11 @@ abstract class _TraversalBenchmark extends AsyncBenchmarkBase { } /// 10k components in a single children container. -class WideTreeBenchmark extends _TraversalBenchmark { +class WideTreeBenchmark({required super.renderPass}) + extends _TraversalBenchmark { static const _amountChildren = 10000; - WideTreeBenchmark({required super.renderPass}) + this : super( '${renderPass ? 'Render' : 'Update'} wide tree (10k x 1)', ticks: 100, @@ -89,11 +86,12 @@ class WideTreeBenchmark extends _TraversalBenchmark { } /// 1k parents with 10 children each: many small children containers. -class NestedTreeBenchmark extends _TraversalBenchmark { +class NestedTreeBenchmark({required super.renderPass}) + extends _TraversalBenchmark { static const _amountParents = 1000; static const _amountChildren = 10; - NestedTreeBenchmark({required super.renderPass}) + this : super( '${renderPass ? 'Render' : 'Update'} nested tree (1k x 10)', ticks: 90, @@ -119,11 +117,12 @@ class NestedTreeBenchmark extends _TraversalBenchmark { } /// A chain 100 levels deep where every level also holds 9 leaf children. -class DeepTreeBenchmark extends _TraversalBenchmark { +class DeepTreeBenchmark({required super.renderPass}) + extends _TraversalBenchmark { static const _depth = 100; static const _leavesPerLevel = 9; - DeepTreeBenchmark({required super.renderPass}) + this : super( '${renderPass ? 'Render' : 'Update'} deep tree (100 levels)', ticks: 1000, @@ -142,7 +141,7 @@ class DeepTreeBenchmark extends _TraversalBenchmark { next = Component( children: [ ...List.generate(_leavesPerLevel, (_) => Component()), - if (next != null) next, + ?next, ], ); } @@ -155,12 +154,12 @@ class DeepTreeBenchmark extends _TraversalBenchmark { /// traversal through [HasTimeScale] (with the time scale left at 1.0, so /// the traversal work stays identical and only the barrier indirection is /// measured). -class BarrierTreeUpdateBenchmark extends _TraversalBenchmark { +class BarrierTreeUpdateBenchmark() extends _TraversalBenchmark { static const _amountParents = 1000; static const _amountChildren = 10; static const _barrierInterval = 10; - BarrierTreeUpdateBenchmark() + this : super( 'Update barrier tree (1k x 10, 10% time-scaled)', ticks: 90, @@ -185,9 +184,9 @@ class BarrierTreeUpdateBenchmark extends _TraversalBenchmark { } } -class _TimeScaledParent extends Component with CustomTraversal, HasTimeScale { - _TimeScaledParent({super.children}); -} +class _TimeScaledParent({super.children}) + extends Component + with CustomTraversal, HasTimeScale; Future main() async { await WideTreeBenchmark.main(); diff --git a/packages/flame/benchmark/collision_detection_benchmark.dart b/packages/flame/benchmark/collision_detection_benchmark.dart index 109b88cc7e1..c49d56353ce 100644 --- a/packages/flame/benchmark/collision_detection_benchmark.dart +++ b/packages/flame/benchmark/collision_detection_benchmark.dart @@ -10,13 +10,11 @@ const _amountTicks = 500; /// Benchmarks collision detection with simple flat hitboxes (no hierarchy). /// All components are direct children of the game world. -class FlatCollisionBenchmark extends AsyncBenchmarkBase { - final Random random; - +class FlatCollisionBenchmark(final Random random) extends AsyncBenchmarkBase { late final FlameGame _game; late final List<_MovingBlock> _blocks; - FlatCollisionBenchmark(this.random) : super('Flat collision detection'); + this : super('Flat collision detection'); static Future main() async { final r = Random(69420); @@ -55,13 +53,10 @@ class FlatCollisionBenchmark extends AsyncBenchmarkBase { /// Benchmarks collision detection with nested hierarchies where children have /// hitboxes and parents have non-uniform scale/rotation. This exercises the /// globalVertices() and AABB computation code paths. -class NestedCollisionBenchmark extends AsyncBenchmarkBase { - final Random random; - +class NestedCollisionBenchmark(final Random random) extends AsyncBenchmarkBase { late final FlameGame _game; - NestedCollisionBenchmark(this.random) - : super('Nested hierarchy collision detection'); + this : super('Nested hierarchy collision detection'); static Future main() async { final r = Random(69420); @@ -110,13 +105,11 @@ class NestedCollisionBenchmark extends AsyncBenchmarkBase { /// Benchmarks globalVertices() calls directly for polygon components in /// hierarchies with non-uniform scale and rotation. -class GlobalVerticesBenchmark extends AsyncBenchmarkBase { - final Random random; - +class GlobalVerticesBenchmark(final Random random) extends AsyncBenchmarkBase { late final FlameGame _game; late final List _hitboxes; - GlobalVerticesBenchmark(this.random) : super('globalVertices() computation'); + this : super('globalVertices() computation'); static Future main() async { final r = Random(69420); @@ -167,16 +160,14 @@ class GlobalVerticesBenchmark extends AsyncBenchmarkBase { } } -class _CollisionGame extends FlameGame with HasCollisionDetection {} - -class _MovingBlock extends PositionComponent with CollisionCallbacks { - final Vector2 velocity; +class _CollisionGame() extends FlameGame with HasCollisionDetection; - _MovingBlock({ - required super.position, - required super.size, - required this.velocity, - }) { +class _MovingBlock({ + required super.position, + required super.size, + required final Vector2 velocity, +}) extends PositionComponent with CollisionCallbacks { + this { add(RectangleHitbox()); } diff --git a/packages/flame/benchmark/common.dart b/packages/flame/benchmark/common.dart index 7b81e825a35..22cbce3328d 100644 --- a/packages/flame/benchmark/common.dart +++ b/packages/flame/benchmark/common.dart @@ -9,9 +9,7 @@ import 'package:flame/game.dart'; /// a very different code path than a real game. Future mountGame(FlameGame game, {Vector2? size}) async { game.onGameResize(size ?? Vector2(800, 600)); - // ignore: invalid_use_of_internal_member await game.load(); - // ignore: invalid_use_of_internal_member game.mount(); await game.ready(); game.update(0); diff --git a/packages/flame/benchmark/component_churn_benchmark.dart b/packages/flame/benchmark/component_churn_benchmark.dart index 163ea89eddd..873e0ba4198 100644 --- a/packages/flame/benchmark/component_churn_benchmark.dart +++ b/packages/flame/benchmark/component_churn_benchmark.dart @@ -20,16 +20,16 @@ const _dt = 1.0 / 60; /// example, a sorted list shifts elements on every removal, while a tree does /// a logarithmic lookup), so a container replacement must be evaluated at /// both sizes. -class ComponentChurnBenchmark extends AsyncBenchmarkBase { +class ComponentChurnBenchmark({required final int staticPopulation}) + extends AsyncBenchmarkBase { static const _batchSize = 100; static const _liveBatches = 5; static const _amountTicks = 60; - final int staticPopulation; late final FlameGame _game; final Queue> _batches = Queue(); - ComponentChurnBenchmark({required this.staticPopulation}) + this : super( 'Lifecycle churn ' '(100 per tick, ${staticPopulation ~/ 1000}k population)', @@ -75,13 +75,13 @@ class ComponentChurnBenchmark extends AsyncBenchmarkBase { /// processed in one tick, then all removed and processed in the next. This /// stresses [FlameGame.processLifecycleEvents] with a long event queue, as /// happens when levels are loaded and torn down. -class MassAddRemoveBenchmark extends AsyncBenchmarkBase { +class MassAddRemoveBenchmark() extends AsyncBenchmarkBase { static const _amountComponents = 1000; static const _amountCycles = 5; late final FlameGame _game; - MassAddRemoveBenchmark() : super('Mass add/remove (1k per cycle)'); + this : super('Mass add/remove (1k per cycle)'); static Future main() async { await MassAddRemoveBenchmark().report(); diff --git a/packages/flame/benchmark/components_at_point_benchmark.dart b/packages/flame/benchmark/components_at_point_benchmark.dart index 3948da19912..0cfc0aabb14 100644 --- a/packages/flame/benchmark/components_at_point_benchmark.dart +++ b/packages/flame/benchmark/components_at_point_benchmark.dart @@ -13,13 +13,11 @@ const _gameSize = 800.0; /// (tap down + tap up delivery). Represents pre-PR behavior where the game /// caught all events without checking which component was hit. /// See PR: https://github.com/flame-engine/flame/pull/3815 -class BaselineBenchmark extends AsyncBenchmarkBase { - final Random random; - +class BaselineBenchmark(final Random random) extends AsyncBenchmarkBase { late final FlameGame _game; late final List _positions; - BaselineBenchmark(this.random) : super('Baseline (no hit test)'); + this : super('Baseline (no hit test)'); static Future main() async { final r = Random(69420); @@ -58,13 +56,11 @@ class BaselineBenchmark extends AsyncBenchmarkBase { /// Benchmarks the real flow: containsEventHandlerAt (hit test with early-stop /// and caching) followed by two componentsAtPoint calls (tap down replays /// from cache, tap up does a real traversal). -class CachedHitTestBenchmark extends AsyncBenchmarkBase { - final Random random; - +class CachedHitTestBenchmark(final Random random) extends AsyncBenchmarkBase { late final FlameGame _game; late final List _positions; - CachedHitTestBenchmark(this.random) : super('Hit Test + Delivery (cached)'); + this : super('Hit Test + Delivery (cached)'); static Future main() async { final r = Random(69420); @@ -106,14 +102,11 @@ class CachedHitTestBenchmark extends AsyncBenchmarkBase { /// Benchmarks the flow without cache: componentsAtPoint called 3 times /// per tap (hit test scan + tap down delivery + tap up delivery). -class UncachedHitTestBenchmark extends AsyncBenchmarkBase { - final Random random; - +class UncachedHitTestBenchmark(final Random random) extends AsyncBenchmarkBase { late final FlameGame _game; late final List _positions; - UncachedHitTestBenchmark(this.random) - : super('Hit Test + Delivery (uncached)'); + this : super('Hit Test + Delivery (uncached)'); static Future main() async { final r = Random(69420); @@ -225,7 +218,7 @@ List _generatePositions(Random random) { ); } -class _TappableComponent extends PositionComponent with TapCallbacks {} +class _TappableComponent() extends PositionComponent with TapCallbacks; Future main() async { final r1 = Random(69420); diff --git a/packages/flame/benchmark/path_collision_benchmark.dart b/packages/flame/benchmark/path_collision_benchmark.dart index b47729e85fe..e30c562c531 100644 --- a/packages/flame/benchmark/path_collision_benchmark.dart +++ b/packages/flame/benchmark/path_collision_benchmark.dart @@ -24,7 +24,12 @@ const _amountTicks = 20; const _worldSize = 800.0; /// The subject is the shape under test, the other is what it collides with. -enum ShapeKind { circle, rectangle, polygon, path } +enum ShapeKind() { + circle, + rectangle, + polygon, + path, +} /// The anchor points of [TestPaths.flame], which is /// what a hand-written polygon of that shape would look like. @@ -42,15 +47,14 @@ final _flameVertices = [ ]; const _flameBounds = Rect.fromLTRB(4, 3, 62, 65); -class PathCollisionBenchmark extends AsyncBenchmarkBase { - final Random random; - final ShapeKind subject; - final ShapeKind other; - +class PathCollisionBenchmark( + final Random random, + final ShapeKind subject, + final ShapeKind other, +) extends AsyncBenchmarkBase { late final FlameGame _game; - PathCollisionBenchmark(this.random, this.subject, this.other) - : super('${subject.name} vs ${other.name}'); + this : super('${subject.name} vs ${other.name}'); @override Future setup() async { @@ -86,21 +90,19 @@ class PathCollisionBenchmark extends AsyncBenchmarkBase { } } -class _CollisionGame extends FlameGame with HasCollisionDetection {} +class _CollisionGame() extends FlameGame with HasCollisionDetection; -class _MovingShape extends PositionComponent with CollisionCallbacks { - final Vector2 velocity; - final double rotationSpeed; +class _MovingShape({ + required ShapeKind kind, + required ShapeKind partnerKind, + required super.position, + required super.size, + required final Vector2 velocity, + required final double rotationSpeed, +}) extends PositionComponent with CollisionCallbacks { late final ShapeHitbox hitbox; - _MovingShape({ - required ShapeKind kind, - required ShapeKind partnerKind, - required super.position, - required super.size, - required this.velocity, - required this.rotationSpeed, - }) : super(anchor: Anchor.center) { + this : super(anchor: Anchor.center) { hitbox = switch (kind) { ShapeKind.circle => _Circle(), ShapeKind.rectangle => _Rectangle(), @@ -138,9 +140,9 @@ mixin _PartnerFilter on ShapeHitbox { } } -class _Circle extends CircleHitbox with _PartnerFilter {} +class _Circle() extends CircleHitbox with _PartnerFilter; -class _Rectangle extends RectangleHitbox with _PartnerFilter {} +class _Rectangle() extends RectangleHitbox with _PartnerFilter; class _Polygon extends PolygonHitbox with _PartnerFilter { _Polygon(super.vertices, {super.anchor, super.position}); diff --git a/packages/flame/benchmark/priority_change_benchmark.dart b/packages/flame/benchmark/priority_change_benchmark.dart index a2fb68538ad..4d2703368e7 100644 --- a/packages/flame/benchmark/priority_change_benchmark.dart +++ b/packages/flame/benchmark/priority_change_benchmark.dart @@ -17,7 +17,7 @@ const _randomSeed = 69420; /// /// All priority values and child picks are precomputed in [setup] and replayed /// identically on every run, so results are comparable across engine versions. -class SiblingPriorityChangeBenchmark extends AsyncBenchmarkBase { +class SiblingPriorityChangeBenchmark() extends AsyncBenchmarkBase { static const _amountParents = 100; static const _amountChildren = 50; static const _amountTicks = 50; @@ -26,8 +26,7 @@ class SiblingPriorityChangeBenchmark extends AsyncBenchmarkBase { late final List> _children; late final List> _changes; - SiblingPriorityChangeBenchmark() - : super('Priority change (1 child per parent)'); + this : super('Priority change (1 child per parent)'); static Future main() async { await SiblingPriorityChangeBenchmark().report(); @@ -79,7 +78,7 @@ class SiblingPriorityChangeBenchmark extends AsyncBenchmarkBase { /// Measures the y-sort pattern: every child of a single large container gets /// a new priority every tick (as when sorting sprites by their y coordinate /// while they move), followed by an update that reorders the whole container. -class YSortPriorityBenchmark extends AsyncBenchmarkBase { +class YSortPriorityBenchmark() extends AsyncBenchmarkBase { static const _amountChildren = 1000; static const _amountTicks = 30; @@ -87,7 +86,7 @@ class YSortPriorityBenchmark extends AsyncBenchmarkBase { late final List _children; late final List> _priorities; - YSortPriorityBenchmark() : super('Priority change (y-sort, all children)'); + this : super('Priority change (y-sort, all children)'); static Future main() async { await YSortPriorityBenchmark().report(); diff --git a/packages/flame/benchmark/ray_intersection_benchmark.dart b/packages/flame/benchmark/ray_intersection_benchmark.dart index 293ef90bf0d..1e5ee7eb755 100644 --- a/packages/flame/benchmark/ray_intersection_benchmark.dart +++ b/packages/flame/benchmark/ray_intersection_benchmark.dart @@ -16,10 +16,10 @@ const _worldWidth = 800.0; const _worldHeight = 600.0; final _half = Vector2(0.5, 0.5); -abstract class RayIntersectionBenchmark extends AsyncBenchmarkBase { - RayIntersectionBenchmark(super.name, {required this.random}); - - final Random random; +abstract class RayIntersectionBenchmark( + super.name, { + required final Random random, +}) extends AsyncBenchmarkBase { late final RayIntersectionGame game; @override @@ -30,11 +30,11 @@ abstract class RayIntersectionBenchmark extends AsyncBenchmarkBase { } } -class ConcaveRayIntersectionBenchmark extends RayIntersectionBenchmark { - final RayInputs inputs; - - ConcaveRayIntersectionBenchmark(this.inputs, {required super.random}) - : super('Concave polygon ray intersection'); +class ConcaveRayIntersectionBenchmark( + final RayInputs inputs, { + required super.random, +}) extends RayIntersectionBenchmark { + this : super('Concave polygon ray intersection'); static Future main() async { final r = Random(69420); @@ -51,11 +51,11 @@ class ConcaveRayIntersectionBenchmark extends RayIntersectionBenchmark { } } -class ConvexRayIntersectionBenchmark extends RayIntersectionBenchmark { - final RayInputs inputs; - - ConvexRayIntersectionBenchmark(this.inputs, {required super.random}) - : super('Convex polygon ray intersection'); +class ConvexRayIntersectionBenchmark( + final RayInputs inputs, { + required super.random, +}) extends RayIntersectionBenchmark { + this : super('Convex polygon ray intersection'); static Future main() async { final r = Random(69420); @@ -78,12 +78,8 @@ class ConvexRayIntersectionBenchmark extends RayIntersectionBenchmark { } } -class RayIntersectionGame extends FlameGame { +class RayIntersectionGame(final RayBatch batch) extends FlameGame { late final RayIntersectionComponent rayIntersectionComponent; - late final RayBatch batch; - - RayIntersectionGame(this.batch); - FutureOr prepare() async { onGameResize(Vector2(_worldWidth, _worldHeight)); await load(); @@ -103,11 +99,7 @@ class RayIntersectionGame extends FlameGame { } } -class RayIntersectionComponent extends Component { - RayIntersectionComponent(this.batch); - - final RayBatch batch; - +class RayIntersectionComponent(final RayBatch batch) extends Component { @override void update(double dt) { super.update(dt); @@ -117,19 +109,9 @@ class RayIntersectionComponent extends Component { } } -class RayInputs { - RayInputs(this.positions, this.rays); - - final List positions; - final List rays; -} +class RayInputs(final List positions, final List rays); -class RayBatch { - RayBatch(this.hitboxes, this.rays); - - final List hitboxes; - final List rays; -} +class RayBatch(final List hitboxes, final List rays); RayBatch _createBatch(List vertices, RayInputs inputs) { final hitboxes = [ diff --git a/packages/flame/benchmark/render_components_benchmark.dart b/packages/flame/benchmark/render_components_benchmark.dart index dae58aedd52..38a7035829a 100644 --- a/packages/flame/benchmark/render_components_benchmark.dart +++ b/packages/flame/benchmark/render_components_benchmark.dart @@ -13,13 +13,12 @@ const _amountComponents = 500; const _amountTicks = 2; const _depthMultiplier = 0.25; -class RenderComponentsBenchmark extends AsyncBenchmarkBase { - final Random random; - +class RenderComponentsBenchmark(final Random random) + extends AsyncBenchmarkBase { late final Canvas _canvas; late final FlameGame _game; - RenderComponentsBenchmark(this.random) : super('Render Components Benchmark'); + this : super('Render Components Benchmark'); static Future main() async { final r = Random(69420); @@ -51,15 +50,10 @@ class RenderComponentsBenchmark extends AsyncBenchmarkBase { } } -class _BenchmarkComponent extends PositionComponent { - final Random random; - final double level; - - _BenchmarkComponent({ - required this.random, - required this.level, - }); - +class _BenchmarkComponent({ + required final Random random, + required final double level, +}) extends PositionComponent { @override Future onLoad() async { if (random.nextDouble() <= level) { diff --git a/packages/flame/benchmark/transform2d_benchmark.dart b/packages/flame/benchmark/transform2d_benchmark.dart index 03856b16314..a0543d577d9 100644 --- a/packages/flame/benchmark/transform2d_benchmark.dart +++ b/packages/flame/benchmark/transform2d_benchmark.dart @@ -8,13 +8,11 @@ const _amountPoints = 1000; /// The per-frame pattern of a moving component: the position changes every /// tick and the matrix is requested again when the component is rendered. -class PositionUpdateBenchmark extends BenchmarkBase { - final Random random; - +class PositionUpdateBenchmark(final Random random) extends BenchmarkBase { late final List _transforms; late final List _positions; - PositionUpdateBenchmark(this.random) : super('Transform2D position update'); + this : super('Transform2D position update'); static void main() { PositionUpdateBenchmark(Random(69420)).report(); @@ -39,13 +37,11 @@ class PositionUpdateBenchmark extends BenchmarkBase { /// A rotating component: the angle changes every tick and the matrix is /// requested again when the component is rendered. -class AngleUpdateBenchmark extends BenchmarkBase { - final Random random; - +class AngleUpdateBenchmark(final Random random) extends BenchmarkBase { late final List _transforms; late final List _angles; - AngleUpdateBenchmark(this.random) : super('Transform2D angle update'); + this : super('Transform2D angle update'); static void main() { AngleUpdateBenchmark(Random(69420)).report(); @@ -72,15 +68,12 @@ class AngleUpdateBenchmark extends BenchmarkBase { /// Converting points back and forth through an unchanged transform, as done /// by hit testing and the camera. -class PointConversionBenchmark extends BenchmarkBase { - final Random random; - +class PointConversionBenchmark(final Random random) extends BenchmarkBase { late final Transform2D _transform; late final List _points; final Vector2 _output = Vector2.zero(); - PointConversionBenchmark(this.random) - : super('Transform2D localToGlobal/globalToLocal'); + this : super('Transform2D localToGlobal/globalToLocal'); static void main() { PointConversionBenchmark(Random(69420)).report(); @@ -103,14 +96,11 @@ class PointConversionBenchmark extends BenchmarkBase { } /// Assigning a full matrix to a transform and reading it back. -class MatrixAssignmentBenchmark extends BenchmarkBase { - final Random random; - +class MatrixAssignmentBenchmark(final Random random) extends BenchmarkBase { late final List _transforms; late final List _matrices; - MatrixAssignmentBenchmark(this.random) - : super('Transform2D transformMatrix setter'); + this : super('Transform2D transformMatrix setter'); static void main() { MatrixAssignmentBenchmark(Random(69420)).report(); @@ -135,13 +125,11 @@ class MatrixAssignmentBenchmark extends BenchmarkBase { } /// Copying one transform into another and reading the resulting matrix. -class SetFromBenchmark extends BenchmarkBase { - final Random random; - +class SetFromBenchmark(final Random random) extends BenchmarkBase { late final List _transforms; late final List _sources; - SetFromBenchmark(this.random) : super('Transform2D setFrom'); + this : super('Transform2D setFrom'); static void main() { SetFromBenchmark(Random(69420)).report(); diff --git a/packages/flame/benchmark/type_query_benchmark.dart b/packages/flame/benchmark/type_query_benchmark.dart index 1fd3f134f95..e609f999a95 100644 --- a/packages/flame/benchmark/type_query_benchmark.dart +++ b/packages/flame/benchmark/type_query_benchmark.dart @@ -18,7 +18,7 @@ const _dt = 1.0 / 60; /// registered queries while reading one query per tick. A children-container /// replacement must keep both the cache-maintenance and the query-read cost /// at least this fast. -class TypeQueryChurnBenchmark extends AsyncBenchmarkBase { +class TypeQueryChurnBenchmark() extends AsyncBenchmarkBase { static const _amountStatic = 1000; static const _batchSize = 50; static const _liveBatches = 5; @@ -28,7 +28,7 @@ class TypeQueryChurnBenchmark extends AsyncBenchmarkBase { late final FlameGame _game; final Queue> _batches = Queue(); - TypeQueryChurnBenchmark() : super('Type-query churn (2 registered queries)'); + this : super('Type-query churn (2 registered queries)'); static Future main() async { await TypeQueryChurnBenchmark().report(); @@ -79,11 +79,11 @@ class TypeQueryChurnBenchmark extends AsyncBenchmarkBase { } } -class _MarkedComponent extends Component { +class _MarkedComponent() extends Component { final int marker = 1; } -class _PlainComponent extends Component {} +class _PlainComponent() extends Component; Future main() async { await TypeQueryChurnBenchmark.main(); diff --git a/packages/flame/benchmark/update_components_benchmark.dart b/packages/flame/benchmark/update_components_benchmark.dart index 39602747d28..f0486ba2a99 100644 --- a/packages/flame/benchmark/update_components_benchmark.dart +++ b/packages/flame/benchmark/update_components_benchmark.dart @@ -11,16 +11,14 @@ const _amountTicks = 500; const _amountInputs = 125; const _amountChildren = 10; -class UpdateComponentsBenchmark extends AsyncBenchmarkBase { - final Random random; - +class UpdateComponentsBenchmark(final Random random) + extends AsyncBenchmarkBase { late final FlameGame _game; late final List<_BenchmarkComponent> _components; late final List _dts; late final Set _inputTicks; - UpdateComponentsBenchmark(this.random) - : super('Updating Components Benchmark'); + this : super('Updating Components Benchmark'); static Future main() async { final r = Random(69420); @@ -65,14 +63,11 @@ class UpdateComponentsBenchmark extends AsyncBenchmarkBase { } } -class _BenchmarkComponent extends PositionComponent { +class _BenchmarkComponent(final int id) extends PositionComponent { static const _groundY = -20.0; - final int id; final Vector2 velocity = Vector2.zero(); - _BenchmarkComponent(this.id); - @override Future onLoad() async { for (var i = 0; i < _amountChildren; i++) { diff --git a/packages/flame/benchmark/update_workload_benchmark.dart b/packages/flame/benchmark/update_workload_benchmark.dart index 40a9cae3da5..84df30d945b 100644 --- a/packages/flame/benchmark/update_workload_benchmark.dart +++ b/packages/flame/benchmark/update_workload_benchmark.dart @@ -32,17 +32,13 @@ const _worldHeight = 600.0; /// the light and heavy rows are not directly comparable to each other, only /// to their own no-op counterpart in the traversal suite and across engine /// versions. -abstract class _WorkloadBenchmark extends AsyncBenchmarkBase { +abstract class _WorkloadBenchmark( + super.name, { + required final int ticks, + required final bool heavy, +}) extends AsyncBenchmarkBase { static const _amountTargets = 32; - _WorkloadBenchmark( - super.name, { - required this.ticks, - required this.heavy, - }); - - final int ticks; - final bool heavy; final Random _random = Random(69420); late final FlameGame _game; late final List _targets; @@ -100,10 +96,11 @@ abstract class _WorkloadBenchmark extends AsyncBenchmarkBase { } /// 10k components in a single children container. -class WideTreeWorkloadBenchmark extends _WorkloadBenchmark { +class WideTreeWorkloadBenchmark({required super.heavy}) + extends _WorkloadBenchmark { static const _amountChildren = 10000; - WideTreeWorkloadBenchmark({required super.heavy}) + this : super( 'Update wide tree (10k x 1), ${heavy ? 'heavy' : 'light'} logic', ticks: heavy ? 10 : 50, @@ -121,11 +118,12 @@ class WideTreeWorkloadBenchmark extends _WorkloadBenchmark { } /// 1k parents with 10 children each: many small children containers. -class NestedTreeWorkloadBenchmark extends _WorkloadBenchmark { +class NestedTreeWorkloadBenchmark({required super.heavy}) + extends _WorkloadBenchmark { static const _amountParents = 1000; static const _amountChildren = 10; - NestedTreeWorkloadBenchmark({required super.heavy}) + this : super( 'Update nested tree (1k x 10), ${heavy ? 'heavy' : 'light'} logic', ticks: heavy ? 9 : 45, @@ -150,11 +148,10 @@ class NestedTreeWorkloadBenchmark extends _WorkloadBenchmark { } } -class _LightComponent extends PositionComponent { - final Vector2 velocity; - - _LightComponent({required super.position, required this.velocity}); - +class _LightComponent({ + required super.position, + required final Vector2 velocity, +}) extends PositionComponent { @override void update(double dt) { position.addScaled(velocity, dt); @@ -167,24 +164,19 @@ class _LightComponent extends PositionComponent { } } -class _HeavyComponent extends PositionComponent { +class _HeavyComponent({ + required super.position, + required final Vector2 velocity, + required final List targets, + required var double cooldown, +}) extends PositionComponent { static const _maxSpeed = 120.0; static const _acceleration = 300.0; static const _cooldownDuration = 1.5; - final Vector2 velocity; - final List targets; final Vector2 _steering = Vector2.zero(); - double cooldown; int shotsFired = 0; - _HeavyComponent({ - required super.position, - required this.velocity, - required this.targets, - required this.cooldown, - }); - @override void update(double dt) { var nearest = targets.first; diff --git a/packages/flame/example/lib/main.dart b/packages/flame/example/lib/main.dart index 1e4be0cb267..f441845f891 100644 --- a/packages/flame/example/lib/main.dart +++ b/packages/flame/example/lib/main.dart @@ -17,7 +17,7 @@ void main() { ); } -class MyWorld extends World with TapCallbacks { +class MyWorld() extends World with TapCallbacks { @override Future onLoad() async { add(Square(Vector2.zero())); @@ -30,7 +30,7 @@ class MyWorld extends World with TapCallbacks { } } -class Square extends RectangleComponent with TapCallbacks { +class Square(Vector2 position) extends RectangleComponent with TapCallbacks { static const speed = 3; static const squareSize = 128.0; static const indicatorSize = 6.0; @@ -38,7 +38,7 @@ class Square extends RectangleComponent with TapCallbacks { static final Paint red = BasicPalette.red.paint(); static final Paint blue = BasicPalette.blue.paint(); - Square(Vector2 position) + this : super( position: position, size: Vector2.all(squareSize), diff --git a/packages/flame/example/pubspec.yaml b/packages/flame/example/pubspec.yaml index 416bbbebca5..a27cc953211 100644 --- a/packages/flame/example/pubspec.yaml +++ b/packages/flame/example/pubspec.yaml @@ -5,8 +5,8 @@ version: 0.1.0 publish_to: 'none' environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame/lib/components.dart b/packages/flame/lib/components.dart index ef569a3f3fe..ed7d36199af 100644 --- a/packages/flame/lib/components.dart +++ b/packages/flame/lib/components.dart @@ -1,5 +1,5 @@ /// {@canonicalFor anchor.Anchor} -library components; +library; export 'src/anchor.dart'; export 'src/camera/camera_component.dart' show CameraComponent; diff --git a/packages/flame/lib/effects.dart b/packages/flame/lib/effects.dart index a7c46559a83..3b341a01cbf 100644 --- a/packages/flame/lib/effects.dart +++ b/packages/flame/lib/effects.dart @@ -37,16 +37,16 @@ export 'src/effects/provider_interfaces.dart' show AnchorProvider, AngleProvider, - ReadOnlyAngleProvider, + HueProvider, + OpacityProvider, + PaintProvider, PositionProvider, - ScaleProvider, - SizeProvider, + ReadOnlyAngleProvider, ReadOnlyPositionProvider, ReadOnlyScaleProvider, ReadOnlySizeProvider, - OpacityProvider, - PaintProvider, - HueProvider; + ScaleProvider, + SizeProvider; export 'src/effects/remove_effect.dart'; export 'src/effects/rotate_around_effect.dart'; export 'src/effects/rotate_effect.dart'; diff --git a/packages/flame/lib/experimental.dart b/packages/flame/lib/experimental.dart index c06f1ecc57d..efb8afbec80 100644 --- a/packages/flame/lib/experimental.dart +++ b/packages/flame/lib/experimental.dart @@ -9,7 +9,7 @@ /// After the components lived here for some time, and when we gain more /// confidence in their robustness, they will be moved out into the main Flame /// library. -library experimental; +library; export 'src/experimental/column_component.dart' show ColumnComponent; export 'src/experimental/expanded_component.dart' show ExpandedComponent; @@ -20,9 +20,9 @@ export 'src/experimental/geometry/shapes/rounded_rectangle.dart' show RoundedRectangle; export 'src/experimental/geometry/shapes/shape.dart' show Shape; export 'src/experimental/layout_component.dart' - show LayoutComponent, LayoutAxis; + show LayoutAxis, LayoutComponent; export 'src/experimental/linear_layout_component.dart' - show LinearLayoutComponent, Direction; + show Direction, LinearLayoutComponent; export 'src/experimental/padding_component.dart' show PaddingComponent; export 'src/experimental/row_component.dart' show RowComponent; export 'src/experimental/single_layout_component.dart' diff --git a/packages/flame/lib/game.dart b/packages/flame/lib/game.dart index 17a5de93d01..a8beb6479f0 100644 --- a/packages/flame/lib/game.dart +++ b/packages/flame/lib/game.dart @@ -1,6 +1,6 @@ /// {@canonicalFor text.TextPaint} /// {@canonicalFor text.TextRenderer} -library game; +library; export 'src/collisions/has_collision_detection.dart'; export 'src/components/router/overlay_route.dart' show OverlayRoute; diff --git a/packages/flame/lib/input.dart b/packages/flame/lib/input.dart index 7a2994c4f95..4bfcd5664fd 100644 --- a/packages/flame/lib/input.dart +++ b/packages/flame/lib/input.dart @@ -1,6 +1,6 @@ /// {@canonicalFor joystick_component.JoystickComponent} /// {@canonicalFor joystick_component.JoystickDirection} -library input; +library; export 'src/components/input/button_component.dart'; export 'src/components/input/hud_button_component.dart'; diff --git a/packages/flame/lib/sprite.dart b/packages/flame/lib/sprite.dart index 161fe38571d..ee59a0b7a66 100644 --- a/packages/flame/lib/sprite.dart +++ b/packages/flame/lib/sprite.dart @@ -2,7 +2,7 @@ /// {@canonicalFor sprite_animation.SpriteAnimationData} /// {@canonicalFor sprite_animation.SpriteAnimationFrame} /// {@canonicalFor sprite_animation.SpriteAnimationFrameData} -library sprite; +library; export 'src/sprite.dart'; export 'src/sprite_animation.dart'; diff --git a/packages/flame/lib/src/anchor.dart b/packages/flame/lib/src/anchor.dart index 97604c140d5..38bdf690930 100644 --- a/packages/flame/lib/src/anchor.dart +++ b/packages/flame/lib/src/anchor.dart @@ -16,7 +16,17 @@ import 'package:meta/meta.dart'; /// where 0 in x-axis means left, 0 in y-axis means top, 1 in x-axis means right /// and 1 in y-axis means bottom. @immutable -class Anchor { +class const Anchor( + /// The relative x position with respect to the object's width; + /// 0 means totally to the left (beginning) and 1 means totally to the + /// right (end). + final double x, + + /// The relative y position with respect to the object's height; + /// 0 means totally to the top (beginning) and 1 means totally to the + /// bottom (end). + final double y, +) { static const Anchor topLeft = Anchor(0.0, 0.0); static const Anchor topCenter = Anchor(0.5, 0.0); static const Anchor topRight = Anchor(1.0, 0.0); @@ -27,22 +37,10 @@ class Anchor { static const Anchor bottomCenter = Anchor(0.5, 1.0); static const Anchor bottomRight = Anchor(1.0, 1.0); - /// The relative x position with respect to the object's width; - /// 0 means totally to the left (beginning) and 1 means totally to the - /// right (end). - final double x; - - /// The relative y position with respect to the object's height; - /// 0 means totally to the top (beginning) and 1 means totally to the - /// bottom (end). - final double y; - /// Returns [x] and [y] as a Vector2. Note that this is still a relative /// fractional representation. Vector2 toVector2() => Vector2(x, y); - const Anchor(this.x, this.y); - /// Take your position [position] that is on this anchor and give back what /// that position it would be on in anchor [otherAnchor] with a size of /// [size]. diff --git a/packages/flame/lib/src/cache/assets_cache.dart b/packages/flame/lib/src/cache/assets_cache.dart index fe3ed2785f2..11510a995ce 100644 --- a/packages/flame/lib/src/cache/assets_cache.dart +++ b/packages/flame/lib/src/cache/assets_cache.dart @@ -8,12 +8,10 @@ import 'package:flutter/services.dart' show AssetBundle; /// /// Files are addressed by their full path, exactly as declared in the /// `pubspec.yaml`, for example `assets/levels/level1.json`. -class AssetsCache { - AssetsCache({AssetBundle? bundle}) : bundle = bundle ?? Flame.bundle; - +class AssetsCache({AssetBundle? bundle}) { /// The [AssetBundle] from which assets are loaded. /// defaults to [Flame.bundle]. - AssetBundle bundle; + AssetBundle bundle = bundle ?? Flame.bundle; final Map> _files = {}; @@ -122,19 +120,10 @@ class AssetsCache { } } -sealed class _Asset { - T value; - _Asset(this.value); -} +sealed class _Asset(var T value); -class _StringAsset extends _Asset { - _StringAsset(super.value); -} +class _StringAsset(super.value) extends _Asset; -class _BinaryAsset extends _Asset { - _BinaryAsset(super.value); -} +class _BinaryAsset(super.value) extends _Asset; -class _JsonAsset extends _Asset> { - _JsonAsset(super.value); -} +class _JsonAsset(super.value) extends _Asset>; diff --git a/packages/flame/lib/src/cache/images.dart b/packages/flame/lib/src/cache/images.dart index aaf1dbf00cd..f2038191ff1 100644 --- a/packages/flame/lib/src/cache/images.dart +++ b/packages/flame/lib/src/cache/images.dart @@ -6,14 +6,12 @@ import 'package:flame/src/flame.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; -class Images { - Images({AssetBundle? bundle}) : bundle = bundle ?? Flame.bundle; - +class Images({AssetBundle? bundle}) { final Map _assets = {}; /// The [AssetBundle] from which images are loaded. /// defaults to [Flame.bundle]. - AssetBundle bundle; + AssetBundle bundle = bundle ?? Flame.bundle; /// Adds the [image] into the cache under the key [name]. /// @@ -138,7 +136,7 @@ class Images { final imagePaths = manifest.listAssets().where((path) { return path.startsWith(directory) && path.toLowerCase().contains(pattern); }); - return loadAll(imagePaths.toList()); + return await loadAll(imagePaths.toList()); } /// Whether the cache contains the specified [key] or not. @@ -178,7 +176,7 @@ class Images { Future _fetchToMemory(String path) async { final data = await bundle.load(path); final bytes = Uint8List.view(data.buffer); - return decodeImageFromList(bytes); + return await decodeImageFromList(bytes); } } diff --git a/packages/flame/lib/src/cache/matrix_pool.dart b/packages/flame/lib/src/cache/matrix_pool.dart index 0dc9e48cbd7..92bf528dca7 100644 --- a/packages/flame/lib/src/cache/matrix_pool.dart +++ b/packages/flame/lib/src/cache/matrix_pool.dart @@ -1,7 +1,7 @@ -import 'dart:typed_data' show Float64List, Float32List; +import 'dart:typed_data' show Float32List, Float64List; import 'dart:ui'; -class MatrixPool { +class MatrixPool() { static final List _pool = []; static const int _bufferSize = 16; diff --git a/packages/flame/lib/src/cache/memory_cache.dart b/packages/flame/lib/src/cache/memory_cache.dart index 9cd97d036cc..64ed24a3f00 100644 --- a/packages/flame/lib/src/cache/memory_cache.dart +++ b/packages/flame/lib/src/cache/memory_cache.dart @@ -1,11 +1,8 @@ import 'dart:collection'; /// Simple class to cache values with size based eviction. -class MemoryCache { +class MemoryCache({final int cacheSize = 10}) { final LinkedHashMap _cache = LinkedHashMap(); - final int cacheSize; - - MemoryCache({this.cacheSize = 10}); /// Adds the [value] to the cache under [key]. /// diff --git a/packages/flame/lib/src/cache/value_cache.dart b/packages/flame/lib/src/cache/value_cache.dart index 263b5e93e2d..95f6c87fa83 100644 --- a/packages/flame/lib/src/cache/value_cache.dart +++ b/packages/flame/lib/src/cache/value_cache.dart @@ -1,13 +1,11 @@ /// Used for caching calculated values, the cache is determined to be valid by /// comparing a list of values that can be of any type and is compared to the /// values that was last used when the cache was updated. -class ValueCache { +class ValueCache() { T? value; List _lastValidCacheValues = []; - ValueCache(); - bool isCacheValid(List validCacheValues) { if (value == null) { return false; diff --git a/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart b/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart index a9e4e01b1c3..e57b9e07ff0 100644 --- a/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart +++ b/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart @@ -17,20 +17,19 @@ import 'package:flame/src/extensions/vector2.dart'; /// but it can also be set explicitly in the constructor. If the target is not /// passed explicitly in the constructor, then the parent component must be a /// [PositionProvider]. -class BoundedPositionBehavior extends Component { - BoundedPositionBehavior({ - required this._bounds, - this._target, - double precision = 0.5, - super.priority, - super.key, - }) : assert(precision > 0, 'Precision must be positive: $precision'), - _previousPosition = Vector2.zero(), - _precision = precision; +class BoundedPositionBehavior({ + required var Shape _bounds, + var PositionProvider? _target, + final double _precision = 0.5, + super.priority, + super.key, +}) extends Component { + this + : assert(_precision > 0, 'Precision must be positive: $_precision'), + _previousPosition = Vector2.zero(); /// The region within which the target's position must be kept. Shape get bounds => _bounds; - Shape _bounds; set bounds(Shape newBounds) { _bounds = newBounds; if (!isValidPoint(_previousPosition)) { @@ -44,10 +43,7 @@ class BoundedPositionBehavior extends Component { bool isValidPoint(Vector2 point) => _bounds.containsPoint(point); PositionProvider get target => _target!; - PositionProvider? _target; - double get precision => _precision; - final double _precision; /// Saved position from the last game tick. final Vector2 _previousPosition; diff --git a/packages/flame/lib/src/camera/behaviors/follow_behavior.dart b/packages/flame/lib/src/camera/behaviors/follow_behavior.dart index 165827490ca..bf977da7166 100644 --- a/packages/flame/lib/src/camera/behaviors/follow_behavior.dart +++ b/packages/flame/lib/src/camera/behaviors/follow_behavior.dart @@ -17,33 +17,26 @@ import 'package:vector_math/vector_math.dart'; /// /// The flags [horizontalOnly]/[verticalOnly] allow constraining the [owner]'s /// movement to the horizontal/vertical directions respectively. -class FollowBehavior extends Component { - FollowBehavior({ - required this._target, - this._owner, - double maxSpeed = double.infinity, - this.horizontalOnly = false, - this.verticalOnly = false, - super.priority, - super.key, - }) : _speed = maxSpeed, - assert(maxSpeed > 0, 'maxSpeed must be positive: $maxSpeed'), - assert( - !(horizontalOnly && verticalOnly), - 'The behavior cannot be both horizontalOnly and verticalOnly', - ); +class FollowBehavior({ + required final ReadOnlyPositionProvider _target, + var PositionProvider? _owner, + double maxSpeed = double.infinity, + final bool horizontalOnly = false, + final bool verticalOnly = false, + super.priority, + super.key, +}) extends Component { + this + : assert(maxSpeed > 0, 'maxSpeed must be positive: $maxSpeed'), + assert( + !(horizontalOnly && verticalOnly), + 'The behavior cannot be both horizontalOnly and verticalOnly', + ); ReadOnlyPositionProvider get target => _target; - final ReadOnlyPositionProvider _target; - PositionProvider get owner => _owner!; - PositionProvider? _owner; - double get maxSpeed => _speed; - final double _speed; - - final bool horizontalOnly; - final bool verticalOnly; + final double _speed = maxSpeed; final _tempDelta = Vector2.zero(); diff --git a/packages/flame/lib/src/camera/behaviors/viewport_aware_bounds_behavior.dart b/packages/flame/lib/src/camera/behaviors/viewport_aware_bounds_behavior.dart index d5f9cb31d78..7da2b7face2 100644 --- a/packages/flame/lib/src/camera/behaviors/viewport_aware_bounds_behavior.dart +++ b/packages/flame/lib/src/camera/behaviors/viewport_aware_bounds_behavior.dart @@ -16,15 +16,12 @@ import 'package:flame/src/experimental/geometry/shapes/shape.dart'; /// of the bounds, when it is false only the viewfinder anchor is considered. /// Note that it only works with [Rectangle], [RoundedRectangle] and [Circle] /// shapes. -class ViewportAwareBoundsBehavior extends Component with ParentIsA { - Shape _boundsShape; +class ViewportAwareBoundsBehavior({ + required var Shape _boundsShape, + super.key, +}) extends Component with ParentIsA { late Rect _visibleWorldRect; - ViewportAwareBoundsBehavior({ - required this._boundsShape, - super.key, - }); - @override void onLoad() { _visibleWorldRect = parent.visibleWorldRect; diff --git a/packages/flame/lib/src/camera/camera_component.dart b/packages/flame/lib/src/camera/camera_component.dart index 78f907d149c..cff0c14a56e 100644 --- a/packages/flame/lib/src/camera/camera_component.dart +++ b/packages/flame/lib/src/camera/camera_component.dart @@ -50,23 +50,24 @@ import 'package:flame/src/game/flame_game.dart'; /// rendering of the world. This is useful for applying effects such as bloom, /// blur, or other fragment shader effects to the world. See [postProcess] for /// more information. -class CameraComponent extends Component { - CameraComponent({ - this.world, - Viewport? viewport, - Viewfinder? viewfinder, - Component? backdrop, - List? hudComponents, - super.children, - super.key, - }) : _viewport = (viewport ?? MaxViewport())..addAll(hudComponents ?? []), - _viewfinder = viewfinder ?? Viewfinder(), - _backdrop = backdrop ?? Component(), - // The priority is set to the max here to avoid some bugs for the users, - // if they for example would add any components that modify positions - // before the CameraComponent, since it then will render the positions - // of the last tick each tick. - super(priority: 0x7fffffff) { +class CameraComponent({ + /// Special component that is designed to be the root of a game world. + /// + /// Multiple cameras can observe the same [world] simultaneously, and the + /// world may itself contain cameras that look into other worlds, or even into + /// itself. + /// + /// The [world] component is generally mounted externally to the camera, and + /// this variable is a mere reference to it. + var World? world, + Viewport? viewport, + Viewfinder? viewfinder, + Component? backdrop, + List? hudComponents, + super.children, + super.key, +}) extends Component { + this : super(priority: 0x7fffffff) { children.register(); addAll([_backdrop, _viewport, _viewfinder]); } @@ -115,7 +116,7 @@ class CameraComponent extends Component { _viewfinder.updateTransform(); } - Viewport _viewport; + Viewport _viewport = (viewport ?? MaxViewport())..addAll(hudComponents ?? []); /// The [viewfinder] controls which part of the world is seen through the /// viewport. @@ -132,24 +133,14 @@ class CameraComponent extends Component { add(_viewfinder); } - Viewfinder _viewfinder; - - /// Special component that is designed to be the root of a game world. - /// - /// Multiple cameras can observe the same [world] simultaneously, and the - /// world may itself contain cameras that look into other worlds, or even into - /// itself. - /// - /// The [world] component is generally mounted externally to the camera, and - /// this variable is a mere reference to it. - World? world; + Viewfinder _viewfinder = viewfinder ?? Viewfinder(); /// The [backdrop] component is rendered statically behind the world. /// /// Here you can add things like the parallax component which should be static /// when the camera moves around. Component get backdrop => _backdrop; - Component _backdrop; + Component _backdrop = backdrop ?? Component(); set backdrop(Component newBackdrop) { _backdrop.removeFromParent(); add(newBackdrop); @@ -557,6 +548,6 @@ class CameraComponent extends Component { } } -class CameraRenderContext extends ComponentRenderContext { +class CameraRenderContext() extends ComponentRenderContext { PostProcess? currentPostProcess; } diff --git a/packages/flame/lib/src/camera/viewfinder.dart b/packages/flame/lib/src/camera/viewfinder.dart index 8c638e7dc24..08fd9e958a7 100644 --- a/packages/flame/lib/src/camera/viewfinder.dart +++ b/packages/flame/lib/src/camera/viewfinder.dart @@ -16,17 +16,15 @@ import 'package:meta/meta.dart'; /// /// If you add children to the [Viewfinder] they will appear like HUDs i.e. /// statically in front of the world. -class Viewfinder extends Component +class Viewfinder({ + super.key, +}) extends Component implements AnchorProvider, AngleProvider, PositionProvider, ScaleProvider, CoordinateTransform { - Viewfinder({ - super.key, - }); - /// Transform matrix used by the viewfinder. final Transform2D transform = Transform2D(); diff --git a/packages/flame/lib/src/camera/viewport.dart b/packages/flame/lib/src/camera/viewport.dart index b72936fe18a..82b49d41076 100644 --- a/packages/flame/lib/src/camera/viewport.dart +++ b/packages/flame/lib/src/camera/viewport.dart @@ -18,17 +18,15 @@ import 'package:meta/meta.dart'; /// /// A viewport establishes its own local coordinate system, with the origin at /// the top left corner of the viewport's bounding box. -abstract class Viewport extends Component +abstract class Viewport({ + super.children, + super.key, +}) extends Component implements AnchorProvider, PositionProvider, SizeProvider, CoordinateTransform { - Viewport({ - super.children, - super.key, - }); - final Vector2 _size = Vector2.zero(); bool _isInitialized = false; diff --git a/packages/flame/lib/src/camera/viewports/fixed_aspect_ratio_viewport.dart b/packages/flame/lib/src/camera/viewports/fixed_aspect_ratio_viewport.dart index 2508bf952be..60a4ad75b66 100644 --- a/packages/flame/lib/src/camera/viewports/fixed_aspect_ratio_viewport.dart +++ b/packages/flame/lib/src/camera/viewports/fixed_aspect_ratio_viewport.dart @@ -11,14 +11,12 @@ import 'package:vector_math/vector_math.dart'; /// This viewport will automatically adjust its size and position when the /// game canvas changes in size. At the same time, manually changing the size /// of this viewport is not supported. -class FixedAspectRatioViewport extends Viewport { - FixedAspectRatioViewport({ - required this.aspectRatio, - super.children, - }) : assert(aspectRatio > 0); - +class FixedAspectRatioViewport({ /// The ratio of width to height of the viewport. - final double aspectRatio; + required final double aspectRatio, + super.children, +}) extends Viewport { + this : assert(aspectRatio > 0); Rect _clipRect = Rect.zero; diff --git a/packages/flame/lib/src/camera/viewports/fixed_resolution_viewport.dart b/packages/flame/lib/src/camera/viewports/fixed_resolution_viewport.dart index fab1e0e4758..fabf36e6692 100644 --- a/packages/flame/lib/src/camera/viewports/fixed_resolution_viewport.dart +++ b/packages/flame/lib/src/camera/viewports/fixed_resolution_viewport.dart @@ -13,15 +13,12 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// This viewport will automatically adjust its size and position when the /// game canvas changes in size. At the same time, manually changing the size /// of this viewport is not supported. -class FixedResolutionViewport extends FixedAspectRatioViewport - implements ReadOnlyScaleProvider { - FixedResolutionViewport({ - required this.resolution, - super.children, - }) : super(aspectRatio: resolution.x / resolution.y); - +class FixedResolutionViewport({ /// The resolution that the viewport should adhere to. - final Vector2 resolution; + required final Vector2 resolution, + super.children, +}) extends FixedAspectRatioViewport implements ReadOnlyScaleProvider { + this : super(aspectRatio: resolution.x / resolution.y); @override Vector2 get virtualSize => resolution; diff --git a/packages/flame/lib/src/camera/viewports/fixed_size_viewport.dart b/packages/flame/lib/src/camera/viewports/fixed_size_viewport.dart index b626c0ac9a7..9852d8cce30 100644 --- a/packages/flame/lib/src/camera/viewports/fixed_size_viewport.dart +++ b/packages/flame/lib/src/camera/viewports/fixed_size_viewport.dart @@ -7,12 +7,12 @@ import 'package:vector_math/vector_math.dart'; /// /// You can change the size of this viewport at runtime, but it will not /// auto-resize when its parent changes size. -class FixedSizeViewport extends Viewport { - FixedSizeViewport( - double width, - double height, { - super.children, - }) { +class FixedSizeViewport( + double width, + double height, { + super.children, +}) extends Viewport { + this { size = Vector2(width, height); } diff --git a/packages/flame/lib/src/camera/viewports/max_viewport.dart b/packages/flame/lib/src/camera/viewports/max_viewport.dart index b90c7015317..a5d28fc016f 100644 --- a/packages/flame/lib/src/camera/viewports/max_viewport.dart +++ b/packages/flame/lib/src/camera/viewports/max_viewport.dart @@ -7,9 +7,7 @@ import 'package:vector_math/vector_math.dart'; /// The default viewport, which is as big as the game canvas allows. /// /// This viewport does not perform any clipping. -class MaxViewport extends Viewport { - MaxViewport({super.children}); - +class MaxViewport({super.children}) extends Viewport { @override @mustCallSuper void onLoad() { diff --git a/packages/flame/lib/src/camera/world.dart b/packages/flame/lib/src/camera/world.dart index 28a06c01ad8..cea829c8c57 100644 --- a/packages/flame/lib/src/camera/world.dart +++ b/packages/flame/lib/src/camera/world.dart @@ -14,13 +14,11 @@ import 'package:vector_math/vector_math.dart'; /// The [priority] of the world by default is the maximum 32bit negative int /// value to ensure it will always be earlier in the component tree than a /// [CameraComponent]. -class World extends Component implements CoordinateTransform { - World({ - super.children, - super.priority = -0x7fffffff, - super.key, - }); - +class World({ + super.children, + super.priority = -0x7fffffff, + super.key, +}) extends Component implements CoordinateTransform { @override void renderTree(Canvas canvas) {} diff --git a/packages/flame/lib/src/collisions/broadphase/broadphase.dart b/packages/flame/lib/src/collisions/broadphase/broadphase.dart index 571c28a0661..795f4c560a1 100644 --- a/packages/flame/lib/src/collisions/broadphase/broadphase.dart +++ b/packages/flame/lib/src/collisions/broadphase/broadphase.dart @@ -15,9 +15,7 @@ import 'package:flame/collisions.dart'; /// for details. /// /// Always experiment to see which approach works best for your game. -abstract class Broadphase> { - Broadphase(); - +abstract class Broadphase>() { /// This method can be used if there are things that needs to be prepared in /// each tick. void update() {} diff --git a/packages/flame/lib/src/collisions/broadphase/collision_prospect.dart b/packages/flame/lib/src/collisions/broadphase/collision_prospect.dart index 38b7e53edb4..123df01f0ca 100644 --- a/packages/flame/lib/src/collisions/broadphase/collision_prospect.dart +++ b/packages/flame/lib/src/collisions/broadphase/collision_prospect.dart @@ -7,7 +7,7 @@ import 'package:meta/meta.dart'; /// /// Equality is based on unordered pair identity: {A, B} == {B, A}. @immutable -abstract class CollisionProspect { +abstract class const CollisionProspect() { T get a; T get b; diff --git a/packages/flame/lib/src/collisions/broadphase/prospect_pool.dart b/packages/flame/lib/src/collisions/broadphase/prospect_pool.dart index bf67d2b2085..d9273cda6d6 100644 --- a/packages/flame/lib/src/collisions/broadphase/prospect_pool.dart +++ b/packages/flame/lib/src/collisions/broadphase/prospect_pool.dart @@ -9,13 +9,11 @@ import 'package:flame/src/collisions/hitboxes/hitbox.dart'; /// /// Internally uses a private mutable subclass but only exposes the immutable /// [CollisionProspect] interface. Implements [Iterable] over acquired entries. -class ProspectPool> - extends IterableBase> { - ProspectPool({this.incrementSize = 1000}); - +class ProspectPool>({ /// How much the pool should increase in size every time it needs to be made /// larger. - final int incrementSize; + final int incrementSize = 1000, +}) extends IterableBase> { final _storage = <_MutableCollisionProspect>[]; /// The number of prospects currently acquired this frame. @@ -70,12 +68,10 @@ class ProspectPool> } } -class _ProspectPoolIterator> - implements Iterator> { - _ProspectPoolIterator(this._storage, this._length); - - final List<_MutableCollisionProspect> _storage; - final int _length; +class _ProspectPoolIterator>( + final List<_MutableCollisionProspect> _storage, + final int _length, +) implements Iterator> { int _index = -1; @override @@ -93,12 +89,8 @@ class _ProspectPoolIterator> /// hash-based collections. All access outside this file is through the /// immutable [CollisionProspect] interface. // ignore: must_be_immutable -class _MutableCollisionProspect extends CollisionProspect { - _MutableCollisionProspect(this._a, this._b); - - T _a; - T _b; - +class _MutableCollisionProspect(var T _a, var T _b) + extends CollisionProspect { @override T get a => _a; @override diff --git a/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart b/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart index a2789d938b5..284d88179d8 100644 --- a/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart +++ b/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart @@ -3,41 +3,35 @@ import 'dart:collection'; import 'package:flame/collisions.dart'; import 'package:flame/extensions.dart'; -typedef ExternalBroadphaseCheck = - bool Function( - ShapeHitbox first, - ShapeHitbox second, - ); - -typedef ExternalMinDistanceCheck = - bool Function( - Vector2 activeItemCenter, - Vector2 potentialCenter, - ); +typedef ExternalBroadphaseCheck = bool Function( + ShapeHitbox first, + ShapeHitbox second, +); + +typedef ExternalMinDistanceCheck = bool Function( + Vector2 activeItemCenter, + Vector2 potentialCenter, +); /// Performs Quad Tree broadphase check. /// /// See [HasQuadTreeCollisionDetection.initializeCollisionDetection] for a /// detailed description of its initialization parameters. -class QuadTreeBroadphase extends Broadphase { - QuadTreeBroadphase({ - required Rect mainBoxSize, - required this.broadphaseCheck, - required this.minimumDistanceCheck, - int maxObjects = 25, - int maxDepth = 10, - }) : tree = QuadTree( - mainBoxSize: mainBoxSize, - maxObjects: maxObjects, - maxDepth: maxDepth, - ); - - final QuadTree tree; +class QuadTreeBroadphase({ + required Rect mainBoxSize, + required var ExternalBroadphaseCheck broadphaseCheck, + required var ExternalMinDistanceCheck minimumDistanceCheck, + int maxObjects = 25, + int maxDepth = 10, +}) extends Broadphase { + final QuadTree tree = QuadTree( + mainBoxSize: mainBoxSize, + maxObjects: maxObjects, + maxDepth: maxDepth, + ); final activeHitboxes = HashSet(); - ExternalBroadphaseCheck broadphaseCheck; - ExternalMinDistanceCheck minimumDistanceCheck; final _broadphaseCheckCache = >{}; final _cachedCenters = {}; @@ -82,7 +76,7 @@ class QuadTreeBroadphase extends Broadphase { itemCenter, _cacheCenterOfHitbox(potential), ); - if (distanceCloseEnough == false) { + if (!distanceCloseEnough) { continue; } diff --git a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart index a7d30fa0ab4..d9b02e0b543 100644 --- a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart +++ b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart @@ -14,18 +14,11 @@ import 'package:flame/extensions.dart'; /// 7. Call [clear] to remove all data. /// /// Use [optimize] to scan the tree and remove unused quadrants. -class QuadTree> { - QuadTree({ - this.maxObjects = 25, - this.maxDepth = 10, - this.mainBoxSize = Rect.zero, - }); - - final int maxObjects; - final int maxDepth; - - Rect mainBoxSize; - +class QuadTree>({ + final int maxObjects = 25, + final int maxDepth = 10, + var Rect mainBoxSize = Rect.zero, +}) { var _rootNode = QuadTreeNode(); int _nodeLastId = 0; final _oldPositionByItem = {}; @@ -292,19 +285,17 @@ class QuadTree> { /// Use [rect] to get node's computed box; /// The class might be useful to render debugging info. /// See examples for details. -class QuadTreeNodeDebugInfo { - QuadTreeNodeDebugInfo(this.rect, this.node, this.cd); - +class QuadTreeNodeDebugInfo( + final Rect rect, + final QuadTreeNode node, + final QuadTreeCollisionDetection cd, +) { factory QuadTreeNodeDebugInfo.init(QuadTreeCollisionDetection cd) { final node = cd.broadphase.tree._rootNode; final rect = cd.broadphase.tree.mainBoxSize; return QuadTreeNodeDebugInfo(rect, node, cd); } - final Rect rect; - final QuadTreeNode node; - final QuadTreeCollisionDetection cd; - List get ownElements => node.hitboxes as List; List get allElements => @@ -331,7 +322,7 @@ class QuadTreeNodeDebugInfo { } } -class QuadTreeNode> { +class QuadTreeNode>() { final List children = List.generate( 4, (index) => null, @@ -362,15 +353,13 @@ class QuadTreeNode> { } } -enum _QuadTreeZone { +enum _QuadTreeZone(final int value) { root(-1), topLeft(0), topRight(1), bottomLeft(2), bottomRight(3); - const _QuadTreeZone(this.value); - factory _QuadTreeZone.fromIndex(int i) { return switch (i) { 0 => _QuadTreeZone.topLeft, @@ -380,6 +369,4 @@ enum _QuadTreeZone { _ => _QuadTreeZone.root, }; } - - final int value; } diff --git a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart index 9a34e8de295..506ff90fa78 100644 --- a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart +++ b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart @@ -5,23 +5,23 @@ import 'package:flutter/widgets.dart'; /// /// Do not use standard [items] list for components. Instead adds all components /// into [QuadTreeBroadphase] class. -class QuadTreeCollisionDetection - extends StandardCollisionDetection { - QuadTreeCollisionDetection({ - required Rect mapDimensions, - required ExternalBroadphaseCheck onComponentTypeCheck, - required ExternalMinDistanceCheck minimumDistanceCheck, - int maxObjects = 25, - int maxDepth = 10, - }) : super( - broadphase: QuadTreeBroadphase( - mainBoxSize: mapDimensions, - maxObjects: maxObjects, - maxDepth: maxDepth, - broadphaseCheck: onComponentTypeCheck, - minimumDistanceCheck: minimumDistanceCheck, - ), - ); +class QuadTreeCollisionDetection({ + required Rect mapDimensions, + required ExternalBroadphaseCheck onComponentTypeCheck, + required ExternalMinDistanceCheck minimumDistanceCheck, + int maxObjects = 25, + int maxDepth = 10, +}) extends StandardCollisionDetection { + this + : super( + broadphase: QuadTreeBroadphase( + mainBoxSize: mapDimensions, + maxObjects: maxObjects, + maxDepth: maxDepth, + broadphaseCheck: onComponentTypeCheck, + minimumDistanceCheck: minimumDistanceCheck, + ), + ); final _listenerCollisionType = {}; final _scheduledUpdate = {}; diff --git a/packages/flame/lib/src/collisions/broadphase/sweep/sweep.dart b/packages/flame/lib/src/collisions/broadphase/sweep/sweep.dart index 42aabb4bb81..327cacd84a7 100644 --- a/packages/flame/lib/src/collisions/broadphase/sweep/sweep.dart +++ b/packages/flame/lib/src/collisions/broadphase/sweep/sweep.dart @@ -1,11 +1,9 @@ import 'package:collection/collection.dart'; import 'package:flame/collisions.dart'; -class Sweep> extends Broadphase { - Sweep({List? items}) : items = items ?? []; - +class Sweep>({List? items}) extends Broadphase { @override - final List items; + final List items = items ?? []; final _active = []; final _prospectPool = ProspectPool(); diff --git a/packages/flame/lib/src/collisions/collision_callbacks.dart b/packages/flame/lib/src/collisions/collision_callbacks.dart index f95bc2e8cb1..2f6b85fb3a4 100644 --- a/packages/flame/lib/src/collisions/collision_callbacks.dart +++ b/packages/flame/lib/src/collisions/collision_callbacks.dart @@ -4,7 +4,7 @@ import 'package:flutter/foundation.dart'; /// The [CollisionType] is used to determine which other hitboxes that it /// should collide with. -enum CollisionType { +enum CollisionType() { /// Collides with other hitboxes of type active or passive. active, @@ -16,9 +16,8 @@ enum CollisionType { } /// Utility class allows to subscribe on collision type changing event -class CollisionTypeNotifier with ChangeNotifier { - CollisionTypeNotifier(CollisionType type) : _value = type; - CollisionType _value = CollisionType.active; +class CollisionTypeNotifier(CollisionType type) with ChangeNotifier { + CollisionType _value = type; set value(CollisionType type) { _value = type; @@ -165,11 +164,10 @@ mixin CollisionCallbacks on Component /// Can be used used to implement an `onCollisionCallback` or an /// `onCollisionStartCallback`. -typedef CollisionCallback = - void Function( - List intersectionPoints, - T other, - ); +typedef CollisionCallback = void Function( + List intersectionPoints, + T other, +); /// Can be used used to implement an `onCollisionEndCallback`. typedef CollisionEndCallback = void Function(T other); diff --git a/packages/flame/lib/src/collisions/collision_detection.dart b/packages/flame/lib/src/collisions/collision_detection.dart index 6f0de5d5139..df1113ae3b9 100644 --- a/packages/flame/lib/src/collisions/collision_detection.dart +++ b/packages/flame/lib/src/collisions/collision_detection.dart @@ -11,16 +11,12 @@ import 'package:material_ui/material_ui.dart'; abstract class CollisionDetection< T extends Hitbox, B extends Broadphase -> { - final B broadphase; - +>({required final B broadphase}) { List get items => broadphase.items; final _lastProspectPool = ProspectPool(); final _currentPotentials = >{}; final collisionsCompletedNotifier = CollisionDetectionCompletionNotifier(); - CollisionDetection({required this.broadphase}); - void add(T item) => broadphase.add(item); void addAll(Iterable items) => items.forEach(add); @@ -183,7 +179,7 @@ abstract class CollisionDetection< /// A class to handle callbacks for when the collision detection is done each /// tick. -class CollisionDetectionCompletionNotifier extends ChangeNotifier { +class CollisionDetectionCompletionNotifier() extends ChangeNotifier { @override void notifyListeners() => super.notifyListeners(); } diff --git a/packages/flame/lib/src/collisions/collision_passthrough.dart b/packages/flame/lib/src/collisions/collision_passthrough.dart index cedffc39d40..f13f013425b 100644 --- a/packages/flame/lib/src/collisions/collision_passthrough.dart +++ b/packages/flame/lib/src/collisions/collision_passthrough.dart @@ -15,11 +15,9 @@ mixin CollisionPassthrough on CollisionCallbacks { @mustCallSuper void onMount() { super.onMount(); - passthroughParent = - ancestors().firstWhereOrNull( - (c) => c is CollisionCallbacks, - ) - as CollisionCallbacks?; + passthroughParent = ancestors().firstWhereOrNull( + (c) => c is CollisionCallbacks, + ) as CollisionCallbacks?; } @override diff --git a/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart index e36915a7e7c..6f6a234c8cd 100644 --- a/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart @@ -1,5 +1,3 @@ -// ignore_for_file: comment_references - import 'dart:math'; import 'package:flame/collisions.dart'; diff --git a/packages/flame/lib/src/collisions/hitboxes/composite_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/composite_hitbox.dart index 3ebaf2a0a69..59e481cc1b9 100644 --- a/packages/flame/lib/src/collisions/hitboxes/composite_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/composite_hitbox.dart @@ -8,15 +8,12 @@ import 'package:flame/components.dart'; /// [RectangleHitbox]s to follow that hats edges properly, then you can add /// those hitboxes to an instance of this class and react to collisions to the /// whole hat, instead of for just each hitbox separately. -class CompositeHitbox extends PositionComponent - with CollisionCallbacks, CollisionPassthrough { - CompositeHitbox({ - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - Iterable? super.children, - super.priority, - }); -} +class CompositeHitbox({ + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + Iterable? super.children, + super.priority, +}) extends PositionComponent with CollisionCallbacks, CollisionPassthrough; diff --git a/packages/flame/lib/src/collisions/hitboxes/hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/hitbox.dart index f8310745a34..2fd0383d027 100644 --- a/packages/flame/lib/src/collisions/hitboxes/hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/hitbox.dart @@ -4,7 +4,7 @@ import 'package:flame/extensions.dart'; /// The [Hitbox] is the default building block to determine whether two objects /// have collided with each other. [ShapeHitbox] is the default implementation /// used in FCS. -abstract class Hitbox> +abstract class Hitbox>() implements GenericCollisionCallbacks { /// Whether the hitbox should: /// * [CollisionType.active] - actively collide with other hitboxes. diff --git a/packages/flame/lib/src/collisions/hitboxes/path_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/path_hitbox.dart index bff2b576eb4..59104ed4386 100644 --- a/packages/flame/lib/src/collisions/hitboxes/path_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/path_hitbox.dart @@ -8,24 +8,24 @@ import 'package:meta/meta.dart'; /// The polygons form a single hitbox: it collides, contains points and is hit /// by rays as a whole, whichever of its polygons is involved. See /// [PathComponent] for how the polygons are made from the path. -class PathHitbox extends PathComponent with ShapeHitbox { +class PathHitbox({ + required super.path, + super.sampling, + super.tolerance, + super.filter, + super.position, + super.angle, + super.anchor, + super.isSolid, + CollisionType collisionType = CollisionType.active, +}) extends PathComponent with ShapeHitbox { /// With this constructor you create a [PathHitbox] from all the closed /// contours of the [path]. /// /// See [PathComponent.new] for the [sampling], [tolerance] and [filter] /// parameters. Fewer vertices make the collision detection cheaper, so use /// the highest sampling that still follows the path closely enough. - PathHitbox({ - required super.path, - super.sampling, - super.tolerance, - super.filter, - super.position, - super.angle, - super.anchor, - super.isSolid, - CollisionType collisionType = CollisionType.active, - }) { + this { this.collisionType = collisionType; } diff --git a/packages/flame/lib/src/collisions/hitboxes/polygon_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/polygon_hitbox.dart index 8476a790dc6..24b7c63b7cc 100644 --- a/packages/flame/lib/src/collisions/hitboxes/polygon_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/polygon_hitbox.dart @@ -1,5 +1,3 @@ -// ignore_for_file: comment_references - import 'package:flame/collisions.dart'; import 'package:flame/extensions.dart'; import 'package:flame/geometry.dart'; diff --git a/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart index 089fc2168b9..00420c90349 100644 --- a/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart @@ -1,5 +1,3 @@ -// ignore_for_file: comment_references - import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/src/geometry/polygon_ray_intersection.dart'; diff --git a/packages/flame/lib/src/collisions/hitboxes/screen_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/screen_hitbox.dart index d470d587d60..4d288b17fb3 100644 --- a/packages/flame/lib/src/collisions/hitboxes/screen_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/screen_hitbox.dart @@ -7,7 +7,8 @@ import 'package:flame/src/collisions/hitboxes/rectangle_hitbox.dart'; /// This component is used to detect hitboxes colliding into the edges of the /// viewport of the game. -class ScreenHitbox extends PositionComponent +class ScreenHitbox() + extends PositionComponent with CollisionCallbacks, HasGameRef { bool _hasWorldAncestor = false; @override diff --git a/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart index 825ca098a88..9fd25cea254 100644 --- a/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart @@ -78,16 +78,14 @@ mixin ShapeHitbox on ShapeComponent implements Hitbox { @override void onMount() { super.onMount(); - _hitboxParent = - ancestors().firstWhere( - (c) => c is PositionComponent && c is! CompositeHitbox, - orElse: () { - throw StateError( - 'A ShapeHitbox needs a PositionComponent ancestor', - ); - }, - ) - as PositionComponent; + _hitboxParent = ancestors().firstWhere( + (c) => c is PositionComponent && c is! CompositeHitbox, + orElse: () { + throw StateError( + 'A ShapeHitbox needs a PositionComponent ancestor', + ); + }, + ) as PositionComponent; _transformListener = () { _validAabb = false; diff --git a/packages/flame/lib/src/collisions/standard_collision_detection.dart b/packages/flame/lib/src/collisions/standard_collision_detection.dart index 439eed41d48..8f019c7eab9 100644 --- a/packages/flame/lib/src/collisions/standard_collision_detection.dart +++ b/packages/flame/lib/src/collisions/standard_collision_detection.dart @@ -10,10 +10,10 @@ import 'package:flame/geometry.dart'; /// /// By default the [Sweep] broadphase is used, this can be configured by /// passing in another [Broadphase] to the constructor. -class StandardCollisionDetection> - extends CollisionDetection { - StandardCollisionDetection({B? broadphase}) - : super(broadphase: broadphase ?? Sweep() as B); +class StandardCollisionDetection>({ + B? broadphase, +}) extends CollisionDetection { + this : super(broadphase: broadphase ?? Sweep() as B); /// Check what the intersection points of two collidables are, /// returns an empty list if there are no intersections. diff --git a/packages/flame/lib/src/components/clip_component.dart b/packages/flame/lib/src/components/clip_component.dart index f3a374d1941..c207103b693 100644 --- a/packages/flame/lib/src/components/clip_component.dart +++ b/packages/flame/lib/src/components/clip_component.dart @@ -9,22 +9,17 @@ typedef ShapeBuilder = Shape Function(Vector2 size); /// {@template clip_component} /// A component that will clip its content. /// {@endtemplate} -class ClipComponent extends PositionComponent { - /// {@macro clip_component} - /// - /// Clips the canvas based its shape and size. - ClipComponent({ - required this._builder, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }); - +class ClipComponent({ + required final ShapeBuilder _builder, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { /// {@macro circle_clip_component} /// /// Clips the canvas in the form of a circle based on its size. @@ -100,8 +95,6 @@ class ClipComponent extends PositionComponent { late Path _path; late Shape _shape; - final ShapeBuilder _builder; - @override Future onLoad() async { _prepare(); diff --git a/packages/flame/lib/src/components/component_pool.dart b/packages/flame/lib/src/components/component_pool.dart index 69e4e1c8e89..2e6012778f9 100644 --- a/packages/flame/lib/src/components/component_pool.dart +++ b/packages/flame/lib/src/components/component_pool.dart @@ -32,14 +32,16 @@ import 'package:flame/components.dart'; /// parent, so you don't need to manually release them. Simply call /// [Component.removeFromParent] when the component should be destroyed, and it /// will be automatically returned to the pool for reuse. -class ComponentPool { - final T Function() _factory; - final List _available = []; +class ComponentPool({ + required final T Function() _factory, /// The maximum number of components that can be stored in the pool. If the /// pool reaches this limit, additional components released back to the pool /// will be discarded. - final int maxSize; + final int maxSize = 100, + int initialSize = 0, +}) { + final List _available = []; /// Creates a new component pool with the specified factory, maximum size, and /// initial size. The [_factory] is a function that creates new instances of @@ -49,11 +51,7 @@ class ComponentPool { /// /// If the [initialSize] exceeds the [maxSize], only [maxSize] components /// will be created and added to the pool. - ComponentPool({ - required this._factory, - this.maxSize = 100, - int initialSize = 0, - }) { + this { for (var i = 0; i < initialSize && i < maxSize; i++) { _available.add(_factory()); } diff --git a/packages/flame/lib/src/components/components_notifier.dart b/packages/flame/lib/src/components/components_notifier.dart index 4106146a9d2..6d7a68baf33 100644 --- a/packages/flame/lib/src/components/components_notifier.dart +++ b/packages/flame/lib/src/components/components_notifier.dart @@ -11,10 +11,9 @@ import 'package:meta/meta.dart'; /// /// For example, in a Player component, that holds a health variable /// you may want to notify changes when that variable has changed. -class ComponentsNotifier extends ChangeNotifier { - ComponentsNotifier(List initial) : _components = initial; - - final List _components; +class ComponentsNotifier(List initial) + extends ChangeNotifier { + final List _components = initial; /// The list of components. List get components => UnmodifiableListView(_components); diff --git a/packages/flame/lib/src/components/core/component.dart b/packages/flame/lib/src/components/core/component.dart index e2bf3a3fa14..14170a97168 100644 --- a/packages/flame/lib/src/components/core/component.dart +++ b/packages/flame/lib/src/components/core/component.dart @@ -69,12 +69,16 @@ part 'custom_traversal.dart'; /// You may also need to override [containsLocalPoint] if the component needs to /// respond to tap events or similar; the [componentsAtLocation] may also need /// to be overridden if you have reimplemented [renderTree]. -class Component { - Component({ - Iterable? children, - int? priority, - this.key, - }) : _priority = priority ?? 0 { +class Component({ + Iterable? children, + int? priority, + + /// A key that can be used to identify this component in the tree. + /// + /// It can be used to retrieve this component from anywhere in the tree. + final ComponentKey? key, +}) { + this { _isTraversalBarrier = this is CustomTraversal; if (children != null) { addAll(children); @@ -1041,7 +1045,7 @@ class Component { /// already added to a component tree since all siblings have to be re-added /// to the parent. int get priority => _priority; - int _priority; + int _priority = priority ?? 0; set priority(int newPriority) { if (_priority != newPriority) { _priority = newPriority; @@ -1455,11 +1459,6 @@ class Component { /// the output. int? debugCoordinatesPrecision = 0; - /// A key that can be used to identify this component in the tree. - /// - /// It can be used to retrieve this component from anywhere in the tree. - final ComponentKey? key; - /// The color that the debug output should be rendered with. Color debugColor = const Color(0xFFFF00FF); @@ -1509,20 +1508,17 @@ class Component { //#endregion } -enum ChildrenChangeType { added, removed } +enum ChildrenChangeType() { + added, + removed, +} /// The lazy [Iterable] returned by [Component.descendants]. -class _DescendantsIterable extends Iterable { - _DescendantsIterable( - this._root, { - required this.includeSelf, - required this.reversed, - }); - - final Component _root; - final bool includeSelf; - final bool reversed; - +class _DescendantsIterable( + final Component _root, { + required final bool includeSelf, + required final bool reversed, +}) extends Iterable { @override Iterator get iterator => reversed ? _ReversedDescendantsIterator(_root, includeSelf: includeSelf) @@ -1538,16 +1534,13 @@ class _DescendantsIterable extends Iterable { /// is only created on the following [moveNext], after the caller has processed /// the component itself, so a caller may still reorder the children of the /// component it just received. -class _DescendantsIterator implements Iterator { - _DescendantsIterator(Component root, {required bool includeSelf}) - : _pendingRoot = includeSelf ? root : null, - _pendingPush = includeSelf ? null : root; - +class _DescendantsIterator(Component root, {required bool includeSelf}) + implements Iterator { /// The root, while it still has to be emitted. - Component? _pendingRoot; + Component? _pendingRoot = includeSelf ? root : null; /// The component whose children iterator has not been pushed yet. - Component? _pendingPush; + Component? _pendingPush = includeSelf ? null : root; final List> _stack = []; Component? _current; @@ -1596,14 +1589,13 @@ class _DescendantsIterator implements Iterator { /// keeps the parent of every open iterator on a parallel stack. The root's /// children iterator is only created on the first [moveNext], so the tree is /// not touched before iteration starts. -class _ReversedDescendantsIterator implements Iterator { - _ReversedDescendantsIterator(this._root, {required bool includeSelf}) - : _pendingRoot = includeSelf; - - final Component _root; +class _ReversedDescendantsIterator( + final Component _root, { + required bool includeSelf, +}) implements Iterator { final List _parents = []; final List> _stack = []; - bool _pendingRoot; + bool _pendingRoot = includeSelf; bool _started = false; Component? _current; diff --git a/packages/flame/lib/src/components/core/component_list.dart b/packages/flame/lib/src/components/core/component_list.dart index 615f4ee3875..67d5ea2fb49 100644 --- a/packages/flame/lib/src/components/core/component_list.dart +++ b/packages/flame/lib/src/components/core/component_list.dart @@ -17,12 +17,10 @@ part of 'component.dart'; /// /// Components of a specific type can be retrieved in constant time with /// [query], once the type has been registered with [register]. -class ComponentList extends Iterable { - ComponentList({this.strictMode = false, this.comparator}); - +class ComponentList({ /// Whether calling [query] for an unregistered type throws an error /// (`true`), or registers the type on first use (`false`). - final bool strictMode; + final bool strictMode = false, /// An optional custom ordering, replacing the default ordering by /// [Component.priority]. Supply one via [Component.createComponentList]. @@ -31,8 +29,8 @@ class ComponentList extends Iterable { /// their insertion order. If the values that the comparator reads change /// after insertion, call [Component.rebalanceChildren] to restore the /// ordering (priority changes on mounted components do this automatically). - final Comparator? comparator; - + final Comparator? comparator, +}) extends Iterable { /// The relative order of [a] and [b]: by the custom [comparator] if one /// was supplied, otherwise by [Component.priority]. int _compareOrder(Component a, Component b) { @@ -405,11 +403,9 @@ int _partitionPoint(List list, bool Function(T element) isBefore) { return low; } -class _ComponentListIterator implements Iterator { - _ComponentListIterator(this._list) : _shiftCount = _list._shiftCount; - - final ComponentList _list; - final int _shiftCount; +class _ComponentListIterator(final ComponentList _list) + implements Iterator { + final int _shiftCount = _list._shiftCount; int _index = -1; Component? _current; @@ -439,11 +435,8 @@ class _ComponentListIterator implements Iterator { } } -class _ReversedComponentListView extends Iterable { - _ReversedComponentListView(this._list); - - final ComponentList _list; - +class _ReversedComponentListView(final ComponentList _list) + extends Iterable { @override int get length => _list._length; @@ -457,15 +450,10 @@ class _ReversedComponentListView extends Iterable { Iterator get iterator => _ReversedComponentListIterator(_list); } -class _ReversedComponentListIterator implements Iterator { - _ReversedComponentListIterator(ComponentList list) - : _list = list, - _shiftCount = list._shiftCount, - _index = list._elements.length; - - final ComponentList _list; - final int _shiftCount; - int _index; +class _ReversedComponentListIterator(final ComponentList _list) + implements Iterator { + final int _shiftCount = _list._shiftCount; + int _index = _list._elements.length; Component? _current; @override @@ -496,11 +484,7 @@ class _ReversedComponentListIterator implements Iterator { /// A cached, always up-to-date result of `query()`: the subset of the /// elements that are of type [C], in the same order as the main list. -class _QueryCache { - _QueryCache(this.data); - - final List data; - +class _QueryCache(final List data) { bool check(Component component) => component is C; /// Inserts [component] into [data], keeping it ordered consistently with diff --git a/packages/flame/lib/src/components/core/component_render_context.dart b/packages/flame/lib/src/components/core/component_render_context.dart index 7e34da62235..34cda4f0d89 100644 --- a/packages/flame/lib/src/components/core/component_render_context.dart +++ b/packages/flame/lib/src/components/core/component_render_context.dart @@ -1 +1 @@ -abstract class ComponentRenderContext {} +abstract class ComponentRenderContext(); diff --git a/packages/flame/lib/src/components/core/component_tree_root.dart b/packages/flame/lib/src/components/core/component_tree_root.dart index f941d2666bd..55bf53b2d96 100644 --- a/packages/flame/lib/src/components/core/component_tree_root.dart +++ b/packages/flame/lib/src/components/core/component_tree_root.dart @@ -3,7 +3,7 @@ part of 'component.dart'; /// A future that can be awaited repeatedly, and is resolved by calling /// [fire]. Once fired, a new future is created lazily for the next round of /// waiters, so the signal can be awaited again right away. -class _ResettableSignal { +class _ResettableSignal() { Completer? _completer; /// Whether some caller is currently awaiting [future]. @@ -23,12 +23,11 @@ class _ResettableSignal { /// This class is just a regular [Component], with some additional /// functionality, namely: it contains global lifecycle events for the component /// tree. -class ComponentTreeRoot extends Component { - ComponentTreeRoot({ - super.children, - super.key, - }) : queue = RecycledQueue(LifecycleEvent.new), - _blocked = {}; +class ComponentTreeRoot({ + super.children, + super.key, +}) extends Component { + this : queue = RecycledQueue(LifecycleEvent.new), _blocked = {}; @internal final RecycledQueue queue; @@ -351,7 +350,7 @@ class ComponentTreeRoot extends Component { } /// The status of processing a Lifecycle event. -enum _LifecycleEventStatus { +enum _LifecycleEventStatus() { /// The event cannot be processed yet: move over to the next one, and skip /// any other events for the same child or parent in this pass. block, @@ -361,7 +360,7 @@ enum _LifecycleEventStatus { } @internal -enum LifecycleEventKind { +enum LifecycleEventKind() { unknown, add, remove, @@ -370,7 +369,7 @@ enum LifecycleEventKind { } @visibleForTesting -class LifecycleEvent implements Disposable { +class LifecycleEvent() implements Disposable { LifecycleEventKind kind = LifecycleEventKind.unknown; Component? child; Component? parent; diff --git a/packages/flame/lib/src/components/core/recycled_queue.dart b/packages/flame/lib/src/components/core/recycled_queue.dart index 8ba787ab46c..84c9eaf748b 100644 --- a/packages/flame/lib/src/components/core/recycled_queue.dart +++ b/packages/flame/lib/src/components/core/recycled_queue.dart @@ -27,16 +27,12 @@ import 'dart:math'; /// shared cursor. /// /// Internally, the queue is backed by a circular list. -class RecycledQueue extends Iterable - implements Iterator { - RecycledQueue(this.factory, {int initialCapacity = 8}) - : _elements = List.generate(initialCapacity, (i) => factory()), - _startIndex = -1, - _endIndex = -1, - _currentIndex = -1; - +class RecycledQueue( /// Function for creating new elements in the queue. - final T Function() factory; + final T Function() factory, { + int initialCapacity = 8, +}) extends Iterable implements Iterator { + this : _startIndex = -1, _endIndex = -1, _currentIndex = -1; /// Index of the first element in the queue, or -1 if the queue is empty. int _startIndex; @@ -57,16 +53,16 @@ class RecycledQueue extends Iterable /// /// Two data layouts are possible: the normal one, when [_endIndex] is larger /// than or equal to the [_startIndex]: - /// ``` + /// ```text /// [----S############E--] /// ``` /// and the wrap-around layout ([_endIndex] < [_startIndex]), which occurs /// when the active elements reach the end of the allocated list and start /// reusing items in the beginning: - /// ``` + /// ```text /// [##E------S##########] /// ``` - final List _elements; + final List _elements = List.generate(initialCapacity, (i) => factory()); /// The list of indices of elements that ought to be removed: this list is /// populated when elements are removed during the iteration, and then the @@ -339,6 +335,6 @@ class RecycledQueue extends Iterable } /// The interface for the elements allowed in the [RecycledQueue]. -abstract class Disposable { +abstract class Disposable() { void dispose(); } diff --git a/packages/flame/lib/src/components/custom_painter_component.dart b/packages/flame/lib/src/components/custom_painter_component.dart index 62010373457..f01844446d6 100644 --- a/packages/flame/lib/src/components/custom_painter_component.dart +++ b/packages/flame/lib/src/components/custom_painter_component.dart @@ -10,21 +10,17 @@ import 'package:flutter/widgets.dart'; /// /// Note that given the active rendering nature of a game, `shouldRepaint` is /// ignored by this component. -class CustomPainterComponent extends PositionComponent { +class CustomPainterComponent({ /// The [CustomPainter] used to render this component - CustomPainter? painter; - - CustomPainterComponent({ - this.painter, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - }); - + var CustomPainter? painter, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, +}) extends PositionComponent { @override @mustCallSuper void render(Canvas canvas) { diff --git a/packages/flame/lib/src/components/debug/child_counter_component.dart b/packages/flame/lib/src/components/debug/child_counter_component.dart index bca90219cc5..6607ade6306 100644 --- a/packages/flame/lib/src/components/debug/child_counter_component.dart +++ b/packages/flame/lib/src/components/debug/child_counter_component.dart @@ -8,13 +8,10 @@ import 'package:flame/text.dart'; /// a target component. /// /// Add it to the game to start seeing the count. -class ChildCounterComponent extends TextComponent { - ChildCounterComponent({ - required this.target, - super.position, - }); - - final Component target; +class ChildCounterComponent({ + required final Component target, + super.position, +}) extends TextComponent { late String _label; @override diff --git a/packages/flame/lib/src/components/debug/time_track_component.dart b/packages/flame/lib/src/components/debug/time_track_component.dart index 5d24608004a..3c29bf09941 100644 --- a/packages/flame/lib/src/components/debug/time_track_component.dart +++ b/packages/flame/lib/src/components/debug/time_track_component.dart @@ -14,9 +14,7 @@ import 'package:flame/text.dart'; /// and [TimeTrackComponent.end] with that same identifier to finish tracking. /// /// To see the recorded times, simply add this component to your game. -class TimeTrackComponent extends TextComponent { - TimeTrackComponent({super.position}); - +class TimeTrackComponent({super.position}) extends TextComponent { static final Map _startTimes = {}; static final Map _endTimes = {}; diff --git a/packages/flame/lib/src/components/fps_component.dart b/packages/flame/lib/src/components/fps_component.dart index 38296ab41c3..c55fcf6ddcb 100644 --- a/packages/flame/lib/src/components/fps_component.dart +++ b/packages/flame/lib/src/components/fps_component.dart @@ -5,16 +5,12 @@ import 'package:flame/components.dart'; /// The [FpsComponent] is a non-visual component which you can get the current /// fps of the game with by calling [fps], once the component has been added to /// the component tree. -class FpsComponent extends Component { - FpsComponent({ - this.windowSize = 60, - super.key, - }); - +class FpsComponent({ /// The sliding window size, i.e. the number of game ticks over which the fps /// measure will be averaged. - final int windowSize; - + final int windowSize = 60, + super.key, +}) extends Component { /// The queue of the recent game tick durations. /// The length of this queue will not exceed [windowSize]. final Queue window = Queue(); diff --git a/packages/flame/lib/src/components/fps_text_component.dart b/packages/flame/lib/src/components/fps_text_component.dart index 4508d351792..c608aad73ba 100644 --- a/packages/flame/lib/src/components/fps_text_component.dart +++ b/packages/flame/lib/src/components/fps_text_component.dart @@ -3,26 +3,25 @@ import 'package:flame/text.dart'; /// The [FpsTextComponent] is a [TextComponent] that writes out the current FPS. /// It has a [FpsComponent] as a child which does the actual calculations. -class FpsTextComponent extends TextComponent { - FpsTextComponent({ - int windowSize = 60, - this.decimalPlaces = 0, - T? super.textRenderer, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - int? priority, - }) : fpsComponent = FpsComponent(windowSize: windowSize), - super( - priority: priority ?? double.maxFinite.toInt(), - ) { +class FpsTextComponent({ + int windowSize = 60, + final int decimalPlaces = 0, + T? super.textRenderer, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + int? priority, +}) extends TextComponent { + this + : super( + priority: priority ?? double.maxFinite.toInt(), + ) { add(fpsComponent); } - final int decimalPlaces; - final FpsComponent fpsComponent; + final FpsComponent fpsComponent = FpsComponent(windowSize: windowSize); @override void update(double dt) { diff --git a/packages/flame/lib/src/components/icon_component.dart b/packages/flame/lib/src/components/icon_component.dart index 0315f18a579..5378d11e50a 100644 --- a/packages/flame/lib/src/components/icon_component.dart +++ b/packages/flame/lib/src/components/icon_component.dart @@ -26,14 +26,24 @@ import 'package:meta/meta.dart'; /// position: Vector2(100, 100), /// )..tint(const Color(0xFFFFD700)); // Gold tint /// ``` -class IconComponent extends PositionComponent with HasPaint { +class IconComponent({ /// The icon to render. - IconData? _icon; + var IconData? _icon, /// The size at which to rasterize the icon. This controls the resolution /// of the rasterized image, independent of the component's display [size]. - double _iconSize; - + var double _iconSize = 64, + Paint? paint, + super.position, + Vector2? size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasPaint { /// The rasterized icon image (rendered in white for tinting). @visibleForTesting Image? image; @@ -54,20 +64,7 @@ class IconComponent extends PositionComponent with HasPaint { /// - [paint]: Optional paint for rendering effects. /// - [size]: The display size of the component. Defaults to /// `Vector2.all(iconSize)` if not specified. - IconComponent({ - this._icon, - this._iconSize = 64, - Paint? paint, - super.position, - Vector2? size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - }) : super(size: size ?? Vector2.all(_iconSize)) { + this : super(size: size ?? Vector2.all(_iconSize)) { if (paint != null) { this.paint = paint; } diff --git a/packages/flame/lib/src/components/input/advanced_button_component.dart b/packages/flame/lib/src/components/input/advanced_button_component.dart index c1876eb05f7..47f76e84fb4 100644 --- a/packages/flame/lib/src/components/input/advanced_button_component.dart +++ b/packages/flame/lib/src/components/input/advanced_button_component.dart @@ -15,48 +15,42 @@ import 'package:flutter/foundation.dart'; /// Note: You have to set the skins that you want to use ([defaultSkin], /// [downSkin], [hoverSkin], [disabledSkin], [defaultLabel]) in [onLoad] /// if you are not passing them in through the constructor. -class AdvancedButtonComponent extends PositionComponent - with HoverCallbacks, TapCallbacks { - AdvancedButtonComponent({ - this.onPressed, - this.onReleased, - this.onCancelled, - this.onChangeState, - PositionComponent? defaultSkin, - PositionComponent? downSkin, - PositionComponent? hoverSkin, - PositionComponent? disabledSkin, - PositionComponent? defaultLabel, - PositionComponent? disabledLabel, - super.size, - super.position, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - }) { - this.defaultSkin = defaultSkin; - this.downSkin = downSkin; - this.hoverSkin = hoverSkin; - this.disabledSkin = disabledSkin; - this.defaultLabel = defaultLabel; - this.disabledLabel = disabledLabel; - size.addListener(_updateSizes); - } - +class AdvancedButtonComponent({ /// Callback for what should happen when the button is pressed. - void Function()? onPressed; + var void Function()? onPressed, /// Callback for what should happen when the button is released. - void Function()? onReleased; + var void Function()? onReleased, /// Callback for what should happen when the tap is cancelled, for example /// when the pointer is dragged outside of the button before it is released. - void Function()? onCancelled; + var void Function()? onCancelled, /// Callback when button state changes - void Function(ButtonState state)? onChangeState; + var void Function(ButtonState state)? onChangeState, + PositionComponent? defaultSkin, + PositionComponent? downSkin, + PositionComponent? hoverSkin, + PositionComponent? disabledSkin, + PositionComponent? defaultLabel, + PositionComponent? disabledLabel, + super.size, + super.position, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, +}) extends PositionComponent with HoverCallbacks, TapCallbacks { + this { + this.defaultSkin = defaultSkin; + this.downSkin = downSkin; + this.hoverSkin = hoverSkin; + this.disabledSkin = disabledSkin; + this.defaultLabel = defaultLabel; + this.disabledLabel = disabledLabel; + size.addListener(_updateSizes); + } @mustCallSuper @override @@ -265,7 +259,7 @@ class AdvancedButtonComponent extends PositionComponent } } -enum ButtonState { +enum ButtonState() { up, upAndSelected, down, @@ -275,8 +269,6 @@ enum ButtonState { disabled, disabledAndSelected; - const ButtonState(); - bool get isDefault { return this == ButtonState.up; } diff --git a/packages/flame/lib/src/components/input/button_component.dart b/packages/flame/lib/src/components/input/button_component.dart index 6c313054e3f..353a014ccbe 100644 --- a/packages/flame/lib/src/components/input/button_component.dart +++ b/packages/flame/lib/src/components/input/button_component.dart @@ -7,35 +7,30 @@ import 'package:meta/meta.dart'; /// /// Note: You have to set the [button] in [onLoad] if you are not passing it in /// through the constructor. -class ButtonComponent extends PositionComponent with TapCallbacks { - PositionComponent? button; - PositionComponent? buttonDown; +class ButtonComponent({ + var PositionComponent? button, + var PositionComponent? buttonDown, /// Callback for what should happen when the button is pressed. - void Function()? onPressed; + var void Function()? onPressed, /// Callback for what should happen when the button is released. - void Function()? onReleased; + var void Function()? onReleased, /// Callback for what should happen when the button is cancelled. - void Function()? onCancelled; - - ButtonComponent({ - this.button, - this.buttonDown, - this.onPressed, - this.onReleased, - this.onCancelled, - super.position, - Vector2? size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - }) : super( - size: size ?? button?.size, - ); + var void Function()? onCancelled, + super.position, + Vector2? size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, +}) extends PositionComponent with TapCallbacks { + this + : super( + size: size ?? button?.size, + ); @override @mustCallSuper diff --git a/packages/flame/lib/src/components/input/hud_button_component.dart b/packages/flame/lib/src/components/input/hud_button_component.dart index 1f5ed202ff2..76742984119 100644 --- a/packages/flame/lib/src/components/input/hud_button_component.dart +++ b/packages/flame/lib/src/components/input/hud_button_component.dart @@ -7,25 +7,25 @@ import 'package:flutter/rendering.dart' show EdgeInsets; /// /// Note: You have to set the [button] in [onLoad] if you are not passing it in /// through the constructor. -class HudButtonComponent extends ButtonComponent - with HasGameRef, ComponentViewportMargin { - HudButtonComponent({ - super.button, - super.buttonDown, - EdgeInsets? margin, - Function()? super.onPressed, - Function()? super.onReleased, - Function()? super.onCancelled, - super.position, - Vector2? size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - }) : super( - size: size ?? button?.size, - ) { +class HudButtonComponent({ + super.button, + super.buttonDown, + EdgeInsets? margin, + Function()? super.onPressed, + Function()? super.onReleased, + Function()? super.onCancelled, + super.position, + Vector2? size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, +}) extends ButtonComponent with HasGameRef, ComponentViewportMargin { + this + : super( + size: size ?? button?.size, + ) { this.margin = margin; } } diff --git a/packages/flame/lib/src/components/input/hud_margin_component.dart b/packages/flame/lib/src/components/input/hud_margin_component.dart index 8d2f328fc3e..815839e30d5 100644 --- a/packages/flame/lib/src/components/input/hud_margin_component.dart +++ b/packages/flame/lib/src/components/input/hud_margin_component.dart @@ -15,25 +15,24 @@ import 'package:meta/meta.dart'; /// If you set the position of the component instead of a margin when /// initializing the component, the margin to the edge of the screen from that /// position will be used. -class HudMarginComponent extends PositionComponent { - HudMarginComponent({ - this.margin, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }) : assert( - margin != null || position != null, - 'Either margin or position must be defined', - ); - +class HudMarginComponent({ /// Instead of setting a position of the [HudMarginComponent] a margin /// from the edges of the viewport can be used instead. - EdgeInsets? margin; + var EdgeInsets? margin, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { + this + : assert( + margin != null || position != null, + 'Either margin or position must be defined', + ); late ReadOnlySizeProvider? _sizeProvider; @@ -41,9 +40,9 @@ class HudMarginComponent extends PositionComponent { @mustCallSuper void onMount() { super.onMount(); - _sizeProvider = - ancestors().firstWhereOrNull((c) => c is ReadOnlySizeProvider) - as ReadOnlySizeProvider?; + _sizeProvider = ancestors().firstWhereOrNull( + (c) => c is ReadOnlySizeProvider, + ) as ReadOnlySizeProvider?; assert( _sizeProvider != null, 'The parent of a HudMarginComponent needs to provide a size, for example ' diff --git a/packages/flame/lib/src/components/input/joystick_component.dart b/packages/flame/lib/src/components/input/joystick_component.dart index 084dc76c81e..871c75cdcfa 100644 --- a/packages/flame/lib/src/components/input/joystick_component.dart +++ b/packages/flame/lib/src/components/input/joystick_component.dart @@ -4,7 +4,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:flutter/widgets.dart'; -enum JoystickDirection { +enum JoystickDirection() { up, upLeft, upRight, @@ -16,11 +16,19 @@ enum JoystickDirection { idle, } -class JoystickComponent extends PositionComponent +class JoystickComponent({ + final PositionComponent? knob, + final PositionComponent? background, + super.position, + EdgeInsets? margin, + double? size, + double? knobRadius, + Anchor super.anchor = Anchor.center, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasGameRef, ComponentViewportMargin, DragCallbacks { - late final PositionComponent? knob; - late final PositionComponent? background; - /// The percentage `[0.0, 1.0]` the knob is dragged from the center to the /// edge. double intensity = 0.0; @@ -43,29 +51,19 @@ class JoystickComponent extends PositionComponent /// The position where the knob rests. late Vector2 _baseKnobPosition; - JoystickComponent({ - this.knob, - this.background, - super.position, - EdgeInsets? margin, - double? size, - double? knobRadius, - Anchor super.anchor = Anchor.center, - super.children, - super.priority, - super.key, - }) : assert( - size != null || background != null, - 'Either size or background must be defined', - ), - assert( - (knob?.position.isZero() ?? true) && - (background?.position.isZero() ?? true), - 'Positions should not be set for the knob or the background', - ), - super( - size: background?.size ?? Vector2.all(size ?? 0), - ) { + this + : assert( + size != null || background != null, + 'Either size or background must be defined', + ), + assert( + (knob?.position.isZero() ?? true) && + (background?.position.isZero() ?? true), + 'Positions should not be set for the knob or the background', + ), + super( + size: background?.size ?? Vector2.all(size ?? 0), + ) { this.margin = margin; this.knobRadius = knobRadius ?? this.size.x / 2; } diff --git a/packages/flame/lib/src/components/input/keyboard_listener_component.dart b/packages/flame/lib/src/components/input/keyboard_listener_component.dart index 6187617f8a3..de2a35afa81 100644 --- a/packages/flame/lib/src/components/input/keyboard_listener_component.dart +++ b/packages/flame/lib/src/components/input/keyboard_listener_component.dart @@ -11,17 +11,11 @@ typedef KeyHandlerCallback = bool Function(Set); /// This component is based on [KeyboardHandler], which requires the [FlameGame] /// which is used to be mixed with [HasKeyboardHandlerComponents]. /// {@endtemplate} -class KeyboardListenerComponent extends Component with KeyboardHandler { - /// {@macro keyboard_listener_component} - KeyboardListenerComponent({ - this._keyUp = const {}, - this._keyDown = const {}, - super.key, - }); - - final Map _keyUp; - final Map _keyDown; - +class KeyboardListenerComponent({ + final Map _keyUp = const {}, + final Map _keyDown = const {}, + super.key, +}) extends Component with KeyboardHandler { @override bool onKeyEvent(KeyEvent event, Set keysPressed) { final isUp = event is KeyUpEvent; diff --git a/packages/flame/lib/src/components/input/sprite_button_component.dart b/packages/flame/lib/src/components/input/sprite_button_component.dart index 04c19fd043b..09b21464d30 100644 --- a/packages/flame/lib/src/components/input/sprite_button_component.dart +++ b/packages/flame/lib/src/components/input/sprite_button_component.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame/events.dart'; import 'package:meta/meta.dart'; -enum ButtonState { +enum ButtonState() { up, down, } @@ -16,30 +16,25 @@ enum ButtonState { /// /// Note: You have to set the [button] in [onLoad] if you are not passing it in /// through the constructor. -class SpriteButtonComponent extends SpriteGroupComponent - with TapCallbacks { - SpriteButtonComponent({ - Sprite? button, - this._buttonDown, - this.onPressed, - super.position, - Vector2? size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - }) : _button = button, - super( - current: ButtonState.up, - size: size ?? button?.originalSize, - ); +class SpriteButtonComponent({ + var Sprite? _button, + var Sprite? _buttonDown, /// Callback for what should happen when the button is pressed. - void Function()? onPressed; - - Sprite? _button; - Sprite? _buttonDown; + var void Function()? onPressed, + super.position, + Vector2? size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, +}) extends SpriteGroupComponent with TapCallbacks { + this + : super( + current: ButtonState.up, + size: size ?? _button?.originalSize, + ); Sprite get button => _button!; Sprite get buttonDown => _buttonDown ?? button; diff --git a/packages/flame/lib/src/components/input/toggle_button_component.dart b/packages/flame/lib/src/components/input/toggle_button_component.dart index 3eceaaeeb5c..7039a3b50a6 100644 --- a/packages/flame/lib/src/components/input/toggle_button_component.dart +++ b/packages/flame/lib/src/components/input/toggle_button_component.dart @@ -9,31 +9,33 @@ import 'package:flutter/foundation.dart'; /// Note: You have to set the [defaultSkin], [defaultSelectedSkin] /// and other skins that you want to use in [onLoad] if you are not passed in /// through the constructor. -class ToggleButtonComponent extends AdvancedButtonComponent { - ToggleButtonComponent({ - super.onPressed, - this.onSelectedChanged, - super.onChangeState, - super.defaultSkin, - super.downSkin, - super.hoverSkin, - super.disabledSkin, - PositionComponent? defaultSelectedSkin, - PositionComponent? downAndSelectedSkin, - PositionComponent? hoverAndSelectedSkin, - PositionComponent? disabledAndSelectedSkin, - super.defaultLabel, - super.disabledLabel, - PositionComponent? defaultSelectedLabel, - PositionComponent? disabledAndSelectedLabel, - super.size, - super.position, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - }) { +class ToggleButtonComponent({ + super.onPressed, + + /// Callback when button selected changed + var ValueChanged? onSelectedChanged, + super.onChangeState, + super.defaultSkin, + super.downSkin, + super.hoverSkin, + super.disabledSkin, + PositionComponent? defaultSelectedSkin, + PositionComponent? downAndSelectedSkin, + PositionComponent? hoverAndSelectedSkin, + PositionComponent? disabledAndSelectedSkin, + super.defaultLabel, + super.disabledLabel, + PositionComponent? defaultSelectedLabel, + PositionComponent? disabledAndSelectedLabel, + super.size, + super.position, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, +}) extends AdvancedButtonComponent { + this { this.defaultSelectedSkin = defaultSelectedSkin; this.downAndSelectedSkin = downAndSelectedSkin; this.hoverAndSelectedSkin = hoverAndSelectedSkin; @@ -42,9 +44,6 @@ class ToggleButtonComponent extends AdvancedButtonComponent { this.disabledAndSelectedLabel = disabledAndSelectedLabel; } - /// Callback when button selected changed - ValueChanged? onSelectedChanged; - @override @mustCallSuper void onMount() { diff --git a/packages/flame/lib/src/components/isometric_tile_map_component.dart b/packages/flame/lib/src/components/isometric_tile_map_component.dart index 60f7af48019..767827b9177 100644 --- a/packages/flame/lib/src/components/isometric_tile_map_component.dart +++ b/packages/flame/lib/src/components/isometric_tile_map_component.dart @@ -9,42 +9,37 @@ import 'package:flame/src/sprite_sheet.dart'; /// /// It can change the scale of each block by using the optional destTileSize /// property. -class IsometricTileMapComponent extends PositionComponent { +class IsometricTileMapComponent( /// This is the tileset that will be used to render this map. - SpriteSheet tileset; + var SpriteSheet tileset, /// The positions of each block will be placed respecting this matrix. - List> matrix; + var List> matrix, { /// Optionally provide a new tile size to render it scaled. - Vector2? destTileSize; + var Vector2? destTileSize, /// This is the vertical height of each block in the tile set. /// /// Note: this must be measured in the destination space. - double? tileHeight; - + var double? tileHeight, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { /// Where the tileset's image is stored. - Sprite _renderSprite; + Sprite _renderSprite = Sprite(tileset.image); /// Displacement applied so that the origin of the component /// matches the origin of the AABB. final Vector2 _offset = Vector2.zero(); - IsometricTileMapComponent( - this.tileset, - this.matrix, { - this.destTileSize, - this.tileHeight, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }) : _renderSprite = Sprite(tileset.image) { + this { _recomputeSizeAndOffset(); } diff --git a/packages/flame/lib/src/components/mixins/coordinate_transform.dart b/packages/flame/lib/src/components/mixins/coordinate_transform.dart index c93100c710f..9313f061219 100644 --- a/packages/flame/lib/src/components/mixins/coordinate_transform.dart +++ b/packages/flame/lib/src/components/mixins/coordinate_transform.dart @@ -17,7 +17,7 @@ import 'package:vector_math/vector_math.dart'; /// The two methods of this interface convert between the parent's coordinate /// space and the local coordinates. The methods may also return `null`, /// indicating that the given cannot be mapped to any local/parent point. -abstract class CoordinateTransform { +abstract class CoordinateTransform() { Vector2? parentToLocal(Vector2 point); Vector2? localToParent(Vector2 point); diff --git a/packages/flame/lib/src/components/mixins/has_auto_batched_children.dart b/packages/flame/lib/src/components/mixins/has_auto_batched_children.dart index e7d7548f1f0..b96de97ebdf 100644 --- a/packages/flame/lib/src/components/mixins/has_auto_batched_children.dart +++ b/packages/flame/lib/src/components/mixins/has_auto_batched_children.dart @@ -280,10 +280,8 @@ mixin HasAutoBatchedChildren on Component { /// /// Reused frame-to-frame: cleared and re-populated on each render pass via /// [flush]. -class _BatchAccumulator { - _BatchAccumulator(Image atlas) : batch = SpriteBatch(atlas); - - final SpriteBatch batch; +class _BatchAccumulator(Image atlas) { + final SpriteBatch batch = SpriteBatch(atlas); void accumulate(Rect source, RSTransform transform, Color color) { batch.addTransform(source: source, transform: transform, color: color); @@ -301,10 +299,4 @@ class _BatchAccumulator { } /// Internal struct for batching info extracted from a component. -class _BatchInfo { - _BatchInfo(this.image, this.sourceRect, this.color); - - final Image image; - final Rect sourceRect; - final Color color; -} +class _BatchInfo(final Image image, final Rect sourceRect, final Color color); diff --git a/packages/flame/lib/src/components/mixins/has_paint.dart b/packages/flame/lib/src/components/mixins/has_paint.dart index a33bd4c1fed..f4829b45a93 100644 --- a/packages/flame/lib/src/components/mixins/has_paint.dart +++ b/packages/flame/lib/src/components/mixins/has_paint.dart @@ -201,12 +201,10 @@ mixin HasPaint on Component void onChanged() {} } -class _ProxyOpacityProvider implements OpacityProvider { - _ProxyOpacityProvider(this.paintId, this.target); - - final T paintId; - final HasPaint target; - +class _ProxyOpacityProvider( + final T paintId, + final HasPaint target, +) implements OpacityProvider { @override double get opacity => target.getOpacity(paintId: paintId); @@ -214,12 +212,12 @@ class _ProxyOpacityProvider implements OpacityProvider { set opacity(double value) => target.setOpacity(value, paintId: paintId); } -class _MultiPaintOpacityProvider implements OpacityProvider { - _MultiPaintOpacityProvider( - this.paintIds, - this.target, { - required this.includeLayers, - }) { +class _MultiPaintOpacityProvider( + final List paintIds, + final HasPaint target, { + required final bool includeLayers, +}) implements OpacityProvider { + this { final maxOpacity = opacity; _opacityRatios = [ @@ -233,9 +231,6 @@ class _MultiPaintOpacityProvider implements OpacityProvider { .toList(growable: false); } - final List paintIds; - final HasPaint target; - final bool includeLayers; late final List _opacityRatios; late final List? _layerOpacityRatios; diff --git a/packages/flame/lib/src/components/mixins/has_visibility.dart b/packages/flame/lib/src/components/mixins/has_visibility.dart index 2ffd25617a4..954e6520b93 100644 --- a/packages/flame/lib/src/components/mixins/has_visibility.dart +++ b/packages/flame/lib/src/components/mixins/has_visibility.dart @@ -15,7 +15,7 @@ import 'package:material_ui/material_ui.dart'; /// If you are adding a custom implementation of the /// [renderTree] method, make sure to wrap your render code /// in a conditional. i.e.: -/// ``` +/// ```dart /// if (isVisible) { /// // Custom render code here /// } diff --git a/packages/flame/lib/src/components/mixins/has_world_ref.dart b/packages/flame/lib/src/components/mixins/has_world_ref.dart index b8084a0590c..ae8b5db4f40 100644 --- a/packages/flame/lib/src/components/mixins/has_world_ref.dart +++ b/packages/flame/lib/src/components/mixins/has_world_ref.dart @@ -22,9 +22,8 @@ mixin HasWorldRef on Component { T? findWorld() { return ancestors( - includeSelf: true, - ).firstWhereOrNull((ancestor) => ancestor is T) - as T?; + includeSelf: true, + ).firstWhereOrNull((ancestor) => ancestor is T) as T?; } T _findWorldAndCheck() { diff --git a/packages/flame/lib/src/components/mixins/snapshot.dart b/packages/flame/lib/src/components/mixins/snapshot.dart index d063c760d9c..825fb261292 100644 --- a/packages/flame/lib/src/components/mixins/snapshot.dart +++ b/packages/flame/lib/src/components/mixins/snapshot.dart @@ -23,7 +23,7 @@ mixin Snapshot on PositionComponent { set renderSnapshot(bool value) { if (_renderSnapshot != value) { _renderSnapshot = value; - if (_renderSnapshot == true) { + if (_renderSnapshot) { _picture = null; } } diff --git a/packages/flame/lib/src/components/nine_tile_box_component.dart b/packages/flame/lib/src/components/nine_tile_box_component.dart index 0e0d18ed7e0..50eca9df82f 100644 --- a/packages/flame/lib/src/components/nine_tile_box_component.dart +++ b/packages/flame/lib/src/components/nine_tile_box_component.dart @@ -6,26 +6,23 @@ import 'package:meta/meta.dart'; export '../nine_tile_box.dart'; /// This class is a thin wrapper on top of [NineTileBox] as a component. -class NineTileBoxComponent extends PositionComponent with HasPaint { - NineTileBox? nineTileBox; - - /// Takes the [NineTileBox] instance to render a box that can grow and shrink - /// seamlessly. - /// - /// It uses the x, y, width and height coordinates from the - /// [PositionComponent] to render. - NineTileBoxComponent({ - this.nineTileBox, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }); - +/// +/// Takes the [NineTileBox] instance to render a box that can grow and shrink +/// seamlessly. +/// +/// It uses the x, y, width and height coordinates from the +/// [PositionComponent] to render. +class NineTileBoxComponent({ + var NineTileBox? nineTileBox, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasPaint { @override @mustCallSuper void onMount() { diff --git a/packages/flame/lib/src/components/parallax_component.dart b/packages/flame/lib/src/components/parallax_component.dart index 0475683a275..c176edb78bf 100644 --- a/packages/flame/lib/src/components/parallax_component.dart +++ b/packages/flame/lib/src/components/parallax_component.dart @@ -56,11 +56,18 @@ extension ParallaxComponentExtension on FlameGame { /// Most of the time you want to add the [ParallaxComponent] as a child to the /// viewport: `game.camera.viewport.add(parallaxComponent);`, since you want it /// to be static to the rest of the game. -class ParallaxComponent extends PositionComponent - with HasGameRef { - bool isFullscreen = true; - Parallax? _parallax; - +class ParallaxComponent({ + var Parallax? _parallax, + super.position, + Vector2? size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasGameRef { + bool isFullscreen = size == null && !(_parallax?.isSized ?? false); Parallax? get parallax => _parallax; set parallax(Parallax? p) { _parallax = p; @@ -68,21 +75,10 @@ class ParallaxComponent extends PositionComponent } /// Creates a component with an empty parallax which can be set later. - ParallaxComponent({ - Parallax? parallax, - super.position, - Vector2? size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }) : _parallax = parallax, - isFullscreen = size == null && !(parallax?.isSized ?? false), - super( - size: size ?? ((parallax?.isSized ?? false) ? parallax?.size : null), - ); + this + : super( + size: size ?? ((_parallax?.isSized ?? false) ? _parallax?.size : null), + ); @mustCallSuper @override diff --git a/packages/flame/lib/src/components/position_component.dart b/packages/flame/lib/src/components/position_component.dart index 4eb3c2fa08c..ddf215a7e4b 100644 --- a/packages/flame/lib/src/components/position_component.dart +++ b/packages/flame/lib/src/components/position_component.dart @@ -62,7 +62,25 @@ import 'package:meta/meta.dart'; /// the approximate bounding rectangle of the rendered picture. If you /// do not specify the size of a PositionComponent, then it will be /// equal to zero and the component won't be able to respond to taps. -class PositionComponent extends Component +class PositionComponent({ + Vector2? position, + Vector2? size, + Vector2? scale, + double? angle, + + /// The angle where this component is looking at when it is in + /// the default state, i.e. when [angle] is equal to zero. + /// For example, a nativeAngle of + /// 0 implies up/north direction + /// pi/2 implies right/east direction + /// pi implies down/south direction + /// -pi/2 implies left/west direction + var double nativeAngle = 0, + Anchor? anchor, + super.children, + super.priority, + super.key, +}) extends Component implements AnchorProvider, AngleProvider, @@ -70,19 +88,7 @@ class PositionComponent extends Component ScaleProvider, SizeProvider, CoordinateTransform { - PositionComponent({ - Vector2? position, - Vector2? size, - Vector2? scale, - double? angle, - this.nativeAngle = 0, - Anchor? anchor, - super.children, - super.priority, - super.key, - }) : transform = Transform2D(), - _anchor = anchor ?? Anchor.topLeft, - _size = NotifyingVector2.copy(size ?? Vector2.zero()) { + this : transform = Transform2D() { decorator = Transform2DDecorator(transform); if (position != null) { transform.position = position; @@ -98,17 +104,8 @@ class PositionComponent extends Component } final Transform2D transform; - final NotifyingVector2 _size; - Anchor _anchor; - - /// The angle where this component is looking at when it is in - /// the default state, i.e. when [angle] is equal to zero. - /// For example, a nativeAngle of - /// 0 implies up/north direction - /// pi/2 implies right/east direction - /// pi implies down/south direction - /// -pi/2 implies left/west direction - double nativeAngle; + final NotifyingVector2 _size = NotifyingVector2.copy(size ?? Vector2.zero()); + Anchor _anchor = anchor ?? Anchor.topLeft; /// The decorator is used to apply visual effects to a component. /// diff --git a/packages/flame/lib/src/components/raster_sprite_component.dart b/packages/flame/lib/src/components/raster_sprite_component.dart index cce22d9842a..3afd069933c 100644 --- a/packages/flame/lib/src/components/raster_sprite_component.dart +++ b/packages/flame/lib/src/components/raster_sprite_component.dart @@ -12,25 +12,25 @@ export '../sprite.dart'; /// will rasterize its sprite when loaded and will automatically /// manage the disposal of the rasterized image when removed. /// {@endtemplate} -class RasterSpriteComponent extends SpriteComponent { - /// {@macro raster_sprite_component} - RasterSpriteComponent({ - required this.baseSprite, - this.images, - super.autoResize, - super.paint, - super.position, - super.size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.bleed, - super.key, - }); +class RasterSpriteComponent({ + /// The base sprite to be rasterized. + required final Sprite baseSprite, + /// The [Images] cache used to store the rasterized image. + final Images? images, + super.autoResize, + super.paint, + super.position, + super.size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.bleed, + super.key, +}) extends SpriteComponent { RasterSpriteComponent.fromImage( Image image, { Vector2? srcPosition, @@ -67,12 +67,6 @@ class RasterSpriteComponent extends SpriteComponent { key: key, ); - /// The base sprite to be rasterized. - final Sprite baseSprite; - - /// The [Images] cache used to store the rasterized image. - final Images? images; - @mustCallSuper @override FutureOr onLoad() async { diff --git a/packages/flame/lib/src/components/router/route.dart b/packages/flame/lib/src/components/router/route.dart index 234341b3e82..aed3f69c054 100644 --- a/packages/flame/lib/src/components/router/route.dart +++ b/packages/flame/lib/src/components/router/route.dart @@ -20,28 +20,31 @@ import 'package:meta/meta.dart'; /// any potentially costly initialization operations. /// /// Routes are managed by the [RouterComponent] component. -class Route extends PositionComponent - with ParentIsA, CustomTraversal, HasTimeScale { - Route( - Component Function()? builder, { - this._loadingBuilder, - this.transparent = false, - this.maintainState = true, - }) : _builder = builder, - _renderEffect = Decorator(); +class Route( + /// The function that will be invoked in order to build the page component + /// when this route first becomes active. This function may also be `null`, + /// in which case the user must override the [build] method. + final Component Function()? _builder, { + + /// The function that will build the loading page component, which is shown + /// when this route first becomes active, but hasn't fully loaded yet. + final Component Function()? _loadingBuilder, /// If true, then the route below this one will continue to be rendered when /// this route becomes active. If false, then this route is assumed to /// completely obscure any route that would be underneath, and therefore the /// route underneath doesn't need to be rendered. - final bool transparent; + final bool transparent = false, /// If false, the route will not maintain the state of this route's page /// component. By default, once a route becomes active, the component /// built by the build routine is maintained by the route after the route /// is popped off the stack. Setting [maintainState] to false will drop the /// page component when the route is popped off the stack. - final bool maintainState; + final bool maintainState = true, +}) extends PositionComponent + with ParentIsA, CustomTraversal, HasTimeScale { + this : _renderEffect = Decorator(); /// The name of the route (set by the [RouterComponent]). String? get name => _name; @@ -49,15 +52,6 @@ class Route extends PositionComponent @internal set name(String? value) => _name = value; - /// The function that will be invoked in order to build the page component - /// when this route first becomes active. This function may also be `null`, - /// in which case the user must override the [build] method. - final Component Function()? _builder; - - /// The function that will build the loading page component, which is shown - /// when this route first becomes active, but hasn't fully loaded yet. - final Component Function()? _loadingBuilder; - /// This method is invoked when the route is pushed on top of the /// [RouterComponent]'s stack. /// diff --git a/packages/flame/lib/src/components/router/router_component.dart b/packages/flame/lib/src/components/router/router_component.dart index 6aecb03d01e..c6891857e68 100644 --- a/packages/flame/lib/src/components/router/router_component.dart +++ b/packages/flame/lib/src/components/router/router_component.dart @@ -27,21 +27,22 @@ import 'package:meta/meta.dart'; /// rendering, and also stops pointer events. In addition, routes are able to /// stop or slow down time for the pages that they control, or to apply visual /// effects (via decorators) to those pages. -class RouterComponent extends Component { - RouterComponent({ - required this.initialRoute, - required Map routes, - Map? routeFactories, - this.onUnknownRoute, - super.key, - super.priority = 0x7fffffff, - }) : _routes = routes, - _routeFactories = routeFactories ?? {} { - routes.forEach((name, route) => route.name = name); - } - +class RouterComponent({ /// Route that will be placed on the stack in the beginning. - final String initialRoute; + required final String initialRoute, + required final Map _routes, + Map? routeFactories, + + /// Function that will be called to resolve any route names that couldn't be + /// resolved via [_routes] or [_routeFactories]. Unlike with routeFactories, + /// the route returned by this function will not be cached. + final RouteFactory? onUnknownRoute, + super.key, + super.priority = 0x7fffffff, +}) extends Component { + this { + _routes.forEach((name, route) => route.name = name); + } /// The stack of all currently active routes. This stack must not be empty /// (it will be populated with the [initialRoute] in the beginning). @@ -58,7 +59,6 @@ class RouterComponent extends Component { /// unique name. This map is initialized in the constructor; in addition, any /// routes produced by the [_routeFactories] will also be cached here. Map get routes => _routes; - final Map _routes; /// Set of functions that are able to resolve routes dynamically. /// @@ -66,12 +66,7 @@ class RouterComponent extends Component { /// "prefix/arg". For such a name, we will call the factory "prefix" with the /// argument "arg". The produced route will be cached in the main [_routes] /// map, and then built and mounted normally. - final Map _routeFactories; - - /// Function that will be called to resolve any route names that couldn't be - /// resolved via [_routes] or [_routeFactories]. Unlike with routeFactories, - /// the route returned by this function will not be cached. - final RouteFactory? onUnknownRoute; + final Map _routeFactories = routeFactories ?? {}; /// Returns the route that is currently at the top of the stack. Route get currentRoute => _routeStack.last; diff --git a/packages/flame/lib/src/components/router/value_route.dart b/packages/flame/lib/src/components/router/value_route.dart index 43fc4c40d0d..30ce1bfb753 100644 --- a/packages/flame/lib/src/components/router/value_route.dart +++ b/packages/flame/lib/src/components/router/value_route.dart @@ -16,13 +16,11 @@ import 'package:meta/meta.dart'; /// /// If the route is popped without invoking [completeWith], then the /// [_defaultValue] will be used. -abstract class ValueRoute extends Route { - ValueRoute({required T value, super.transparent}) - : _defaultValue = value, - _completer = Completer(), - super(null); +abstract class ValueRoute({required T value, super.transparent}) + extends Route { + this : _completer = Completer(), super(null); - final T _defaultValue; + final T _defaultValue = value; final Completer _completer; /// Future that will complete when this route is popped from the stack. diff --git a/packages/flame/lib/src/components/router/world_route.dart b/packages/flame/lib/src/components/router/world_route.dart index 6ac7ddf772c..cc00328c121 100644 --- a/packages/flame/lib/src/components/router/world_route.dart +++ b/packages/flame/lib/src/components/router/world_route.dart @@ -5,7 +5,11 @@ import 'package:meta/meta.dart'; /// [WorldRoute] is a class that allows setting the world that a camera is /// looking at. -class WorldRoute extends Route { +class WorldRoute( + final World Function() builder, { + final CameraComponent? camera, + super.maintainState, +}) extends Route { /// A world route that uses the specified [builder]. This builder will be /// registered with the Game's map of world builders when this route is /// first activated. @@ -13,10 +17,8 @@ class WorldRoute extends Route { /// The [camera] parameter is optional and can be used to set the camera /// that will be used to render the world, if not provided the default camera /// will be used. - WorldRoute(this.builder, {this.camera, super.maintainState}) : super(null); + this : super(null); - final World Function() builder; - final CameraComponent? camera; late World? _previousWorld; World? world; diff --git a/packages/flame/lib/src/components/scroll_text_box_component.dart b/packages/flame/lib/src/components/scroll_text_box_component.dart index bb2005a5f73..40f05f02a4b 100644 --- a/packages/flame/lib/src/components/scroll_text_box_component.dart +++ b/packages/flame/lib/src/components/scroll_text_box_component.dart @@ -14,7 +14,22 @@ import 'package:flutter/painting.dart'; /// /// This component uses [TextBoxComponent] to provide scrollable text /// capabilities. -class ScrollTextBoxComponent extends PositionComponent { +class ScrollTextBoxComponent({ + required Vector2 size, + String? text, + T? textRenderer, + TextBoxConfig? boxConfig, + Anchor align = Anchor.topLeft, + double pixelRatio = 1.0, + super.position, + super.scale, + double angle = 0.0, + super.anchor = Anchor.topLeft, + super.priority, + super.key, + List? children, + void Function()? onComplete, +}) extends PositionComponent { late final _ScrollTextBoxComponent _scrollTextBoxComponent; late final ValueNotifier newLineNotifier; @@ -28,26 +43,12 @@ class ScrollTextBoxComponent extends PositionComponent { /// - Other parameters include alignment, pixel ratio, and positioning /// settings. /// An assertion ensures that the [size] has positive dimensions. - ScrollTextBoxComponent({ - required Vector2 size, - String? text, - T? textRenderer, - TextBoxConfig? boxConfig, - Anchor align = Anchor.topLeft, - double pixelRatio = 1.0, - super.position, - super.scale, - double angle = 0.0, - super.anchor = Anchor.topLeft, - super.priority, - super.key, - List? children, - void Function()? onComplete, - }) : assert( - size.x > 0 && size.y > 0, - 'size must have positive dimensions: $size', - ), - super(size: size) { + this + : assert( + size.x > 0 && size.y > 0, + 'size must have positive dimensions: $size', + ), + super(size: size) { final marginTop = boxConfig?.margins.top ?? 0; final marginBottom = boxConfig?.margins.bottom ?? 0; final innerMargins = EdgeInsets.fromLTRB(0, marginTop, 0, marginBottom); @@ -104,8 +105,17 @@ class ScrollTextBoxComponent extends PositionComponent { /// Extends [TextBoxComponent] and incorporates drag callbacks for text /// scrolling. It manages the rendering and user interaction for the text within /// the box. -class _ScrollTextBoxComponent extends TextBoxComponent - with DragCallbacks { +class _ScrollTextBoxComponent({ + String? text, + T? textRenderer, + TextBoxConfig? boxConfig, + Anchor super.align = Anchor.topLeft, + double super.pixelRatio = 1.0, + super.position, + super.scale, + double super.angle = 0.0, + super.onComplete, +}) extends TextBoxComponent with DragCallbacks { double scrollBoundsY = 0.0; late final ClipComponent clipComponent; @@ -114,21 +124,12 @@ class _ScrollTextBoxComponent extends TextBoxComponent bool _isOnCompleteExecuted = false; - _ScrollTextBoxComponent({ - String? text, - T? textRenderer, - TextBoxConfig? boxConfig, - Anchor super.align = Anchor.topLeft, - double super.pixelRatio = 1.0, - super.position, - super.scale, - double super.angle = 0.0, - super.onComplete, - }) : super( - text: text ?? '', - textRenderer: textRenderer ?? TextPaint(), - boxConfig: boxConfig ?? const TextBoxConfig(), - ); + this + : super( + text: text ?? '', + textRenderer: textRenderer ?? TextPaint(), + boxConfig: boxConfig ?? const TextBoxConfig(), + ); @override Future onLoad() { diff --git a/packages/flame/lib/src/components/sprite_animation_component.dart b/packages/flame/lib/src/components/sprite_animation_component.dart index 7305cc1d76f..aff95c33d22 100644 --- a/packages/flame/lib/src/components/sprite_animation_component.dart +++ b/packages/flame/lib/src/components/sprite_animation_component.dart @@ -6,52 +6,48 @@ import 'package:meta/meta.dart'; export '../sprite_animation.dart'; -class SpriteAnimationComponent extends PositionComponent with HasPaint { - /// The animation ticker used for updating [animation]. - SpriteAnimationTicker? _animationTicker; - - /// Returns the animation ticker for current [animation]. - SpriteAnimationTicker? get animationTicker => _animationTicker; +class SpriteAnimationComponent({ + SpriteAnimation? animation, + bool? autoResize, /// If the component should be removed once the animation has finished. /// Needs the animation to have `loop = false` to ever remove the component, /// since it will never finish otherwise. - bool removeOnFinish; + var bool removeOnFinish = false, /// Whether the animation is paused or playing. - bool playing; + var bool playing = true, /// Whether to reset the animation when the component is removed from the /// component tree. - bool resetOnRemove; + var bool resetOnRemove = false, + Paint? paint, + super.position, + super.size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasPaint { + /// The animation ticker used for updating [animation]. + SpriteAnimationTicker? _animationTicker = animation?.createTicker(); + + /// Returns the animation ticker for current [animation]. + SpriteAnimationTicker? get animationTicker => _animationTicker; /// When set to true, the component is auto-resized to match the /// size of current animation sprite. - bool _autoResize; + bool _autoResize = autoResize ?? size == null; /// Creates a component with an empty animation which can be set later - SpriteAnimationComponent({ - SpriteAnimation? animation, - bool? autoResize, - this.removeOnFinish = false, - this.playing = true, - this.resetOnRemove = false, - Paint? paint, - super.position, - super.size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _autoResize = autoResize ?? size == null, - _animationTicker = animation?.createTicker() { + this + : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ) { if (paint != null) { this.paint = paint; } diff --git a/packages/flame/lib/src/components/sprite_animation_group_component.dart b/packages/flame/lib/src/components/sprite_animation_group_component.dart index 4ad623715f9..b013b6e2cd6 100644 --- a/packages/flame/lib/src/components/sprite_animation_group_component.dart +++ b/packages/flame/lib/src/components/sprite_animation_group_component.dart @@ -6,66 +6,59 @@ import 'package:flutter/foundation.dart'; export '../sprite_animation.dart'; -class SpriteAnimationGroupComponent extends PositionComponent with HasPaint { +class SpriteAnimationGroupComponent({ + /// Map with the available states for this animation group + var Map? _animations, + /// Key with the current playing animation - T? _current; + var T? _current, + bool? autoResize, + + /// Whether the animation is paused or playing. + var bool playing = true, + + /// Map with the mapping each state to the flag removeOnFinish + final Map removeOnFinish = const {}, + /// Whether the current animation's ticker should reset to the beginning + /// when it becomes current. + var bool autoResetTicker = true, + Paint? paint, + super.position, + super.size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasPaint { ValueNotifier? _currentAnimationNotifier; /// A [ValueNotifier] that notifies when the current animation changes. ValueNotifier get currentAnimationNotifier => _currentAnimationNotifier ??= ValueNotifier(_current); - /// Map with the mapping each state to the flag removeOnFinish - final Map removeOnFinish; - - /// Map with the available states for this animation group - Map? _animations; - /// Map containing animation tickers for each animation state. - Map? _animationTickers; - - /// Whether the animation is paused or playing. - bool playing; + Map? _animationTickers = _animations != null + ? Map.fromEntries( + _animations.entries + .map((e) => MapEntry(e.key, e.value.createTicker())) + .toList(), + ) + : null; /// When set to true, the component is auto-resized to match the /// size of current animation sprite. - bool _autoResize; - - /// Whether the current animation's ticker should reset to the beginning - /// when it becomes current. - bool autoResetTicker; + bool _autoResize = autoResize ?? size == null; /// Creates a component with an empty animation which can be set later - SpriteAnimationGroupComponent({ - this._animations, - this._current, - bool? autoResize, - this.playing = true, - this.removeOnFinish = const {}, - this.autoResetTicker = true, - Paint? paint, - super.position, - super.size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _autoResize = autoResize ?? size == null, - _animationTickers = _animations != null - ? Map.fromEntries( - _animations.entries - .map((e) => MapEntry(e.key, e.value.createTicker())) - .toList(), - ) - : null { + this + : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ) { if (paint != null) { this.paint = paint; } diff --git a/packages/flame/lib/src/components/sprite_batch_component.dart b/packages/flame/lib/src/components/sprite_batch_component.dart index d994f32e5fb..ca5784a9997 100644 --- a/packages/flame/lib/src/components/sprite_batch_component.dart +++ b/packages/flame/lib/src/components/sprite_batch_component.dart @@ -4,23 +4,16 @@ import 'package:flame/src/components/core/component.dart'; import 'package:flame/src/sprite_batch.dart'; import 'package:meta/meta.dart'; -class SpriteBatchComponent extends Component { - SpriteBatch? spriteBatch; - BlendMode? blendMode; - Rect? cullRect; - Paint? paint; - - /// Creates a component with an empty sprite batch which can be set later - SpriteBatchComponent({ - this.spriteBatch, - this.blendMode, - this.cullRect, - this.paint, - super.key, - super.children, - super.priority, - }); - +/// A component that renders a [SpriteBatch], which can also be set later. +class SpriteBatchComponent({ + var SpriteBatch? spriteBatch, + var BlendMode? blendMode, + var Rect? cullRect, + var Paint? paint, + super.key, + super.children, + super.priority, +}) extends Component { @override @mustCallSuper void onMount() { diff --git a/packages/flame/lib/src/components/sprite_component.dart b/packages/flame/lib/src/components/sprite_component.dart index fd52f264aa6..273d2552417 100644 --- a/packages/flame/lib/src/components/sprite_component.dart +++ b/packages/flame/lib/src/components/sprite_component.dart @@ -10,36 +10,33 @@ export '../sprite.dart'; /// angle. /// /// This a commonly used subclass of [Component]. -class SpriteComponent extends PositionComponent with HasPaint { +class SpriteComponent({ + /// The [sprite] to be rendered by this component. + var Sprite? _sprite, + bool? autoResize, + Paint? paint, + super.position, + Vector2? size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + var double? bleed, + super.key, +}) extends PositionComponent with HasPaint { /// When set to true, the component is auto-resized to match the /// size of underlying sprite. - bool _autoResize; - - /// The [sprite] to be rendered by this component. - Sprite? _sprite; + bool _autoResize = autoResize ?? size == null; /// Creates a component with an empty sprite which can be set later - SpriteComponent({ - Sprite? sprite, - bool? autoResize, - Paint? paint, - super.position, - Vector2? size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - this.bleed, - super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _autoResize = autoResize ?? size == null, - _sprite = sprite, - super(size: size ?? sprite?.srcSize) { + this + : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ), + super(size: size ?? _sprite?.srcSize) { if (paint != null) { this.paint = paint; } @@ -109,8 +106,6 @@ class SpriteComponent extends PositionComponent with HasPaint { _resizeToSprite(); } - double? bleed; - @override @mustCallSuper void onMount() { diff --git a/packages/flame/lib/src/components/sprite_group_component.dart b/packages/flame/lib/src/components/sprite_group_component.dart index 76c25ddfd2d..99234776670 100644 --- a/packages/flame/lib/src/components/sprite_group_component.dart +++ b/packages/flame/lib/src/components/sprite_group_component.dart @@ -7,46 +7,41 @@ export '../sprite_animation.dart'; /// A [PositionComponent] that can have multiple [Sprite]s and render /// the one mapped with the [current] key. -class SpriteGroupComponent extends PositionComponent with HasPaint { - /// Key for the current sprite. - T? _current; +class SpriteGroupComponent({ + /// Map with the available states for this sprite group. + var Map? _sprites, + /// Key for the current sprite. + var T? _current, + bool? autoResize, + Paint? paint, + super.position, + Vector2? size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasPaint { ValueNotifier? _currentSpriteNotifier; /// A [ValueNotifier] that notifies when the current sprite changes. ValueNotifier get currentSpriteNotifier => _currentSpriteNotifier ??= ValueNotifier(_current); - /// Map with the available states for this sprite group. - Map? _sprites; - /// When set to true, the component is auto-resized to match the /// size of current sprite. - bool _autoResize; + bool _autoResize = autoResize ?? size == null; /// Creates a component with an empty animation which can be set later. - SpriteGroupComponent({ - Map? sprites, - T? current, - bool? autoResize, - Paint? paint, - super.position, - Vector2? size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _current = current, - _sprites = sprites, - _autoResize = autoResize ?? size == null, - super(size: size ?? sprites?[current]?.srcSize) { + this + : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ), + super(size: size ?? _sprites?[_current]?.srcSize) { if (paint != null) { this.paint = paint; } diff --git a/packages/flame/lib/src/components/text_box_component.dart b/packages/flame/lib/src/components/text_box_component.dart index 2fca14f8afe..0320f493556 100644 --- a/packages/flame/lib/src/components/text_box_component.dart +++ b/packages/flame/lib/src/components/text_box_component.dart @@ -14,37 +14,29 @@ import 'package:meta/meta.dart'; /// A set of configurations for the [TextBoxComponent] itself, as opposed to /// the [TextRenderer], which contains the configuration for how to render the /// text only (font size, color, family, etc). -class TextBoxConfig { +class const TextBoxConfig({ /// Max width this paragraph can take. Lines will be broken trying to respect /// word boundaries in as many lines as necessary. - final double maxWidth; + final double maxWidth = 200.0, /// Margins of the text box with respect to the [PositionComponent.size]. - final EdgeInsets margins; + final EdgeInsets margins = const EdgeInsets.all(8.0), /// Defaults to 0. If not zero, the characters will appear one-by-one giving /// a typing effect to the text box, and this will be the delay in seconds /// between each character. - final double timePerChar; + final double timePerChar = 0.0, /// Defaults to null. If not null, this component will disappear after this /// many seconds after being fully typed out. - final double? dismissDelay; + final double? dismissDelay, /// Only relevant if [timePerChar] is set. If true, the box will start with /// the size to fit the first character and grow as more lines are typed. /// If false, the box will start with the full necessary size from the /// beginning (both width and height). - final bool growingBox; - - const TextBoxConfig({ - this.maxWidth = 200.0, - this.margins = const EdgeInsets.all(8.0), - this.timePerChar = 0.0, - this.dismissDelay, - this.growingBox = false, - }); - + final bool growingBox = false, +}) { TextBoxConfig copyWith({ double? maxWidth, EdgeInsets? margins, @@ -62,10 +54,27 @@ class TextBoxConfig { } } -class TextBoxComponent extends TextComponent { +class TextBoxComponent({ + super.text, + T? super.textRenderer, + TextBoxConfig? boxConfig, + Anchor? align, + double? pixelRatio, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + + /// Callback function to be executed after all text is displayed. + var void Function()? onComplete, + super.key, +}) extends TextComponent { static final Paint _imagePaint = BasicPalette.white.paint() ..filterQuality = FilterQuality.medium; - TextBoxConfig _boxConfig; + TextBoxConfig _boxConfig = boxConfig ?? const TextBoxConfig(); TextBoxConfig get boxConfig => _boxConfig; @@ -80,7 +89,8 @@ class TextBoxComponent extends TextComponent { redraw(); } - final double pixelRatio; + final double pixelRatio = + pixelRatio ?? PlatformDispatcher.instance.views.first.devicePixelRatio; @visibleForTesting final List lines = []; @@ -105,33 +115,8 @@ class TextBoxComponent extends TextComponent { double _currentLinePosition = 0.0; bool _isOnCompleteExecuted = false; - /// Callback function to be executed after all text is displayed. - void Function()? onComplete; - double get lineHeight => _lineHeight; - TextBoxComponent({ - super.text, - T? super.textRenderer, - TextBoxConfig? boxConfig, - Anchor? align, - double? pixelRatio, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - this.onComplete, - super.key, - }) : _boxConfig = boxConfig ?? const TextBoxConfig(), - _fixedSize = size != null, - align = align ?? Anchor.topLeft, - pixelRatio = - pixelRatio ?? - PlatformDispatcher.instance.views.first.devicePixelRatio; - /// Alignment of the text within its bounding box. /// /// This property combines both the horizontal and vertical alignment. For @@ -144,14 +129,14 @@ class TextBoxComponent extends TextComponent { /// its every line will have 10% of whitespace on the left, and 90% on the /// right. You can use an `AnchorEffect` to make the text gradually transition /// between different alignment values. - Anchor align; + Anchor align = align ?? Anchor.topLeft; /// If true, the size of the component will remain fixed. If false, the size /// will expand or shrink to the fit the text. /// /// This property is set to true if the user has explicitly specified [size] /// in the constructor. - final bool _fixedSize; + final bool _fixedSize = size != null; @override set text(String value) { diff --git a/packages/flame/lib/src/components/text_component.dart b/packages/flame/lib/src/components/text_component.dart index dcb46eeacab..3850ecd39f1 100644 --- a/packages/flame/lib/src/components/text_component.dart +++ b/packages/flame/lib/src/components/text_component.dart @@ -5,26 +5,24 @@ import 'package:flame/text.dart'; import 'package:flutter/painting.dart'; import 'package:meta/meta.dart'; -class TextComponent extends PositionComponent - with HasPaint { - TextComponent({ - String? text, - T? textRenderer, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }) : _text = text ?? '', - _textRenderer = textRenderer ?? TextRendererFactory.createDefault() { +class TextComponent({ + String? text, + T? textRenderer, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasPaint { + this { updateBounds(); } String get text => _text; - String _text; + String _text = text ?? ''; set text(String text) { if (_text != text) { _text = text; @@ -33,7 +31,7 @@ class TextComponent extends PositionComponent } T get textRenderer => _textRenderer; - T _textRenderer; + T _textRenderer = textRenderer ?? TextRendererFactory.createDefault(); set textRenderer(T textRenderer) { _textRenderer = textRenderer; updateBounds(); diff --git a/packages/flame/lib/src/components/text_element_component.dart b/packages/flame/lib/src/components/text_element_component.dart index c1e385513fc..29eaaf11862 100644 --- a/packages/flame/lib/src/components/text_element_component.dart +++ b/packages/flame/lib/src/components/text_element_component.dart @@ -2,23 +2,18 @@ import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:flame/text.dart'; -class TextElementComponent extends PositionComponent { - final Vector2? documentSize; - TextElement element; - - TextElementComponent({ - required this.element, - this.documentSize, - super.size, - super.position, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }); - +class TextElementComponent({ + required var TextElement element, + final Vector2? documentSize, + super.size, + super.position, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { factory TextElementComponent.fromDocument({ required DocumentRoot document, DocumentStyle? style, diff --git a/packages/flame/lib/src/components/timer_component.dart b/packages/flame/lib/src/components/timer_component.dart index 07894f887b9..e4a23bc56a8 100644 --- a/packages/flame/lib/src/components/timer_component.dart +++ b/packages/flame/lib/src/components/timer_component.dart @@ -6,10 +6,17 @@ import 'package:meta/meta.dart'; /// A component that uses a [Timer] instance which you can react to when it has /// finished. -class TimerComponent extends Component { +class TimerComponent({ + required double period, + bool repeat = false, + bool autoStart = true, + final bool removeOnFinish = false, + VoidCallback? onTick, + final bool tickWhenLoaded = false, + int? tickCount, + super.key, +}) extends Component { late final Timer timer; - final bool removeOnFinish; - final bool tickWhenLoaded; /// Creates a [TimerComponent] /// @@ -23,16 +30,7 @@ class TimerComponent extends Component { /// [tickCount] The number of time the timer will tick before stopping. /// This is is only used when [repeat] is true. If null, /// the timer will run indefinitely. - TimerComponent({ - required double period, - bool repeat = false, - bool autoStart = true, - this.removeOnFinish = false, - VoidCallback? onTick, - this.tickWhenLoaded = false, - int? tickCount, - super.key, - }) { + this { timer = Timer( period: period, repeat: repeat, diff --git a/packages/flame/lib/src/components/widget_component.dart b/packages/flame/lib/src/components/widget_component.dart index f6f988f418e..dc5cdfd5588 100644 --- a/packages/flame/lib/src/components/widget_component.dart +++ b/packages/flame/lib/src/components/widget_component.dart @@ -54,30 +54,8 @@ import 'package:meta/meta.dart'; /// [WidgetComponent] is rendered several times in one frame, for example /// because its world is viewed by several cameras, only the first render /// paints the widget. -class WidgetComponent extends PositionComponent { - WidgetComponent({ - required Widget widget, - this.constraints, - super.size, - super.position, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - }) : _widget = widget, // ignore: prefer_initializing_formals - _adoptsWidgetSize = size == null { - size.addListener(_onSizeChanged); - } - - Widget _widget; - final bool _adoptsWidgetSize; - bool _isAdoptingSize = false; - bool _isPainted = false; - Game? _game; - final _HostNotifier _hostNotifier = _HostNotifier(); +class WidgetComponent({ + required var Widget _widget, /// The constraints that the widget is laid out with when no [size] was /// given. When this is null too, the widget is laid out with loose @@ -85,7 +63,26 @@ class WidgetComponent extends PositionComponent { /// /// Ignored when a [size] was given, since the widget then always gets tight /// constraints of that size. - final BoxConstraints? constraints; + final BoxConstraints? constraints, + super.size, + super.position, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { + this { + size.addListener(_onSizeChanged); + } + + final bool _adoptsWidgetSize = size == null; + bool _isAdoptingSize = false; + bool _isPainted = false; + Game? _game; + final _HostNotifier _hostNotifier = _HostNotifier(); /// The Flutter widget hosted by this component. /// @@ -199,6 +196,6 @@ class WidgetComponent extends PositionComponent { } } -class _HostNotifier extends ChangeNotifier { +class _HostNotifier() extends ChangeNotifier { void notify() => notifyListeners(); } diff --git a/packages/flame/lib/src/device.dart b/packages/flame/lib/src/device.dart index 188013957f6..021d601c502 100644 --- a/packages/flame/lib/src/device.dart +++ b/packages/flame/lib/src/device.dart @@ -7,7 +7,7 @@ import 'package:flutter/services.dart'; /// full-screen). /// /// To use this class, access it via Flame.device. -class Device { +class Device() { void _warnIfDesktop(String source) { assert(() { if (!kIsWeb && diff --git a/packages/flame/lib/src/devtools/connectors/component_count_connector.dart b/packages/flame/lib/src/devtools/connectors/component_count_connector.dart index 3384618410a..dccce266329 100644 --- a/packages/flame/lib/src/devtools/connectors/component_count_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/component_count_connector.dart @@ -5,7 +5,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// The [ComponentCountConnector] is responsible for reporting the component /// count of the game to the devtools extension. -class ComponentCountConnector extends DevToolsConnector { +class ComponentCountConnector() extends DevToolsConnector { @override void init() { // Get the amount of components in the tree. diff --git a/packages/flame/lib/src/devtools/connectors/component_snapshot_connector.dart b/packages/flame/lib/src/devtools/connectors/component_snapshot_connector.dart index 0a34f8e6445..a736c7f4abf 100644 --- a/packages/flame/lib/src/devtools/connectors/component_snapshot_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/component_snapshot_connector.dart @@ -15,7 +15,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// `ext.flame_devtools.getComponentTree` service extension. The optional /// `pixelRatio` parameter can be used to render the image in a higher (or /// lower) resolution than the logical size of the component. -class ComponentSnapshotConnector extends DevToolsConnector { +class ComponentSnapshotConnector() extends DevToolsConnector { @override void init() { registerExtension( diff --git a/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart b/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart index 1863e91a85f..8e732acab43 100644 --- a/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart @@ -8,7 +8,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// The [ComponentTreeConnector] is responsible for reporting the component /// tree of the game, and information about single components, to the devtools /// extension. -class ComponentTreeConnector extends DevToolsConnector { +class ComponentTreeConnector() extends DevToolsConnector { @override void init() { // Get the component tree of the game. @@ -55,24 +55,15 @@ class ComponentTreeConnector extends DevToolsConnector { } /// This should only be used internally by the devtools extension. -class ComponentTreeNode { - final int id; - final String name; - final String toStringText; - final bool isPositionComponent; - final Map attributes; - final List children; - - ComponentTreeNode( - this.id, - this.name, - this.toStringText, - // ignore: avoid_positional_boolean_parameters - this.isPositionComponent, - this.children, { - this.attributes = const {}, - }); - +class ComponentTreeNode( + final int id, + final String name, + final String toStringText, + // ignore: avoid_positional_boolean_parameters + final bool isPositionComponent, + final List children, { + final Map attributes = const {}, +}) { ComponentTreeNode.fromComponent(Component component) : this( component.hashCode, diff --git a/packages/flame/lib/src/devtools/connectors/debug_mode_connector.dart b/packages/flame/lib/src/devtools/connectors/debug_mode_connector.dart index 4a853421fbf..d06e99bc26c 100644 --- a/packages/flame/lib/src/devtools/connectors/debug_mode_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/debug_mode_connector.dart @@ -6,7 +6,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// The [DebugModeConnector] is responsible for reporting and setting the /// `debugMode` of the game from the devtools extension. -class DebugModeConnector extends DevToolsConnector { +class DebugModeConnector() extends DevToolsConnector { @override void init() { // Get the `debugMode` for a component in the tree. diff --git a/packages/flame/lib/src/devtools/connectors/game_loop_connector.dart b/packages/flame/lib/src/devtools/connectors/game_loop_connector.dart index 090fe5823c9..92d598184a8 100644 --- a/packages/flame/lib/src/devtools/connectors/game_loop_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/game_loop_connector.dart @@ -6,7 +6,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// The [GameLoopConnector] is responsible for reporting and setting the /// pause/running state of the game and stepping the game forwards or backwards /// from the devtools extension. -class GameLoopConnector extends DevToolsConnector { +class GameLoopConnector() extends DevToolsConnector { @override void init() { // Get whether the game is currently paused or not. diff --git a/packages/flame/lib/src/devtools/connectors/game_snapshot_connector.dart b/packages/flame/lib/src/devtools/connectors/game_snapshot_connector.dart index 5f2262b3519..ffe1014391a 100644 --- a/packages/flame/lib/src/devtools/connectors/game_snapshot_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/game_snapshot_connector.dart @@ -15,7 +15,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// `world` parameter set to `true`, or a `rect` given as `x,y,width,height` /// in world coordinates, the world is rendered directly instead of through /// the camera, which also shows the components that are off screen. -class GameSnapshotConnector extends DevToolsConnector { +class GameSnapshotConnector() extends DevToolsConnector { @override void init() { registerExtension( @@ -87,7 +87,7 @@ class GameSnapshotConnector extends DevToolsConnector { game.render(canvas); - return _toImage(pictureRecorder, size.x, size.y, pixelRatio); + return await _toImage(pictureRecorder, size.x, size.y, pixelRatio); } /// Renders the [rect] of the world of the [game], in world coordinates, @@ -108,7 +108,7 @@ class GameSnapshotConnector extends DevToolsConnector { child.renderTree(canvas); } - return _toImage(pictureRecorder, rect.width, rect.height, pixelRatio); + return await _toImage(pictureRecorder, rect.width, rect.height, pixelRatio); } /// The smallest rectangle, in world coordinates, that contains every diff --git a/packages/flame/lib/src/devtools/connectors/input_connector.dart b/packages/flame/lib/src/devtools/connectors/input_connector.dart index cb758b30434..22cfa9575f0 100644 --- a/packages/flame/lib/src/devtools/connectors/input_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/input_connector.dart @@ -13,7 +13,7 @@ import 'package:flutter/services.dart'; /// Positions are in canvas coordinates, the same ones that a snapshot of the /// game uses, and the events are delivered through the same dispatchers that /// real input goes through. -class InputConnector extends DevToolsConnector { +class InputConnector() extends DevToolsConnector { @override void init() { registerExtension( diff --git a/packages/flame/lib/src/devtools/connectors/overlay_navigation_connector.dart b/packages/flame/lib/src/devtools/connectors/overlay_navigation_connector.dart index 6ca6bec018d..100b89b62b5 100644 --- a/packages/flame/lib/src/devtools/connectors/overlay_navigation_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/overlay_navigation_connector.dart @@ -6,7 +6,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// The [OverlayNavigationConnector] is responsible of getting the names of all /// registered overlays, navigating to the overlay with the given name, and /// showing or hiding single overlays. -class OverlayNavigationConnector extends DevToolsConnector { +class OverlayNavigationConnector() extends DevToolsConnector { @override void init() { // Get the names of all registered overlays, and of the active ones. diff --git a/packages/flame/lib/src/devtools/connectors/position_component_attributes_connector.dart b/packages/flame/lib/src/devtools/connectors/position_component_attributes_connector.dart index a69655532ee..cd08a996d86 100644 --- a/packages/flame/lib/src/devtools/connectors/position_component_attributes_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/position_component_attributes_connector.dart @@ -10,7 +10,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// /// The `priority` attribute can be set on any component, the other attributes /// only on a [PositionComponent]. -class PositionComponentAttributesConnector extends DevToolsConnector { +class PositionComponentAttributesConnector() extends DevToolsConnector { @override void init() { registerExtension( diff --git a/packages/flame/lib/src/devtools/dev_tools_connector.dart b/packages/flame/lib/src/devtools/dev_tools_connector.dart index dfff29adc99..fee7873977b 100644 --- a/packages/flame/lib/src/devtools/dev_tools_connector.dart +++ b/packages/flame/lib/src/devtools/dev_tools_connector.dart @@ -12,8 +12,8 @@ import 'package:flutter/foundation.dart'; /// service extensions which makes it possible for the devtools extension to /// communicate with your interface. Then the [initGame] method will be called /// every time a new game is set in the service. -abstract class DevToolsConnector { - DevToolsConnector() { +abstract class DevToolsConnector() { + this { init(); } diff --git a/packages/flame/lib/src/devtools/dev_tools_service.dart b/packages/flame/lib/src/devtools/dev_tools_service.dart index c64a6f21ba1..09773633a2d 100644 --- a/packages/flame/lib/src/devtools/dev_tools_service.dart +++ b/packages/flame/lib/src/devtools/dev_tools_service.dart @@ -19,9 +19,7 @@ import 'package:flame/src/devtools/dev_tools_connector.dart'; /// created will be connected to the devtools. If you want to change it to /// another game instance you can call [DevToolsService.initWithGame] with /// the game instance that you want to observe. -class DevToolsService { - DevToolsService._(); - +class DevToolsService._() { static final instance = DevToolsService._(); /// Initializes the service with the given game instance. diff --git a/packages/flame/lib/src/effects/anchor_by_effect.dart b/packages/flame/lib/src/effects/anchor_by_effect.dart index 8985cabc94e..1cdbe47eed5 100644 --- a/packages/flame/lib/src/effects/anchor_by_effect.dart +++ b/packages/flame/lib/src/effects/anchor_by_effect.dart @@ -18,17 +18,16 @@ import 'package:vector_math/vector_math.dart'; /// allows it to be combined with other [AnchorEffect]s. When several /// [AnchorByEffect]s are applied to the same target simultaneously, the anchor /// is moved by the vector sum of offsets from all effects. -class AnchorByEffect extends AnchorEffect { - AnchorByEffect( - Vector2 offset, - EffectController controller, { - AnchorProvider? target, - void Function()? onComplete, - super.key, - }) : _offset = offset.clone(), - super(controller, target, onComplete: onComplete); +class AnchorByEffect( + Vector2 offset, + EffectController controller, { + AnchorProvider? target, + void Function()? onComplete, + super.key, +}) extends AnchorEffect { + this : super(controller, target, onComplete: onComplete); - final Vector2 _offset; + final Vector2 _offset = offset.clone(); @override void apply(double progress) { diff --git a/packages/flame/lib/src/effects/anchor_effect.dart b/packages/flame/lib/src/effects/anchor_effect.dart index 4f016b6d29b..03b76f49fba 100644 --- a/packages/flame/lib/src/effects/anchor_effect.dart +++ b/packages/flame/lib/src/effects/anchor_effect.dart @@ -14,15 +14,15 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// /// Factory constructors [AnchorEffect.by] and [AnchorEffect.to] are also /// provided for convenience. -abstract class AnchorEffect extends Effect +abstract class AnchorEffect( + super.controller, + AnchorProvider? target, { + super.onComplete, + super.key, +}) extends Effect with EffectTarget implements MeasurableEffect { - AnchorEffect( - super.controller, - AnchorProvider? target, { - super.onComplete, - super.key, - }) { + this { this.target = target; } diff --git a/packages/flame/lib/src/effects/anchor_to_effect.dart b/packages/flame/lib/src/effects/anchor_to_effect.dart index 9f0a2035e1b..4882696b5e2 100644 --- a/packages/flame/lib/src/effects/anchor_to_effect.dart +++ b/packages/flame/lib/src/effects/anchor_to_effect.dart @@ -9,17 +9,15 @@ import 'package:vector_math/vector_math.dart'; /// The anchor will move in a straight line from the anchor's value at the start /// of the effect towards the provided target. The timing of the move is /// governed by the [controller]. -class AnchorToEffect extends AnchorEffect { - AnchorToEffect( - Anchor destination, - EffectController controller, { - AnchorProvider? target, - void Function()? onComplete, - super.key, - }) : _destination = destination, - super(controller, target, onComplete: onComplete); +class AnchorToEffect( + final Anchor _destination, + EffectController controller, { + AnchorProvider? target, + void Function()? onComplete, + super.key, +}) extends AnchorEffect { + this : super(controller, target, onComplete: onComplete); - final Anchor _destination; late Vector2 _offset; @override diff --git a/packages/flame/lib/src/effects/color_effect.dart b/packages/flame/lib/src/effects/color_effect.dart index 1fc17502ee0..175c01b5796 100644 --- a/packages/flame/lib/src/effects/color_effect.dart +++ b/packages/flame/lib/src/effects/color_effect.dart @@ -2,7 +2,6 @@ import 'dart:math'; import 'package:flame/components.dart'; import 'package:flame/src/effects/component_effect.dart'; -import 'package:flame/src/effects/controllers/effect_controller.dart'; import 'package:material_ui/material_ui.dart'; /// Change the color of a component over time. @@ -10,29 +9,27 @@ import 'package:material_ui/material_ui.dart'; /// Due to how this effect is implemented, and how Flutter's [ColorFilter] /// class works, this effect can't be mixed with other [ColorEffect]s, when more /// than one is added to the component, only the last one will have effect. -class ColorEffect extends ComponentEffect { - final String? paintId; - final Color color; +class ColorEffect( + final Color color, + super.controller, { + double opacityFrom = 0, + double opacityTo = 1, + final String? paintId, + super.onComplete, + super.key, +}) extends ComponentEffect { ColorFilter? _original; late final Tween _tween; - ColorEffect( - this.color, - EffectController controller, { - double opacityFrom = 0, - double opacityTo = 1, - this.paintId, - super.onComplete, - super.key, - }) : assert( - opacityFrom >= 0 && - opacityFrom <= 1 && - opacityTo >= 0 && - opacityTo <= 1, - 'Opacity value should be between 0 and 1', - ), - _tween = Tween(begin: opacityFrom, end: opacityTo), - super(controller); + this + : assert( + opacityFrom >= 0 && + opacityFrom <= 1 && + opacityTo >= 0 && + opacityTo <= 1, + 'Opacity value should be between 0 and 1', + ), + _tween = Tween(begin: opacityFrom, end: opacityTo); @override Future onMount() async { diff --git a/packages/flame/lib/src/effects/combined_effect.dart b/packages/flame/lib/src/effects/combined_effect.dart index a21f0c12e25..58d1841f371 100644 --- a/packages/flame/lib/src/effects/combined_effect.dart +++ b/packages/flame/lib/src/effects/combined_effect.dart @@ -17,28 +17,29 @@ import 'package:flame/effects.dart'; /// infinitely. This is equivalent to setting `repeatCount = infinity`. If both /// the `infinite` and the `repeatCount` parameters are given, then `infinite` /// takes precedence. -class CombinedEffect extends Effect with CustomTraversal { - CombinedEffect( - List effects, { - bool alternate = false, - bool infinite = false, - int repeatCount = 1, - super.onComplete, - super.key, - }) : assert(effects.isNotEmpty, 'The list of effects cannot be empty'), - assert( - !(infinite && repeatCount != 1), - 'Parameters infinite and repeatCount cannot be specified ' - 'simultaneously', - ), - super( - _createController( - effects: effects, - alternate: alternate, - infinite: infinite, - repeatCount: repeatCount, - ), - ) { +class CombinedEffect( + List effects, { + bool alternate = false, + bool infinite = false, + int repeatCount = 1, + super.onComplete, + super.key, +}) extends Effect with CustomTraversal { + this + : assert(effects.isNotEmpty, 'The list of effects cannot be empty'), + assert( + !(infinite && repeatCount != 1), + 'Parameters infinite and repeatCount cannot be specified ' + 'simultaneously', + ), + super( + _createController( + effects: effects, + alternate: alternate, + infinite: infinite, + repeatCount: repeatCount, + ), + ) { addAll(effects); } diff --git a/packages/flame/lib/src/effects/component_effect.dart b/packages/flame/lib/src/effects/component_effect.dart index 6da175afd01..65a683e737d 100644 --- a/packages/flame/lib/src/effects/component_effect.dart +++ b/packages/flame/lib/src/effects/component_effect.dart @@ -5,13 +5,11 @@ import 'package:flame/src/effects/effect.dart'; /// /// A general abstraction for creating effects targeting [Component]s, currently /// used by `SizeEffect`, `OpacityEffect` and `Transform2DEffect`. -abstract class ComponentEffect extends Effect { - ComponentEffect( - super.controller, { - super.onComplete, - super.key, - }); - +abstract class ComponentEffect( + super.controller, { + super.onComplete, + super.key, +}) extends Effect { late T target; @override diff --git a/packages/flame/lib/src/effects/controllers/callback_controller.dart b/packages/flame/lib/src/effects/controllers/callback_controller.dart index 49c18069136..2592b5e9f18 100644 --- a/packages/flame/lib/src/effects/controllers/callback_controller.dart +++ b/packages/flame/lib/src/effects/controllers/callback_controller.dart @@ -1,19 +1,20 @@ import 'dart:ui'; + import 'package:flame/effects.dart'; /// This effect controller invokes the [callback] function and then immediately /// finishes. Use it as part of a more complex effect to insert callbacks at /// certain parts of that effect. -class CallbackController extends DurationEffectController { +class CallbackController( + final VoidCallback callback, { + required final double _progress, +}) extends DurationEffectController { /// Creates a controller that invokes the given [callback] function. /// The [_progress] parameter specifies the progress level of the effect at /// the time when the callback is invoked. It is the responsibility of the /// user to ensure that this progress level is contiguous with respect to the /// progress of the overall effect. - CallbackController(this.callback, {required this._progress}) : super(0.0); - - final VoidCallback callback; - final double _progress; + this : super(0.0); @override double get progress => _progress; diff --git a/packages/flame/lib/src/effects/controllers/combined_effect_controller.dart b/packages/flame/lib/src/effects/controllers/combined_effect_controller.dart index db38b966683..a2dbada8013 100644 --- a/packages/flame/lib/src/effects/controllers/combined_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/combined_effect_controller.dart @@ -3,16 +3,13 @@ import 'dart:math'; import 'package:flame/src/effects/controllers/effect_controller.dart'; import 'package:flame/src/effects/effect.dart'; -class CombinedEffectController extends EffectController { - CombinedEffectController( - this.effects, { - required this.alternate, - }) : _duration = _calculateDuration(effects, alternate), - super.empty(); - - final List effects; - final bool alternate; - final double _duration; +class CombinedEffectController( + final List effects, { + required final bool alternate, +}) extends EffectController { + this : super.empty(); + + final double _duration = _calculateDuration(effects, alternate); double t = 0; diff --git a/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart b/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart index 158cd93972b..3e76dc17ffe 100644 --- a/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart @@ -3,14 +3,11 @@ import 'package:flutter/animation.dart'; /// A controller that grows non-linearly from 0 to 1 following the provided /// [curve]. The [duration] cannot be 0. -class CurvedEffectController extends DurationEffectController { - CurvedEffectController(super.duration, Curve curve) - : assert(duration > 0, 'Duration must be positive: $duration'), - _curve = curve; +class CurvedEffectController(super.duration, final Curve _curve) + extends DurationEffectController { + this : assert(duration > 0, 'Duration must be positive: $duration'); Curve get curve => _curve; - final Curve _curve; - @override double get progress => _curve.transform(timer / duration); } diff --git a/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart b/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart index fa957522f27..2993bb472bb 100644 --- a/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart @@ -2,16 +2,15 @@ import 'package:flame/effects.dart'; /// An effect controller that waits for [delay] seconds before running the /// child controller. While waiting, the progress will be reported at 0. -class DelayedEffectController extends EffectController - with HasSingleChildEffectController { - DelayedEffectController(EffectController child, {required this.delay}) +class DelayedEffectController( + final EffectController _child, { + required final double delay, +}) extends EffectController with HasSingleChildEffectController { + this : assert(delay >= 0, 'Delay must be non-negative: $delay'), - _child = child, _timer = 0, super.empty(); - final EffectController _child; - final double delay; double _timer; @override diff --git a/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart b/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart index 96599d6ff49..54c33d0e377 100644 --- a/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart @@ -10,17 +10,15 @@ import 'package:meta/meta.dart'; /// which keeps track of how much time has passed within this controller. The /// effect controller will be considered [completed] when the timer reaches the /// [duration] value. -abstract class DurationEffectController extends EffectController { - DurationEffectController(this.duration) +abstract class DurationEffectController(@override var double duration) + extends EffectController { + this : assert(duration >= 0, 'Duration cannot be negative: $duration'), _timer = 0, super.empty(); double _timer; - @override - double duration; - @protected double get timer => _timer; diff --git a/packages/flame/lib/src/effects/controllers/effect_controller.dart b/packages/flame/lib/src/effects/controllers/effect_controller.dart index 1c3f95bb380..a171a13e315 100644 --- a/packages/flame/lib/src/effects/controllers/effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/effect_controller.dart @@ -43,7 +43,7 @@ import 'package:flutter/animation.dart' show Curve, Curves; /// Unlike the `dart.ui.AnimationController`, this class does not use a `Ticker` /// to keep track of time. Instead, it must be pushed through time manually, by /// calling the `update()` method within the game loop. -abstract class EffectController { +abstract class EffectController.empty() { /// Factory function for producing common [EffectController]s. /// /// In the simplest case, when only `duration` is provided, this will return @@ -230,8 +230,6 @@ abstract class EffectController { return controller; } - EffectController.empty(); - /// Will the effect continue to run forever (never completes)? bool get isInfinite => duration == double.infinity; diff --git a/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart b/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart index 76ae8219c3f..8c307bdc451 100644 --- a/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart @@ -2,13 +2,10 @@ import 'package:flame/effects.dart'; /// Effect controller that wraps a [child] effect controller and repeats it /// infinitely. -class InfiniteEffectController extends EffectController +class InfiniteEffectController(final EffectController _child) + extends EffectController with HasSingleChildEffectController { - InfiniteEffectController(EffectController child) - : _child = child, - super.empty(); - - final EffectController _child; + this : super.empty(); @override EffectController get child => _child; diff --git a/packages/flame/lib/src/effects/controllers/linear_effect_controller.dart b/packages/flame/lib/src/effects/controllers/linear_effect_controller.dart index 2e5f8913427..fa1fe87503e 100644 --- a/packages/flame/lib/src/effects/controllers/linear_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/linear_effect_controller.dart @@ -4,10 +4,7 @@ import 'package:flame/src/effects/controllers/duration_effect_controller.dart'; /// /// The [duration] can also be 0, in which case the effect will jump from 0 to 1 /// instantaneously. -class LinearEffectController extends DurationEffectController { - LinearEffectController(super.duration); - - // If duration is 0, `completed` will be true, and division by 0 avoided. +class LinearEffectController(super.duration) extends DurationEffectController { @override double get progress => completed ? 1 : (timer / duration); } diff --git a/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart b/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart index 5bd561ee7be..4d5109249b6 100644 --- a/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart @@ -9,11 +9,8 @@ import 'package:flame/src/effects/controllers/duration_effect_controller.dart'; /// This controller is best used in combination with other controllers. For /// example, you can create a repeated controller where the progress changes /// 0->1->0 over a short period of time, then pauses, and this sequence repeats. -class PauseEffectController extends DurationEffectController { - PauseEffectController(super.duration, {required this._progress}); - - final double _progress; - +class PauseEffectController(super.duration, {required final double _progress}) + extends DurationEffectController { @override double get progress => _progress; } diff --git a/packages/flame/lib/src/effects/controllers/random_effect_controller.dart b/packages/flame/lib/src/effects/controllers/random_effect_controller.dart index fbf8da127ec..49908fda47d 100644 --- a/packages/flame/lib/src/effects/controllers/random_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/random_effect_controller.dart @@ -12,12 +12,12 @@ import 'package:flame/effects.dart'; /// The child's duration is randomized first at construction, and then at each /// reset (`setToStart`). Thus, the child has a concrete well-defined duration /// at any point in time. -class RandomEffectController extends EffectController +class RandomEffectController( + final DurationEffectController _child, + final RandomVariable randomGenerator, +) extends EffectController with HasSingleChildEffectController { - RandomEffectController(DurationEffectController child, this.randomGenerator) - : assert(!child.isInfinite, 'Child cannot be infinite'), - _child = child, - super.empty() { + this : assert(!_child.isInfinite, 'Child cannot be infinite'), super.empty() { _initializeDuration(); } @@ -52,9 +52,6 @@ class RandomEffectController extends EffectController ); } - final DurationEffectController _child; - final RandomVariable randomGenerator; - @override DurationEffectController get child => _child; @@ -95,11 +92,9 @@ class RandomEffectController extends EffectController /// [RandomVariable] is an object capable of producing random values with the /// prescribed distribution function. Each distribution is implemented within /// its own derived class. -abstract class RandomVariable { - RandomVariable(Random? random) : _random = random ?? _defaultRandom; - +abstract class RandomVariable(Random? random) { /// Internal random number generator. - final Random _random; + final Random _random = random ?? _defaultRandom; static final Random _defaultRandom = Random(); /// Produces the next value for this random variable. @@ -107,24 +102,19 @@ abstract class RandomVariable { } /// Random variable distributed uniformly between [min] and [max]. -class _UniformRandomVariable extends RandomVariable { - _UniformRandomVariable(this.min, this.max, Random? random) : super(random); - - final double min; - final double max; - +class _UniformRandomVariable(final double min, final double max, super.random) + extends RandomVariable { @override double nextValue() => _random.nextDouble() * (max - min) + min; } /// Exponentially distributed random variable with rate parameter [beta]. -class _ExponentialRandomVariable extends RandomVariable { - _ExponentialRandomVariable(this.beta, Random? random) : super(random); - +class _ExponentialRandomVariable( /// Rate parameter of the exponential distribution. This will be the average /// of all returned values - final double beta; - + final double beta, + super.random, +) extends RandomVariable { @override double nextValue() => -log(1 - _random.nextDouble()) * beta; } diff --git a/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart b/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart index 74bf98af290..de2d1868f55 100644 --- a/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart @@ -5,22 +5,19 @@ import 'package:flame/effects.dart'; /// The [repeatCount] must be positive, and [child] controller cannot be /// infinite. The child controller will be reset after each iteration (except /// the last). -class RepeatedEffectController extends EffectController - with HasSingleChildEffectController { - RepeatedEffectController(EffectController child, this.repeatCount) +class RepeatedEffectController( + final EffectController _child, + final int repeatCount, +) extends EffectController with HasSingleChildEffectController { + this : assert(repeatCount > 0, 'repeatCount must be positive'), - assert(!child.isInfinite, 'child cannot be infinite'), - _child = child, - _remainingCount = repeatCount, + assert(!_child.isInfinite, 'child cannot be infinite'), super.empty(); - final EffectController _child; - final int repeatCount; - /// How many iterations this controller has remaining. When this reaches 0 /// the controller is considered completed. int get remainingIterationsCount => _remainingCount; - int _remainingCount; + int _remainingCount = repeatCount; @override EffectController get child => _child; diff --git a/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart b/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart index b9a352d0ed2..56d74f934c8 100644 --- a/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart @@ -3,14 +3,11 @@ import 'package:flutter/animation.dart'; /// A controller that grows non-linearly from 1 to 0 following the provided /// [curve]. The [duration] cannot be 0. -class ReverseCurvedEffectController extends DurationEffectController { - ReverseCurvedEffectController(super.duration, Curve curve) - : assert(duration > 0, 'Duration must be positive: $duration'), - _curve = curve; +class ReverseCurvedEffectController(super.duration, final Curve _curve) + extends DurationEffectController { + this : assert(duration > 0, 'Duration must be positive: $duration'); Curve get curve => _curve; - final Curve _curve; - @override double get progress => _curve.transform(1 - timer / duration); } diff --git a/packages/flame/lib/src/effects/controllers/reverse_linear_effect_controller.dart b/packages/flame/lib/src/effects/controllers/reverse_linear_effect_controller.dart index 123cee3889d..b30aefabe0f 100644 --- a/packages/flame/lib/src/effects/controllers/reverse_linear_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/reverse_linear_effect_controller.dart @@ -4,10 +4,8 @@ import 'package:flame/src/effects/controllers/duration_effect_controller.dart'; /// /// The [duration] can also be 0, in which case the effect will jump from 1 to 0 /// instantaneously. -class ReverseLinearEffectController extends DurationEffectController { - ReverseLinearEffectController(super.duration); - - // If duration is 0, `completed` will be true, and division by 0 avoided. +class ReverseLinearEffectController(super.duration) + extends DurationEffectController { @override double get progress => completed ? 0 : 1 - (timer / duration); } diff --git a/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart b/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart index 54ddaf9da52..36b2003ecdd 100644 --- a/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart @@ -3,19 +3,19 @@ import 'package:flame/src/effects/effect.dart'; /// An effect controller that executes a list of other controllers one after /// another. -class SequenceEffectController extends EffectController { - SequenceEffectController(List controllers) +class SequenceEffectController(List controllers) + extends EffectController { + this : assert(controllers.isNotEmpty, 'List of controllers cannot be empty'), assert( !controllers.any((c) => c.isInfinite), 'Children controllers cannot be infinite', ), - children = controllers, _currentIndex = 0, super.empty(); /// Individual controllers in the sequence. - final List children; + final List children = controllers; /// The index of the controller currently being executed. This starts with 0, /// and by the end it will be equal to `_children.length - 1`. This variable diff --git a/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart b/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart index c3ec5043791..c26f6003e79 100644 --- a/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart @@ -1,4 +1,5 @@ import 'dart:math' as math; + import 'package:flame/geometry.dart'; import 'package:flame/src/effects/controllers/duration_effect_controller.dart'; import 'package:flame/src/effects/controllers/infinite_effect_controller.dart'; @@ -11,10 +12,9 @@ import 'package:flame/src/effects/controllers/repeated_effect_controller.dart'; /// /// Combine with [RepeatedEffectController] or [InfiniteEffectController] in /// order to create longer waves. -class SineEffectController extends DurationEffectController { - SineEffectController({required double period}) - : assert(period > 0, 'Period must be positive: $period'), - super(period); +class SineEffectController({required double period}) + extends DurationEffectController { + this : assert(period > 0, 'Period must be positive: $period'), super(period); @override double get progress { diff --git a/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart b/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart index ea1641ace4e..a31e3aba9d1 100644 --- a/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart @@ -13,15 +13,13 @@ import 'package:flame/src/effects/measurable_effect.dart'; /// - the [speed] cannot be zero (or negative), /// - the [child] controller must be a [DurationEffectController], /// - the parent effect must be a [MeasurableEffect]. -class SpeedEffectController extends EffectController +class SpeedEffectController( + final DurationEffectController _child, { + required final double speed, +}) extends EffectController with HasSingleChildEffectController { - SpeedEffectController(DurationEffectController child, {required this.speed}) - : assert(speed > 0, 'Speed must be positive: $speed'), - _child = child, - super.empty(); + this : assert(speed > 0, 'Speed must be positive: $speed'), super.empty(); - final DurationEffectController _child; - final double speed; MeasurableEffect? _parentEffect; /// Note that this controller's [started] property is true even if the diff --git a/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart b/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart index 5624cf29a18..0938b4ded96 100644 --- a/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart @@ -10,13 +10,11 @@ import 'package:flame/src/effects/controllers/repeated_effect_controller.dart'; /// /// Combine with [RepeatedEffectController] or [InfiniteEffectController] in /// order to create longer zigzags. -class ZigzagEffectController extends DurationEffectController { - ZigzagEffectController({required double period}) - : assert(period > 0, 'Period must be positive: $period'), - _quarterPeriod = period / 4, - super(period); +class ZigzagEffectController({required double period}) + extends DurationEffectController { + this : assert(period > 0, 'Period must be positive: $period'), super(period); - final double _quarterPeriod; + final double _quarterPeriod = period / 4; @override double get progress { diff --git a/packages/flame/lib/src/effects/effect.dart b/packages/flame/lib/src/effects/effect.dart index 4bb183828d0..5d868b6f23e 100644 --- a/packages/flame/lib/src/effects/effect.dart +++ b/packages/flame/lib/src/effects/effect.dart @@ -26,21 +26,22 @@ import 'package:meta/meta.dart'; /// expected to define the `apply()` method, which facilitates the necessary /// changes in the effect's target; and also the `reset()` method if they have /// non-trivial internal state. -abstract class Effect extends Component { - Effect( - this.controller, { - this.onComplete, - super.key, - }) : removeOnFinish = true, - _paused = false, - _started = false, - _finished = false { +abstract class Effect( + /// An object that describes how the effect should evolve over time. + final EffectController controller, { + + /// Optional callback function to be invoked once the effect completes. + var void Function()? onComplete, + super.key, +}) extends Component { + this + : removeOnFinish = true, + _paused = false, + _started = false, + _finished = false { controller.onMount(this); } - /// An object that describes how the effect should evolve over time. - final EffectController controller; - /// Whether the effect should be removed from its parent once it is completed, /// true by default. /// @@ -49,9 +50,6 @@ abstract class Effect extends Component { /// in order to make it run once again. bool removeOnFinish; - /// Optional callback function to be invoked once the effect completes. - void Function()? onComplete; - /// Boolean indicators of the effect's state, their purpose is to ensure that /// the `onStart()` and `onFinish()` callbacks are called exactly once. bool _started; diff --git a/packages/flame/lib/src/effects/function_effect.dart b/packages/flame/lib/src/effects/function_effect.dart index abad4c0a51a..bb5f7eb7678 100644 --- a/packages/flame/lib/src/effects/function_effect.dart +++ b/packages/flame/lib/src/effects/function_effect.dart @@ -9,16 +9,12 @@ import 'package:flame/src/effects/effect_target.dart'; /// /// This could for example be used to make game state changes that happen over /// time, but that isn't necessarily visual, like most other effects are. -class FunctionEffect extends Effect with EffectTarget { - FunctionEffect( - this.function, - super.controller, { - super.onComplete, - super.key, - }); - - void Function(T target, double progress) function; - +class FunctionEffect( + var void Function(T target, double progress) function, + super.controller, { + super.onComplete, + super.key, +}) extends Effect with EffectTarget { @override void apply(double progress) { function(target, progress); diff --git a/packages/flame/lib/src/effects/glow_effect.dart b/packages/flame/lib/src/effects/glow_effect.dart index 22b19b6e2cd..e739edc557d 100644 --- a/packages/flame/lib/src/effects/glow_effect.dart +++ b/packages/flame/lib/src/effects/glow_effect.dart @@ -7,17 +7,12 @@ import 'package:flame/effects.dart'; /// This effect applies incremental changes to the MaskFilter on Paint of a /// component and requires that any other effect or update logic applied to the /// same component also used incremental updates. -class GlowEffect extends Effect with EffectTarget { - GlowEffect( - this.strength, - super.controller, { - this.style = BlurStyle.outer, - super.key, - }); - - final BlurStyle style; - final double strength; - +class GlowEffect( + final double strength, + super.controller, { + final BlurStyle style = BlurStyle.outer, + super.key, +}) extends Effect with EffectTarget { @override void apply(double progress) { target.paint.maskFilter = MaskFilter.blur(style, strength * progress); diff --git a/packages/flame/lib/src/effects/hue_by_effect.dart b/packages/flame/lib/src/effects/hue_by_effect.dart index 77c02e8aa02..e08e0738114 100644 --- a/packages/flame/lib/src/effects/hue_by_effect.dart +++ b/packages/flame/lib/src/effects/hue_by_effect.dart @@ -2,19 +2,17 @@ import 'package:flame/src/effects/hue_effect.dart'; import 'package:flame/src/effects/provider_interfaces.dart'; /// An effect that changes the hue of a component by a specified angle. -class HueByEffect extends HueEffect { - HueByEffect( - double angle, - super.controller, { - HueProvider? target, - super.onComplete, - super.key, - }) : _angle = angle { +class HueByEffect( + final double _angle, + super.controller, { + HueProvider? target, + super.onComplete, + super.key, +}) extends HueEffect { + this { this.target = target; } - final double _angle; - @override void apply(double progress) { final dProgress = progress - previousProgress; diff --git a/packages/flame/lib/src/effects/hue_effect.dart b/packages/flame/lib/src/effects/hue_effect.dart index 774ab40b48e..be864518b39 100644 --- a/packages/flame/lib/src/effects/hue_effect.dart +++ b/packages/flame/lib/src/effects/hue_effect.dart @@ -11,13 +11,11 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// This effect applies incremental changes to the hue property of the target, /// and requires that any other effect or update logic applied to the same /// target also used incremental updates. -abstract class HueEffect extends Effect with EffectTarget { - HueEffect( - super.controller, { - super.onComplete, - super.key, - }); - +abstract class HueEffect( + super.controller, { + super.onComplete, + super.key, +}) extends Effect with EffectTarget { factory HueEffect.by( double angle, EffectController controller, { diff --git a/packages/flame/lib/src/effects/hue_to_effect.dart b/packages/flame/lib/src/effects/hue_to_effect.dart index e2350da20f1..5b5b967cbc1 100644 --- a/packages/flame/lib/src/effects/hue_to_effect.dart +++ b/packages/flame/lib/src/effects/hue_to_effect.dart @@ -2,19 +2,18 @@ import 'package:flame/src/effects/hue_effect.dart'; import 'package:flame/src/effects/provider_interfaces.dart'; /// An effect that changes the hue of a component to a specified angle. -class HueToEffect extends HueEffect { - HueToEffect( - double angle, - super.controller, { - HueProvider? target, - super.onComplete, - super.key, - }) : _destinationAngle = angle, - _angle = 0.0 { +class HueToEffect( + double angle, + super.controller, { + HueProvider? target, + super.onComplete, + super.key, +}) extends HueEffect { + this : _angle = 0.0 { this.target = target; } - final double _destinationAngle; + final double _destinationAngle = angle; double _angle; @override diff --git a/packages/flame/lib/src/effects/measurable_effect.dart b/packages/flame/lib/src/effects/measurable_effect.dart index e13cdaab19b..1a238915b4f 100644 --- a/packages/flame/lib/src/effects/measurable_effect.dart +++ b/packages/flame/lib/src/effects/measurable_effect.dart @@ -7,7 +7,7 @@ import 'package:flame/src/effects/controllers/speed_effect_controller.dart'; /// /// Use this interface for any effect that you want to be compatible with the /// [SpeedEffectController]. -abstract class MeasurableEffect { +abstract class MeasurableEffect() { /// Calculate the "measure" of the effect, which is the effect's distance /// from min to max progress. The "measure" is any property for which the /// notion of _speed_ is well-defined. diff --git a/packages/flame/lib/src/effects/move_along_path_effect.dart b/packages/flame/lib/src/effects/move_along_path_effect.dart index 4902ea5d52b..c69837005b7 100644 --- a/packages/flame/lib/src/effects/move_along_path_effect.dart +++ b/packages/flame/lib/src/effects/move_along_path_effect.dart @@ -23,21 +23,20 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// follows the path so that it is always oriented tangent to the path. When /// using this flag, make sure that the effect is applied to a target that /// actually supports rotations. -class MoveAlongPathEffect extends MoveEffect { - MoveAlongPathEffect( - Path path, - EffectController controller, { - bool absolute = false, - bool oriented = false, - PositionProvider? target, - super.onComplete, - super.key, - }) : _isAbsolute = absolute, - _followDirection = oriented, - super( - controller, - target, - ) { +class MoveAlongPathEffect( + Path path, + EffectController controller, { + bool absolute = false, + bool oriented = false, + PositionProvider? target, + super.onComplete, + super.key, +}) extends MoveEffect { + this + : super( + controller, + target, + ) { final metrics = path.computeMetrics().toList(); if (metrics.length != 1) { throw ArgumentError( @@ -53,11 +52,11 @@ class MoveAlongPathEffect extends MoveEffect { /// put onto the start of the path and then follow that path. If false, the /// path is considered _relative_, i.e. this path is added as an offset to /// the current position of the target. - final bool _isAbsolute; + final bool _isAbsolute = absolute; /// If true, then not only the target's position will follow the path, but /// also the target's angle of rotation. - final bool _followDirection; + final bool _followDirection = oriented; /// The path that the target will follow. late final PathMetric _pathMetric; diff --git a/packages/flame/lib/src/effects/move_by_effect.dart b/packages/flame/lib/src/effects/move_by_effect.dart index a84d2783129..b84d7c825d5 100644 --- a/packages/flame/lib/src/effects/move_by_effect.dart +++ b/packages/flame/lib/src/effects/move_by_effect.dart @@ -17,17 +17,16 @@ import 'package:vector_math/vector_math.dart'; /// allows it to be combined with other [MoveEffect]s. When several /// [MoveByEffect]s are applied to the same target simultaneously, the target /// is moved by the vector sum of offsets from all effects. -class MoveByEffect extends MoveEffect { - MoveByEffect( - Vector2 offset, - EffectController controller, { - PositionProvider? target, - void Function()? onComplete, - super.key, - }) : _offset = offset.clone(), - super(controller, target, onComplete: onComplete); +class MoveByEffect( + Vector2 offset, + EffectController controller, { + PositionProvider? target, + void Function()? onComplete, + super.key, +}) extends MoveEffect { + this : super(controller, target, onComplete: onComplete); - final Vector2 _offset; + final Vector2 _offset = offset.clone(); @override void apply(double progress) { diff --git a/packages/flame/lib/src/effects/move_effect.dart b/packages/flame/lib/src/effects/move_effect.dart index dab3d4cec69..b702f5ae369 100644 --- a/packages/flame/lib/src/effects/move_effect.dart +++ b/packages/flame/lib/src/effects/move_effect.dart @@ -14,15 +14,15 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// /// Factory constructors [MoveEffect.by] and [MoveEffect.to] are also provided, /// but they may be deprecated in the future. -abstract class MoveEffect extends Effect +abstract class MoveEffect( + super.controller, + PositionProvider? target, { + super.onComplete, + super.key, +}) extends Effect with EffectTarget implements MeasurableEffect { - MoveEffect( - super.controller, - PositionProvider? target, { - super.onComplete, - super.key, - }) { + this { this.target = target; } diff --git a/packages/flame/lib/src/effects/move_to_effect.dart b/packages/flame/lib/src/effects/move_to_effect.dart index 120293dc8aa..4764d2f431e 100644 --- a/packages/flame/lib/src/effects/move_to_effect.dart +++ b/packages/flame/lib/src/effects/move_to_effect.dart @@ -19,18 +19,18 @@ import 'package:vector_math/vector_math.dart'; /// will end up moving the target towards point A+B. A more interesting /// combination of move effects is to have a [MoveToEffect], together with one /// or more [MoveByEffect]s that produce oscillating motion. -class MoveToEffect extends MoveEffect { - MoveToEffect( - Vector2 destination, - EffectController controller, { - PositionProvider? target, - void Function()? onComplete, - super.key, - }) : _destination = destination.clone(), - _offset = Vector2.zero(), - super(controller, target, onComplete: onComplete); +class MoveToEffect( + Vector2 destination, + EffectController controller, { + PositionProvider? target, + void Function()? onComplete, + super.key, +}) extends MoveEffect { + this + : _offset = Vector2.zero(), + super(controller, target, onComplete: onComplete); - final Vector2 _destination; + final Vector2 _destination = destination.clone(); final Vector2 _offset; @override diff --git a/packages/flame/lib/src/effects/opacity_effect.dart b/packages/flame/lib/src/effects/opacity_effect.dart index d437bc00c43..ac19e5eaf6e 100644 --- a/packages/flame/lib/src/effects/opacity_effect.dart +++ b/packages/flame/lib/src/effects/opacity_effect.dart @@ -6,16 +6,16 @@ import 'package:flame/effects.dart'; /// This effect applies incremental changes to the component's opacity, and /// requires that any other effect or update logic applied to the same component /// also used incremental updates. -class OpacityEffect extends Effect with EffectTarget { +class OpacityEffect.by( + double offset, + super.controller, { + OpacityProvider? target, + super.onComplete, + super.key, +}) extends Effect with EffectTarget { /// This constructor will set the opacity in relation to it's current opacity /// over time. - OpacityEffect.by( - double offset, - super.controller, { - OpacityProvider? target, - super.onComplete, - super.key, - }) : _opacityOffset = offset { + this { this.target = target; } @@ -66,7 +66,7 @@ class OpacityEffect extends Effect with EffectTarget { ); } - double _opacityOffset; + double _opacityOffset = offset; double _roundingError = 0.0; @override @@ -89,19 +89,18 @@ class OpacityEffect extends Effect with EffectTarget { } /// Implementation class for [OpacityEffect.to] -class _OpacityToEffect extends OpacityEffect { - final double _targetOpacity; - - _OpacityToEffect( - this._targetOpacity, - EffectController controller, { - super.target, - super.onComplete, - super.key, - }) : super.by( - 0.0, - controller, - ); +class _OpacityToEffect( + final double _targetOpacity, + EffectController controller, { + super.target, + super.onComplete, + super.key, +}) extends OpacityEffect { + this + : super.by( + 0.0, + controller, + ); @override void onStart() { diff --git a/packages/flame/lib/src/effects/provider_interfaces.dart b/packages/flame/lib/src/effects/provider_interfaces.dart index 0bc08988992..18d2565981b 100644 --- a/packages/flame/lib/src/effects/provider_interfaces.dart +++ b/packages/flame/lib/src/effects/provider_interfaces.dart @@ -3,28 +3,25 @@ import 'dart:ui'; import 'package:flame/components.dart'; /// Interface for a component that can be affected by move effects. -abstract class PositionProvider implements ReadOnlyPositionProvider { +abstract class PositionProvider() implements ReadOnlyPositionProvider { set position(Vector2 value); } /// Interface for a class that has [position] property which can be read but not /// modified. -abstract class ReadOnlyPositionProvider { +abstract class ReadOnlyPositionProvider() { Vector2 get position; } /// This class allows constructing [PositionProvider]s on the fly, using the /// callbacks for the position getter and setter. This class doesn't require /// either the getter or the setter, if you do not intend to use those. -class PositionProviderImpl implements PositionProvider { - PositionProviderImpl({ - Vector2 Function()? getValue, - void Function(Vector2)? setValue, - }) : _getter = getValue, - _setter = setValue; - - final Vector2 Function()? _getter; - final void Function(Vector2)? _setter; +class PositionProviderImpl({ + Vector2 Function()? getValue, + void Function(Vector2)? setValue, +}) implements PositionProvider { + final Vector2 Function()? _getter = getValue; + final void Function(Vector2)? _setter = setValue; @override Vector2 get position => _getter!(); @@ -35,40 +32,40 @@ class PositionProviderImpl implements PositionProvider { /// Interface for a class that has [scale] property which can be read but not /// modified. -abstract class ReadOnlyScaleProvider { +abstract class ReadOnlyScaleProvider() { Vector2 get scale; } /// Interface for a component that can be affected by scale effects. -abstract class ScaleProvider extends ReadOnlyScaleProvider { +abstract class ScaleProvider() extends ReadOnlyScaleProvider { set scale(Vector2 value); } /// Interface for a class that has [angle] property which can be read but not /// modified. -abstract class ReadOnlyAngleProvider { +abstract class ReadOnlyAngleProvider() { double get angle; } /// Interface for a component that can be affected by rotation effects. -abstract class AngleProvider extends ReadOnlyAngleProvider { +abstract class AngleProvider() extends ReadOnlyAngleProvider { set angle(double value); } /// Interface for a component that can be affected by anchor effects. -abstract class AnchorProvider { +abstract class AnchorProvider() { Anchor get anchor; set anchor(Anchor value); } /// Interface for a class that has [size] property which can be read but not /// modified. -abstract class ReadOnlySizeProvider { +abstract class ReadOnlySizeProvider() { Vector2 get size; } /// Interface for a component that can be affected by size effects. -abstract class SizeProvider extends ReadOnlySizeProvider { +abstract class SizeProvider() extends ReadOnlySizeProvider { set size(Vector2 value); } @@ -82,7 +79,7 @@ abstract class SizeProvider extends ReadOnlySizeProvider { /// necessarily produce the same `x` when reading it back. /// /// See [HasPaint] for an example implementation. -abstract class OpacityProvider { +abstract class OpacityProvider() { double get opacity; set opacity(double value); } @@ -90,13 +87,13 @@ abstract class OpacityProvider { /// Interface for a component that can be affected by Paint effects. /// /// See [HasPaint] for an example implementation. -abstract class PaintProvider { +abstract class PaintProvider() { Paint get paint; set paint(Paint value); } /// Interface for a component that can be affected by hue effects. -abstract class HueProvider { +abstract class HueProvider() { double get hue; set hue(double value); } diff --git a/packages/flame/lib/src/effects/remove_effect.dart b/packages/flame/lib/src/effects/remove_effect.dart index b1af7e36e0b..adedca3cd73 100644 --- a/packages/flame/lib/src/effects/remove_effect.dart +++ b/packages/flame/lib/src/effects/remove_effect.dart @@ -2,14 +2,15 @@ import 'package:flame/effects.dart'; /// This simple effect, when attached to a component, will cause that component /// to be removed from the game tree after `delay` seconds. -class RemoveEffect extends ComponentEffect { - RemoveEffect({ - double delay = 0.0, - super.onComplete, - super.key, - }) : super( - LinearEffectController(delay), - ); +class RemoveEffect({ + double delay = 0.0, + super.onComplete, + super.key, +}) extends ComponentEffect { + this + : super( + LinearEffectController(delay), + ); @override void apply(double progress) { diff --git a/packages/flame/lib/src/effects/rotate_around_effect.dart b/packages/flame/lib/src/effects/rotate_around_effect.dart index 40bb9c9b202..0b8d44e0373 100644 --- a/packages/flame/lib/src/effects/rotate_around_effect.dart +++ b/packages/flame/lib/src/effects/rotate_around_effect.dart @@ -10,29 +10,23 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// by [center]. The target's angle is by default aligned to the target's /// angle around center, but this can be disabled by setting [alignRotation] to /// false. -class RotateAroundEffect extends Effect - with EffectTarget - implements MeasurableEffect { - RotateAroundEffect( - this.angle, - super.controller, { - required this.center, - this.alignRotation = true, - super.onComplete, - super.key, - }); - +class RotateAroundEffect( /// The magnitude of the effect: how much the target should turn as the /// progress goes from 0 to 1. - final double angle; + final double angle, + super.controller, { /// The center (pivot point) of the rotation. - final Vector2 center; + required final Vector2 center, /// Whether the targets angle should be aligned to the target's current /// rotation around [center]. - final bool alignRotation; - + final bool alignRotation = true, + super.onComplete, + super.key, +}) extends Effect + with EffectTarget + implements MeasurableEffect { @override void apply(double progress) { final dProgress = progress - previousProgress; diff --git a/packages/flame/lib/src/effects/rotate_effect.dart b/packages/flame/lib/src/effects/rotate_effect.dart index abc6f497f9b..31390449947 100644 --- a/packages/flame/lib/src/effects/rotate_effect.dart +++ b/packages/flame/lib/src/effects/rotate_effect.dart @@ -19,16 +19,14 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// This effect applies incremental changes to the component's angle, and /// requires that any other effect or update logic applied to the same component /// also used incremental updates. -class RotateEffect extends Effect - with EffectTarget - implements MeasurableEffect { - RotateEffect.by( - double angle, - super.controller, { - super.onComplete, - super.key, - }) : _angle = angle; - +class RotateEffect.by( + /// The magnitude of the effect: how much the target should turn as the + /// progress goes from 0 to 1. + var double _angle, + super.controller, { + super.onComplete, + super.key, +}) extends Effect with EffectTarget implements MeasurableEffect { factory RotateEffect.to( double angle, EffectController controller, { @@ -43,10 +41,6 @@ class RotateEffect extends Effect ); } - /// The magnitude of the effect: how much the target should turn as the - /// progress goes from 0 to 1. - double _angle; - @override void apply(double progress) { final dProgress = progress - previousProgress; @@ -57,16 +51,15 @@ class RotateEffect extends Effect double measure() => _angle; } -class _RotateToEffect extends RotateEffect { - _RotateToEffect( - double angle, - EffectController controller, { - super.onComplete, - super.key, - }) : _destinationAngle = angle, - super.by(0, controller); +class _RotateToEffect( + double angle, + EffectController controller, { + super.onComplete, + super.key, +}) extends RotateEffect { + this : super.by(0, controller); - final double _destinationAngle; + final double _destinationAngle = angle; @override void onStart() { diff --git a/packages/flame/lib/src/effects/scale_effect.dart b/packages/flame/lib/src/effects/scale_effect.dart index 9bc23e6ebe1..5406853d5c9 100644 --- a/packages/flame/lib/src/effects/scale_effect.dart +++ b/packages/flame/lib/src/effects/scale_effect.dart @@ -15,14 +15,12 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// This effect applies incremental changes to the component's scale, and /// requires that any other effect or update logic applied to the same component /// also used incremental updates. -class ScaleEffect extends Effect with EffectTarget { - ScaleEffect.by( - Vector2 scaleFactor, - super.controller, { - super.onComplete, - super.key, - }) : _scaleFactor = scaleFactor.clone(); - +class ScaleEffect.by( + Vector2 scaleFactor, + super.controller, { + super.onComplete, + super.key, +}) extends Effect with EffectTarget { factory ScaleEffect.to( Vector2 targetScale, EffectController controller, { @@ -35,7 +33,7 @@ class ScaleEffect extends Effect with EffectTarget { key: key, ); - final Vector2 _scaleFactor; + final Vector2 _scaleFactor = scaleFactor.clone(); late Vector2 _scaleDelta; @override @@ -54,19 +52,19 @@ class ScaleEffect extends Effect with EffectTarget { } /// Implementation class for [ScaleEffect.to] -class _ScaleToEffect extends ScaleEffect { - final Vector2 _targetScale; +class _ScaleToEffect( + Vector2 targetScale, + EffectController controller, { + super.onComplete, + super.key, +}) extends ScaleEffect { + final Vector2 _targetScale = targetScale.clone(); - _ScaleToEffect( - Vector2 targetScale, - EffectController controller, { - super.onComplete, - super.key, - }) : _targetScale = targetScale.clone(), - super.by( - Vector2.zero(), - controller, - ); + this + : super.by( + Vector2.zero(), + controller, + ); @override void onStart() { diff --git a/packages/flame/lib/src/effects/sequence_effect.dart b/packages/flame/lib/src/effects/sequence_effect.dart index 6aa24c254e0..1cb9a066524 100644 --- a/packages/flame/lib/src/effects/sequence_effect.dart +++ b/packages/flame/lib/src/effects/sequence_effect.dart @@ -46,28 +46,29 @@ EffectController _createController({ /// [EffectController] as a parameter. This is because the timing of a sequence /// effect depends on the timings of individual effects, and cannot be /// represented as a regular effect controller. -class SequenceEffect extends Effect with CustomTraversal { - SequenceEffect( - List effects, { - bool alternate = false, - bool infinite = false, - int repeatCount = 1, - super.onComplete, - super.key, - }) : assert(effects.isNotEmpty, 'The list of effects cannot be empty'), - assert( - !(infinite && repeatCount != 1), - 'Parameters infinite and repeatCount cannot be specified ' - 'simultaneously', - ), - super( - _createController( - effects: effects, - alternate: alternate, - infinite: infinite, - repeatCount: repeatCount, - ), - ) { +class SequenceEffect( + List effects, { + bool alternate = false, + bool infinite = false, + int repeatCount = 1, + super.onComplete, + super.key, +}) extends Effect with CustomTraversal { + this + : assert(effects.isNotEmpty, 'The list of effects cannot be empty'), + assert( + !(infinite && repeatCount != 1), + 'Parameters infinite and repeatCount cannot be specified ' + 'simultaneously', + ), + super( + _createController( + effects: effects, + alternate: alternate, + infinite: infinite, + repeatCount: repeatCount, + ), + ) { addAll(effects); } @@ -90,18 +91,15 @@ class SequenceEffect extends Effect with CustomTraversal { /// The provided implementation returns a value proportional to the number of /// effects that has already completed, however this is not used anywhere since /// `SequenceEffect.apply()` is empty. -class _SequenceEffectEffectController extends EffectController { - _SequenceEffectEffectController( - this.effects, { - required this.alternate, - }) : super.empty(); - +class _SequenceEffectEffectController( /// The list of children effects. - final List effects; + final List effects, { /// If this flag is true, then after the sequence runs to the end, it will /// run again in the reverse order. - final bool alternate; + required final bool alternate, +}) extends EffectController { + this : super.empty(); /// Index of the currently running effect within the [effects] list. If there /// are n effects in total, then this runs as 0, 1, ..., n-1. After that, if diff --git a/packages/flame/lib/src/effects/size_effect.dart b/packages/flame/lib/src/effects/size_effect.dart index 093c3c1d79c..96349304307 100644 --- a/packages/flame/lib/src/effects/size_effect.dart +++ b/packages/flame/lib/src/effects/size_effect.dart @@ -9,20 +9,20 @@ import 'package:flame/src/effects/provider_interfaces.dart'; /// This effect applies incremental changes to the component's size, and /// requires that any other effect or update logic applied to the same component /// also used incremental updates. -class SizeEffect extends Effect with EffectTarget { +class SizeEffect.by( + Vector2 offset, + super.controller, { + SizeProvider? target, + super.onComplete, + super.key, +}) extends Effect with EffectTarget { /// This constructor will create an effect that sets the size in relation to /// the [PositionComponent]'s current size, for example if the [offset] is /// set to `Vector2(10, -10)` and the size of the affected component is /// `Vector2(100, 100)` at the start of the affected the effect will peak when /// the size is `Vector2(110, 90)`, if there is nothing else affecting the /// size at the same time. - SizeEffect.by( - Vector2 offset, - super.controller, { - SizeProvider? target, - super.onComplete, - super.key, - }) : _offset = offset.clone() { + this { this.target = target; } @@ -44,7 +44,7 @@ class SizeEffect extends Effect with EffectTarget { key: key, ); - Vector2 _offset; + Vector2 _offset = offset.clone(); @override void apply(double progress) { @@ -55,19 +55,19 @@ class SizeEffect extends Effect with EffectTarget { } /// Implementation class for [SizeEffect.to] -class _SizeToEffect extends SizeEffect { - final Vector2 _targetSize; +class _SizeToEffect( + Vector2 targetSize, + EffectController controller, { + super.onComplete, + super.key, +}) extends SizeEffect { + final Vector2 _targetSize = targetSize.clone(); - _SizeToEffect( - Vector2 targetSize, - EffectController controller, { - super.onComplete, - super.key, - }) : _targetSize = targetSize.clone(), - super.by( - Vector2.zero(), - controller, - ); + this + : super.by( + Vector2.zero(), + controller, + ); @override void onStart() { diff --git a/packages/flame/lib/src/effects/transform2d_effect.dart b/packages/flame/lib/src/effects/transform2d_effect.dart index 58cdfdb33bb..243c9bb795e 100644 --- a/packages/flame/lib/src/effects/transform2d_effect.dart +++ b/packages/flame/lib/src/effects/transform2d_effect.dart @@ -11,13 +11,11 @@ import 'package:flame/src/game/transform2d.dart'; /// Currently this class only supports being attached to [PositionComponent]s, /// but in the future it will be extended to work with any [Transform2D]-based /// classes. -abstract class Transform2DEffect extends ComponentEffect { - Transform2DEffect( - super.controller, { - super.onComplete, - super.key, - }); - +abstract class Transform2DEffect( + super.controller, { + super.onComplete, + super.key, +}) extends ComponentEffect { late Transform2D transform; @override diff --git a/packages/flame/lib/src/events/callbacks/input_callbacks.dart b/packages/flame/lib/src/events/callbacks/input_callbacks.dart index 1fbb6a8fd80..582bed53ec9 100644 --- a/packages/flame/lib/src/events/callbacks/input_callbacks.dart +++ b/packages/flame/lib/src/events/callbacks/input_callbacks.dart @@ -1,4 +1,4 @@ /// Marker interface implemented by every input callbacks mixin. /// /// See `PointerInputCallbacks` for the positional subset. -abstract interface class InputCallbacks {} +abstract interface class InputCallbacks(); diff --git a/packages/flame/lib/src/events/callbacks/pointer_input_callbacks.dart b/packages/flame/lib/src/events/callbacks/pointer_input_callbacks.dart index f870aeef453..417af957a88 100644 --- a/packages/flame/lib/src/events/callbacks/pointer_input_callbacks.dart +++ b/packages/flame/lib/src/events/callbacks/pointer_input_callbacks.dart @@ -5,4 +5,4 @@ import 'package:flame/src/events/callbacks/input_callbacks.dart'; /// hit-testing. /// /// Non-positional input, such as keyboard, implements [InputCallbacks]. -abstract interface class PointerInputCallbacks implements InputCallbacks {} +abstract interface class PointerInputCallbacks() implements InputCallbacks; diff --git a/packages/flame/lib/src/events/dispatchers/dispatcher.dart b/packages/flame/lib/src/events/dispatchers/dispatcher.dart index 844591efb94..622a99d0360 100644 --- a/packages/flame/lib/src/events/dispatchers/dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/dispatcher.dart @@ -1,7 +1,8 @@ import 'package:flame/components.dart'; import 'package:flame/src/game/flame_game.dart'; -abstract class Dispatcher extends Component +abstract class Dispatcher() + extends Component with HasGameRef { static void addDispatcher( Component component, diff --git a/packages/flame/lib/src/events/dispatchers/double_tap_dispatcher.dart b/packages/flame/lib/src/events/dispatchers/double_tap_dispatcher.dart index 723c9640da8..fca121093be 100644 --- a/packages/flame/lib/src/events/dispatchers/double_tap_dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/double_tap_dispatcher.dart @@ -3,9 +3,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flutter/gestures.dart'; -class DoubleTapDispatcherKey implements ComponentKey { - const DoubleTapDispatcherKey(); - +class const DoubleTapDispatcherKey() implements ComponentKey { @override int get hashCode => 20260645; // 'DoubleTapDispatcherKey' as hashCode @@ -18,7 +16,7 @@ class DoubleTapDispatcherKey implements ComponentKey { /// the component tree that is mixed with [DoubleTapCallbacks]. This will be /// attached to the [FlameGame] instance automatically whenever any /// [DoubleTapCallbacks] are mounted into the component tree. -class DoubleTapDispatcher extends Dispatcher { +class DoubleTapDispatcher() extends Dispatcher { final _components = {}; void _onDoubleTapDown(DoubleTapDownEvent event) { diff --git a/packages/flame/lib/src/events/dispatchers/long_press_dispatcher.dart b/packages/flame/lib/src/events/dispatchers/long_press_dispatcher.dart index 2455a2f1a3e..bbec9bd1640 100644 --- a/packages/flame/lib/src/events/dispatchers/long_press_dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/long_press_dispatcher.dart @@ -9,7 +9,7 @@ import 'package:meta/meta.dart'; /// that use the [LongPressCallbacks] mixin. It will be attached to the /// [FlameGame] instance automatically whenever any [LongPressCallbacks] /// components are mounted into the component tree. -class LongPressDispatcher extends Dispatcher { +class LongPressDispatcher() extends Dispatcher { /// Records all components currently being long-pressed, keyed by pointerId. final Set> _records = {}; @@ -148,9 +148,7 @@ class LongPressDispatcher extends Dispatcher { } /// Unique key for the [LongPressDispatcher] so the game can identify it. -class LongPressDispatcherKey implements ComponentKey { - const LongPressDispatcherKey(); - +class const LongPressDispatcherKey() implements ComponentKey { @override int get hashCode => 71825634; // arbitrary unique number diff --git a/packages/flame/lib/src/events/dispatchers/mouse_move_dispatcher.dart b/packages/flame/lib/src/events/dispatchers/mouse_move_dispatcher.dart index c3bae912a86..167e5ab0ae7 100644 --- a/packages/flame/lib/src/events/dispatchers/mouse_move_dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/mouse_move_dispatcher.dart @@ -9,7 +9,7 @@ import 'package:meta/meta.dart'; /// [MouseMoveCallbacks] components in the component tree. It will be attached /// to the [FlameGame] instance automatically whenever any /// [MouseMoveCallbacks] components are mounted into the component tree. -class MouseMoveDispatcher extends Dispatcher { +class MouseMoveDispatcher() extends Dispatcher { /// The record of all components currently being hovered. final Set> _records = {}; @@ -82,9 +82,7 @@ class MouseMoveDispatcher extends Dispatcher { } } -class MouseMoveDispatcherKey implements ComponentKey { - const MouseMoveDispatcherKey(); - +class const MouseMoveDispatcherKey() implements ComponentKey { @override int get hashCode => 'MouseMoveDispatcherKey'.hashCode; diff --git a/packages/flame/lib/src/events/dispatchers/multi_drag_scale_dispatcher.dart b/packages/flame/lib/src/events/dispatchers/multi_drag_scale_dispatcher.dart index 2bdc54b2d83..e0fb24be9b6 100644 --- a/packages/flame/lib/src/events/dispatchers/multi_drag_scale_dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/multi_drag_scale_dispatcher.dart @@ -6,9 +6,7 @@ import 'package:flame/src/game/game_render_box.dart'; import 'package:flutter/gestures.dart'; import 'package:meta/meta.dart'; -class MultiDragScaleDispatcherKey implements ComponentKey { - const MultiDragScaleDispatcherKey(); - +class const MultiDragScaleDispatcherKey() implements ComponentKey { @override int get hashCode => 91604875; // 'MultiDragScaleDispatcherKey' as hashCode @@ -24,7 +22,7 @@ class MultiDragScaleDispatcherKey implements ComponentKey { /// Use [enableDrag] and [enableScale] (called via [addDispatcher]) to control /// which event types are forwarded to the underlying /// [MultiDragScaleGestureRecognizer]. -class MultiDragScaleDispatcher extends Dispatcher { +class MultiDragScaleDispatcher() extends Dispatcher { /// The record of all components currently being touched. final Set> _records = {}; @@ -92,9 +90,9 @@ class MultiDragScaleDispatcher extends Dispatcher { required bool hasScale, }) { final game = component.findRootGame()!; - var dispatcher = - game.findByKey(const MultiDragScaleDispatcherKey()) - as MultiDragScaleDispatcher?; + var dispatcher = game.findByKey( + const MultiDragScaleDispatcherKey(), + ) as MultiDragScaleDispatcher?; if (dispatcher == null) { dispatcher = MultiDragScaleDispatcher(); game.registerKey(const MultiDragScaleDispatcherKey(), dispatcher); @@ -119,9 +117,9 @@ class MultiDragScaleDispatcher extends Dispatcher { if (game == null) { return; } - final dispatcher = - game.findByKey(const MultiDragScaleDispatcherKey()) - as MultiDragScaleDispatcher?; + final dispatcher = game.findByKey( + const MultiDragScaleDispatcherKey(), + ) as MultiDragScaleDispatcher?; if (dispatcher == null) { return; } @@ -430,8 +428,11 @@ class MultiDragScaleDispatcher extends Dispatcher { /// dispatcher, in contrast, is shared by the whole game and needs to tell /// pointers apart, so one of these is created per pointer to hold the id and /// attach it to every event that follows. -class _FlameDragAdapter implements Drag { - _FlameDragAdapter(this._dispatcher, Offset startPoint) { +class _FlameDragAdapter( + final MultiDragScaleDispatcher _dispatcher, + Offset startPoint, +) implements Drag { + this { _id = _globalIdCounter++; _dispatcher.handleDragStart( _id, @@ -443,7 +444,6 @@ class _FlameDragAdapter implements Drag { ); } - final MultiDragScaleDispatcher _dispatcher; late final int _id; static int _globalIdCounter = 0; diff --git a/packages/flame/lib/src/events/dispatchers/multi_tap_dispatcher.dart b/packages/flame/lib/src/events/dispatchers/multi_tap_dispatcher.dart index aa01ce1073e..28de9ad3077 100644 --- a/packages/flame/lib/src/events/dispatchers/multi_tap_dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/multi_tap_dispatcher.dart @@ -6,9 +6,7 @@ import 'package:flame/src/game/flame_game.dart'; import 'package:flutter/gestures.dart'; import 'package:meta/meta.dart'; -class MultiTapDispatcherKey implements ComponentKey { - const MultiTapDispatcherKey(); - +class const MultiTapDispatcherKey() implements ComponentKey { @override int get hashCode => 401913931; // 'MultiTapDispatcherKey' as hashCode @@ -17,7 +15,7 @@ class MultiTapDispatcherKey implements ComponentKey { other is MultiTapDispatcherKey && other.hashCode == hashCode; } -class MultiTapDispatcher extends Dispatcher { +class MultiTapDispatcher() extends Dispatcher { /// The record of all components currently being touched. final Set> _record = {}; diff --git a/packages/flame/lib/src/events/dispatchers/non_primary_tap_dispatcher.dart b/packages/flame/lib/src/events/dispatchers/non_primary_tap_dispatcher.dart index 03ec9937169..a840957448a 100644 --- a/packages/flame/lib/src/events/dispatchers/non_primary_tap_dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/non_primary_tap_dispatcher.dart @@ -3,9 +3,7 @@ import 'package:flame/events.dart'; import 'package:flame/game.dart'; import 'package:flutter/gestures.dart'; -class NonPrimaryTapDispatcherKey implements ComponentKey { - const NonPrimaryTapDispatcherKey(); - +class const NonPrimaryTapDispatcherKey() implements ComponentKey { @override int get hashCode => 'NonPrimaryTapDispatcherKey'.hashCode; @@ -20,7 +18,7 @@ class NonPrimaryTapDispatcherKey implements ComponentKey { /// [TertiaryTapCallbacks]. This will be attached to the [FlameGame] instance /// automatically whenever any of those callbacks are mounted into the /// component tree. -class NonPrimaryTapDispatcher extends Dispatcher { +class NonPrimaryTapDispatcher() extends Dispatcher { final _secondaryComponents = {}; final _tertiaryComponents = {}; diff --git a/packages/flame/lib/src/events/dispatchers/scroll_dispatcher.dart b/packages/flame/lib/src/events/dispatchers/scroll_dispatcher.dart index 5d9043bd606..96734c00a19 100644 --- a/packages/flame/lib/src/events/dispatchers/scroll_dispatcher.dart +++ b/packages/flame/lib/src/events/dispatchers/scroll_dispatcher.dart @@ -8,7 +8,7 @@ import 'package:meta/meta.dart'; /// [ScrollCallbacks] components in the component tree. It will be attached /// to the [FlameGame] instance automatically whenever any /// [ScrollCallbacks] components are mounted into the component tree. -class ScrollDispatcher extends Dispatcher { +class ScrollDispatcher() extends Dispatcher { @mustCallSuper void onPointerScroll(ScrollEvent event) { event.deliverAtPoint( @@ -45,9 +45,7 @@ class ScrollDispatcher extends Dispatcher { } /// Unique key for the [ScrollDispatcher] so the game can identify it. -class ScrollDispatcherKey implements ComponentKey { - const ScrollDispatcherKey(); - +class const ScrollDispatcherKey() implements ComponentKey { @override int get hashCode => 'ScrollDispatcherKey'.hashCode; diff --git a/packages/flame/lib/src/events/hardware_keyboard_detector.dart b/packages/flame/lib/src/events/hardware_keyboard_detector.dart index 044812234e7..dc0f281672c 100644 --- a/packages/flame/lib/src/events/hardware_keyboard_detector.dart +++ b/packages/flame/lib/src/events/hardware_keyboard_detector.dart @@ -31,13 +31,11 @@ import 'package:flutter/services.dart'; /// Use [pauseKeyEvents] property to temporarily halt/resume the delivery of /// [onKeyEvent]s. The events will also stop being delivered when the component /// is removed from the component tree. -class HardwareKeyboardDetector extends Component { - HardwareKeyboardDetector({this._onKeyEvent}); - +class HardwareKeyboardDetector({final void Function(KeyEvent)? _onKeyEvent}) + extends Component { final List _physicalKeys = []; Set _logicalKeys = {}; bool _pause = true; - final void Function(KeyEvent)? _onKeyEvent; /// The list of keys that are currently being pressed on the keyboard (or a /// keyboard-like device). The keys are listed in the order in which they diff --git a/packages/flame/lib/src/events/messages/displacement_event.dart b/packages/flame/lib/src/events/messages/displacement_event.dart index 544d0914c93..26612e14a23 100644 --- a/packages/flame/lib/src/events/messages/displacement_event.dart +++ b/packages/flame/lib/src/events/messages/displacement_event.dart @@ -20,15 +20,9 @@ extension DisplacementContextDelta on DisplacementContext { /// This class includes properties that describe both positions where the event /// has occurred (start and end) and the delta (i.e. displacement) represented /// by the event. -abstract class DisplacementEvent - extends LocationContextEvent { - DisplacementEvent( - this._game, { - required super.raw, - required this.deviceStartPosition, - required this.deviceEndPosition, - }); - final Game _game; +abstract class DisplacementEvent( + final Game _game, { + required super.raw, /// Event start position in the coordinate space of the device -- either the /// phone, or the browser window, or the app. @@ -36,8 +30,16 @@ abstract class DisplacementEvent /// If the game runs in a full-screen mode, then this would be equal to the /// [canvasStartPosition]. Otherwise, the [deviceStartPosition] is the /// Flutter-level global position. - final Vector2 deviceStartPosition; + required final Vector2 deviceStartPosition, + /// Event end position in the coordinate space of the device -- either the + /// phone, or the browser window, or the app. + /// + /// If the game runs in a full-screen mode, then this would be equal to the + /// [canvasEndPosition]. Otherwise, the [deviceEndPosition] is the + /// Flutter-level global position. + required final Vector2 deviceEndPosition, +}) extends LocationContextEvent { /// Event start position in the coordinate space of the game widget, i.e. /// relative to the game canvas. /// @@ -54,14 +56,6 @@ abstract class DisplacementEvent /// property at other times. Vector2 get localStartPosition => renderingTrace.last.start; - /// Event end position in the coordinate space of the device -- either the - /// phone, or the browser window, or the app. - /// - /// If the game runs in a full-screen mode, then this would be equal to the - /// [canvasEndPosition]. Otherwise, the [deviceEndPosition] is the - /// Flutter-level global position. - final Vector2 deviceEndPosition; - /// Event end position in the coordinate space of the game widget, i.e. /// relative to the game canvas. /// diff --git a/packages/flame/lib/src/events/messages/double_tap_cancel_event.dart b/packages/flame/lib/src/events/messages/double_tap_cancel_event.dart index 66a5c187087..684206bf419 100644 --- a/packages/flame/lib/src/events/messages/double_tap_cancel_event.dart +++ b/packages/flame/lib/src/events/messages/double_tap_cancel_event.dart @@ -1,5 +1,5 @@ import 'package:flame/events.dart'; -class DoubleTapCancelEvent extends Event { - DoubleTapCancelEvent() : super(raw: null); +class DoubleTapCancelEvent() extends Event { + this : super(raw: null); } diff --git a/packages/flame/lib/src/events/messages/double_tap_down_event.dart b/packages/flame/lib/src/events/messages/double_tap_down_event.dart index 33447438203..3786585c883 100644 --- a/packages/flame/lib/src/events/messages/double_tap_down_event.dart +++ b/packages/flame/lib/src/events/messages/double_tap_down_event.dart @@ -2,12 +2,13 @@ import 'package:flame/events.dart'; import 'package:flame/extensions.dart'; import 'package:flutter/gestures.dart'; -class DoubleTapDownEvent extends PositionEvent { - final PointerDeviceKind deviceKind; +class DoubleTapDownEvent(super.game, TapDownDetails details) + extends PositionEvent { + final PointerDeviceKind deviceKind = + details.kind ?? PointerDeviceKind.unknown; - DoubleTapDownEvent(super.game, TapDownDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( + this + : super( raw: details, devicePosition: details.globalPosition.toVector2(), ); diff --git a/packages/flame/lib/src/events/messages/double_tap_event.dart b/packages/flame/lib/src/events/messages/double_tap_event.dart index f28b3f3b901..ab8b71fb612 100644 --- a/packages/flame/lib/src/events/messages/double_tap_event.dart +++ b/packages/flame/lib/src/events/messages/double_tap_event.dart @@ -1,5 +1,5 @@ import 'package:flame/events.dart'; -class DoubleTapEvent extends Event { - DoubleTapEvent() : super(raw: null); +class DoubleTapEvent() extends Event { + this : super(raw: null); } diff --git a/packages/flame/lib/src/events/messages/drag_cancel_event.dart b/packages/flame/lib/src/events/messages/drag_cancel_event.dart index 83e5e71a6b8..e97b80dd6da 100644 --- a/packages/flame/lib/src/events/messages/drag_cancel_event.dart +++ b/packages/flame/lib/src/events/messages/drag_cancel_event.dart @@ -1,12 +1,12 @@ import 'package:flame/events.dart'; import 'package:flutter/gestures.dart'; -class DragCancelEvent extends Event { - DragCancelEvent(this.pointerId) : super(raw: null); - +class DragCancelEvent( /// The id of the event that has been cancelled. This id corresponds to the /// id of the previous [DragStartEvent]. - final int pointerId; + final int pointerId, +) extends Event { + this : super(raw: null); DragEndEvent toDragEnd() => DragEndEvent(pointerId, DragEndDetails()); diff --git a/packages/flame/lib/src/events/messages/drag_end_event.dart b/packages/flame/lib/src/events/messages/drag_end_event.dart index 7a438909a2b..1455a6d2bb0 100644 --- a/packages/flame/lib/src/events/messages/drag_end_event.dart +++ b/packages/flame/lib/src/events/messages/drag_end_event.dart @@ -2,14 +2,11 @@ import 'package:flame/events.dart'; import 'package:flame/extensions.dart'; import 'package:flutter/gestures.dart'; -class DragEndEvent extends Event { - DragEndEvent(this.pointerId, DragEndDetails details) - : velocity = details.velocity.pixelsPerSecond.toVector2(), - super(raw: details); +class DragEndEvent(final int pointerId, DragEndDetails details) + extends Event { + this : super(raw: details); - final int pointerId; - - final Vector2 velocity; + final Vector2 velocity = details.velocity.pixelsPerSecond.toVector2(); @override String toString() => diff --git a/packages/flame/lib/src/events/messages/drag_start_event.dart b/packages/flame/lib/src/events/messages/drag_start_event.dart index f483b9a99c9..7aad8b76511 100644 --- a/packages/flame/lib/src/events/messages/drag_start_event.dart +++ b/packages/flame/lib/src/events/messages/drag_start_event.dart @@ -6,22 +6,24 @@ import 'package:flutter/gestures.dart'; /// gesture on the game canvas. /// /// This is a [PositionEvent], where the position is the point of touch. -class DragStartEvent extends PositionEvent { - DragStartEvent(this.pointerId, super.game, DragStartDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( - raw: details, - devicePosition: details.globalPosition.toVector2(), - ); - +class DragStartEvent( /// The unique identifier of the drag event. /// /// Subsequent [DragUpdateEvent] or [DragEndEvent] will carry the same pointer /// id. This allows distinguishing multiple drags that may occur at the same /// time on the same component. - final int pointerId; + final int pointerId, + super.game, + DragStartDetails details, +) extends PositionEvent { + this + : super( + raw: details, + devicePosition: details.globalPosition.toVector2(), + ); - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = + details.kind ?? PointerDeviceKind.unknown; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/drag_update_event.dart b/packages/flame/lib/src/events/messages/drag_update_event.dart index 4f1db649508..04efca5392f 100644 --- a/packages/flame/lib/src/events/messages/drag_update_event.dart +++ b/packages/flame/lib/src/events/messages/drag_update_event.dart @@ -2,18 +2,20 @@ import 'package:flame/events.dart'; import 'package:flame/extensions.dart'; import 'package:flutter/gestures.dart'; -class DragUpdateEvent extends DisplacementEvent { - DragUpdateEvent(this.pointerId, super.game, DragUpdateDetails details) - : timestamp = details.sourceTimeStamp ?? Duration.zero, - super( +class DragUpdateEvent( + final int pointerId, + super.game, + DragUpdateDetails details, +) extends DisplacementEvent { + this + : super( raw: details, deviceStartPosition: details.globalPosition.toVector2(), deviceEndPosition: details.globalPosition.toVector2() + details.delta.toVector2(), ); - final int pointerId; - final Duration timestamp; + final Duration timestamp = details.sourceTimeStamp ?? Duration.zero; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/event.dart b/packages/flame/lib/src/events/messages/event.dart index 774699ee987..6b7617ac38b 100644 --- a/packages/flame/lib/src/events/messages/event.dart +++ b/packages/flame/lib/src/events/messages/event.dart @@ -10,18 +10,16 @@ import 'package:meta/meta.dart'; /// /// The type parameter [R] represents the type of the original Flutter raw event /// that triggered this Flame event. -abstract class Event { +abstract class Event({ /// The original Flutter raw event that triggered this Flame event. - R raw; - + required var R raw, +}) { /// If this flag is false (default), the event will be delivered to the first /// component that can handle it. If that component sets this flag to true, /// the event will propagate further down the component tree to other eligible /// components. bool continuePropagation = false; - Event({required this.raw}); - @internal void deliverToComponents( Component rootComponent, diff --git a/packages/flame/lib/src/events/messages/location_context_event.dart b/packages/flame/lib/src/events/messages/location_context_event.dart index 17221d1b30c..a20fac30a4a 100644 --- a/packages/flame/lib/src/events/messages/location_context_event.dart +++ b/packages/flame/lib/src/events/messages/location_context_event.dart @@ -7,7 +7,8 @@ import 'package:meta/meta.dart'; /// /// The type parameter [C] is the generalization of the representation used to /// describe the location instance, such as a [Vector2]. -abstract class LocationContextEvent extends Event { +abstract class LocationContextEvent({required super.raw}) + extends Event { /// The stacktrace of coordinates of the event within the components in their /// rendering order. /// @@ -16,8 +17,6 @@ abstract class LocationContextEvent extends Event { /// of each parent component until the root. final List renderingTrace = []; - LocationContextEvent({required super.raw}); - /// The context in the parent's coordinate space, containing start and end /// points. /// diff --git a/packages/flame/lib/src/events/messages/long_press_cancel_event.dart b/packages/flame/lib/src/events/messages/long_press_cancel_event.dart index 3a8260d424b..7ae6aed935d 100644 --- a/packages/flame/lib/src/events/messages/long_press_cancel_event.dart +++ b/packages/flame/lib/src/events/messages/long_press_cancel_event.dart @@ -5,11 +5,11 @@ import 'package:flame/events.dart'; /// /// This may happen if the pointer moves too far before the long press /// duration elapses, or if the gesture is otherwise interrupted. -class LongPressCancelEvent extends Event { - LongPressCancelEvent(this.pointerId) : super(raw: null); - +class LongPressCancelEvent( /// The id of the gesture that was cancelled. - final int pointerId; + final int pointerId, +) extends Event { + this : super(raw: null); @override String toString() => 'LongPressCancelEvent(pointerId: $pointerId)'; diff --git a/packages/flame/lib/src/events/messages/long_press_end_event.dart b/packages/flame/lib/src/events/messages/long_press_end_event.dart index 717efb0e171..02fb2d44512 100644 --- a/packages/flame/lib/src/events/messages/long_press_end_event.dart +++ b/packages/flame/lib/src/events/messages/long_press_end_event.dart @@ -7,19 +7,20 @@ import 'package:flutter/gestures.dart'; /// /// This is a [PositionEvent], where the position is the point where the /// pointer was lifted. -class LongPressEndEvent extends PositionEvent { - LongPressEndEvent(this.pointerId, super.game, LongPressEndDetails details) - : velocity = details.velocity.pixelsPerSecond.toVector2(), - super( +class LongPressEndEvent( + /// The unique identifier for this long press gesture. + final int pointerId, + super.game, + LongPressEndDetails details, +) extends PositionEvent { + this + : super( raw: details, devicePosition: details.globalPosition.toVector2(), ); - /// The unique identifier for this long press gesture. - final int pointerId; - /// The velocity of the pointer at the time the long press ended. - final Vector2 velocity; + final Vector2 velocity = details.velocity.pixelsPerSecond.toVector2(); @override String toString() => diff --git a/packages/flame/lib/src/events/messages/long_press_move_update_event.dart b/packages/flame/lib/src/events/messages/long_press_move_update_event.dart index bb29fa6fa26..45c398e8229 100644 --- a/packages/flame/lib/src/events/messages/long_press_move_update_event.dart +++ b/packages/flame/lib/src/events/messages/long_press_move_update_event.dart @@ -8,30 +8,27 @@ import 'package:flutter/gestures.dart'; /// This is a [DisplacementEvent] whose start/end positions represent a /// frame-to-frame delta, matching the semantics of `DragUpdateEvent`. /// Use [localDelta] to move a component to follow the pointer. -class LongPressMoveUpdateEvent - extends DisplacementEvent { +class LongPressMoveUpdateEvent( + /// The unique identifier for this long press gesture. + final int pointerId, + super.game, + LongPressMoveUpdateDetails details, { + required Offset previousGlobalPosition, +}) extends DisplacementEvent { /// Creates a [LongPressMoveUpdateEvent]. /// /// [previousGlobalPosition] is the global position from the previous /// move-update (or the start position for the first update). This is used /// to compute the frame-to-frame delta. - LongPressMoveUpdateEvent( - this.pointerId, - super.game, - LongPressMoveUpdateDetails details, { - required Offset previousGlobalPosition, - }) : offsetFromOrigin = details.offsetFromOrigin.toVector2(), - super( - raw: details, - deviceStartPosition: previousGlobalPosition.toVector2(), - deviceEndPosition: details.globalPosition.toVector2(), - ); - - /// The unique identifier for this long press gesture. - final int pointerId; + this + : super( + raw: details, + deviceStartPosition: previousGlobalPosition.toVector2(), + deviceEndPosition: details.globalPosition.toVector2(), + ); /// The offset from the initial long press contact point. - final Vector2 offsetFromOrigin; + final Vector2 offsetFromOrigin = details.offsetFromOrigin.toVector2(); @override String toString() => diff --git a/packages/flame/lib/src/events/messages/long_press_start_event.dart b/packages/flame/lib/src/events/messages/long_press_start_event.dart index a4d5842a5c7..dfb6b8cb5f5 100644 --- a/packages/flame/lib/src/events/messages/long_press_start_event.dart +++ b/packages/flame/lib/src/events/messages/long_press_start_event.dart @@ -7,18 +7,20 @@ import 'package:flutter/gestures.dart'; /// to be recognized as a long press). /// /// This is a [PositionEvent], where the position is the point of contact. -class LongPressStartEvent extends PositionEvent { - LongPressStartEvent(this.pointerId, super.game, LongPressStartDetails details) - : super( - raw: details, - devicePosition: details.globalPosition.toVector2(), - ); - +class LongPressStartEvent( /// The unique identifier for this long press gesture. /// /// Subsequent move update, end, or cancel events will carry the same /// pointer id. - final int pointerId; + final int pointerId, + super.game, + LongPressStartDetails details, +) extends PositionEvent { + this + : super( + raw: details, + devicePosition: details.globalPosition.toVector2(), + ); @override String toString() => diff --git a/packages/flame/lib/src/events/messages/mouse_move_event.dart b/packages/flame/lib/src/events/messages/mouse_move_event.dart index e5c8d574165..97fccda77ff 100644 --- a/packages/flame/lib/src/events/messages/mouse_move_event.dart +++ b/packages/flame/lib/src/events/messages/mouse_move_event.dart @@ -3,21 +3,19 @@ import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flutter/services.dart'; -class MouseMoveEvent extends PositionEvent { - MouseMoveEvent( - this.pointerId, - super.game, - PointerHoverEvent rawEvent, - ) : timestamp = rawEvent.timeStamp, - delta = rawEvent.delta.toVector2(), - super( +class MouseMoveEvent( + final int pointerId, + super.game, + PointerHoverEvent rawEvent, +) extends PositionEvent { + this + : super( raw: rawEvent, devicePosition: rawEvent.position.toVector2(), ); - final int pointerId; - final Duration timestamp; - final Vector2 delta; + final Duration timestamp = rawEvent.timeStamp; + final Vector2 delta = rawEvent.delta.toVector2(); static final _nanPoint = Vector2.all(double.nan); diff --git a/packages/flame/lib/src/events/messages/position_event.dart b/packages/flame/lib/src/events/messages/position_event.dart index 163447c24c9..2d73bfb8406 100644 --- a/packages/flame/lib/src/events/messages/position_event.dart +++ b/packages/flame/lib/src/events/messages/position_event.dart @@ -7,10 +7,8 @@ import 'package:flame/game.dart'; /// /// This class includes properties that describe the position where the event /// has occurred. -abstract class PositionEvent extends LocationContextEvent { - PositionEvent(this._game, {required this.devicePosition, required super.raw}); - - final Game _game; +abstract class PositionEvent( + final Game _game, { /// Event position in the coordinate space of the device -- either the phone, /// or the browser window, or the app. @@ -18,8 +16,9 @@ abstract class PositionEvent extends LocationContextEvent { /// If the game runs in a full-screen mode, then this would be equal to the /// [canvasPosition]. Otherwise, the [devicePosition] is the Flutter-level /// global position. - final Vector2 devicePosition; - + required final Vector2 devicePosition, + required super.raw, +}) extends LocationContextEvent { /// Event position in the coordinate space of the game widget, i.e. relative /// to the game canvas. /// diff --git a/packages/flame/lib/src/events/messages/scale_end_event.dart b/packages/flame/lib/src/events/messages/scale_end_event.dart index d8308de3046..5dc9d95576f 100644 --- a/packages/flame/lib/src/events/messages/scale_end_event.dart +++ b/packages/flame/lib/src/events/messages/scale_end_event.dart @@ -3,16 +3,15 @@ import 'package:flame/extensions.dart'; import 'package:flutter/gestures.dart'; /// Event propagated through the Flame engine when a scale gesture ends. -class ScaleEndEvent extends Event { - ScaleEndEvent(this.pointerId, ScaleEndDetails details) - : velocity = details.velocity.pixelsPerSecond.toVector2(), - super(raw: details); - +class ScaleEndEvent( /// The unique identifier of the scale gesture. - final int pointerId; + final int pointerId, + ScaleEndDetails details, +) extends Event { + this : super(raw: details); /// The velocity of the fingers at the end of the scale gesture. - final Vector2 velocity; + final Vector2 velocity = details.velocity.pixelsPerSecond.toVector2(); @override String toString() => diff --git a/packages/flame/lib/src/events/messages/scale_start_event.dart b/packages/flame/lib/src/events/messages/scale_start_event.dart index a8b64360d15..005d749fdd8 100644 --- a/packages/flame/lib/src/events/messages/scale_start_event.dart +++ b/packages/flame/lib/src/events/messages/scale_start_event.dart @@ -7,24 +7,26 @@ import 'package:flutter/gestures.dart'; /// /// This is a [PositionEvent], where the position is the focal point of the /// gesture. -class ScaleStartEvent extends PositionEvent { - ScaleStartEvent(this.pointerId, super.game, ScaleStartDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( - raw: details, - devicePosition: details.focalPoint.toVector2(), - ); - +class ScaleStartEvent( /// The unique identifier of the scale event. /// /// Subsequent [ScaleUpdateEvent] or [ScaleEndEvent] will carry the same /// pointer id. This allows distinguishing multiple simultaneous scale /// gestures. /// - final int pointerId; + final int pointerId, + super.game, + ScaleStartDetails details, +) extends PositionEvent { + this + : super( + raw: details, + devicePosition: details.focalPoint.toVector2(), + ); /// The type of device that initiated the gesture. - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = + details.kind ?? PointerDeviceKind.unknown; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/scale_update_event.dart b/packages/flame/lib/src/events/messages/scale_update_event.dart index 5aae4622c9a..dcc977a7565 100644 --- a/packages/flame/lib/src/events/messages/scale_update_event.dart +++ b/packages/flame/lib/src/events/messages/scale_update_event.dart @@ -4,19 +4,14 @@ import 'package:flutter/gestures.dart'; /// Event propagated through the Flame engine when the user updates a scale /// (pinch/zoom/rotate) gesture on the game canvas. -class ScaleUpdateEvent extends DisplacementEvent { - ScaleUpdateEvent( - this.pointerId, - super.game, - ScaleUpdateDetails details, - ) : scale = details.scale, - horizontalScale = details.horizontalScale, - verticalScale = details.verticalScale, - rotation = details.rotation, - pointerCount = details.pointerCount, - focalPointDelta = details.focalPointDelta.toVector2(), - timestamp = details.sourceTimeStamp ?? Duration.zero, - super( +class ScaleUpdateEvent( + /// Unique identifier of this scale gesture (Flame-level) + final int pointerId, + super.game, + ScaleUpdateDetails details, +) extends DisplacementEvent { + this + : super( raw: details, deviceStartPosition: details.focalPoint.toVector2(), deviceEndPosition: @@ -24,29 +19,26 @@ class ScaleUpdateEvent extends DisplacementEvent { details.focalPointDelta.toVector2(), ); - /// Unique identifier of this scale gesture (Flame-level) - final int pointerId; - /// The instantaneous 2D scale factor (global) - final double scale; + final double scale = details.scale; /// Horizontal-only scale factor - final double horizontalScale; + final double horizontalScale = details.horizontalScale; /// Vertical-only scale factor - final double verticalScale; + final double verticalScale = details.verticalScale; /// Rotation delta in radians - final double rotation; + final double rotation = details.rotation; /// Number of fingers detected during this update - final int pointerCount; + final int pointerCount = details.pointerCount; /// Movement of the pinch center since last frame - final Vector2 focalPointDelta; + final Vector2 focalPointDelta = details.focalPointDelta.toVector2(); /// Timestamp for ordering/debugging - final Duration timestamp; + final Duration timestamp = details.sourceTimeStamp ?? Duration.zero; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/scroll_event.dart b/packages/flame/lib/src/events/messages/scroll_event.dart index 946fb0854a9..d043bf3b358 100644 --- a/packages/flame/lib/src/events/messages/scroll_event.dart +++ b/packages/flame/lib/src/events/messages/scroll_event.dart @@ -7,12 +7,12 @@ import 'package:flutter/gestures.dart' as flutter; /// /// This event includes scroll delta information in addition to the position /// where the scroll occurred. -class ScrollEvent extends PositionEvent { - ScrollEvent( - super.game, - flutter.PointerScrollEvent rawEvent, - ) : scrollDelta = rawEvent.scrollDelta.toVector2(), - super( +class ScrollEvent( + super.game, + flutter.PointerScrollEvent rawEvent, +) extends PositionEvent { + this + : super( raw: rawEvent, devicePosition: rawEvent.position.toVector2(), ); @@ -21,7 +21,7 @@ class ScrollEvent extends PositionEvent { /// /// Positive values indicate scrolling down or to the right, /// negative values indicate scrolling up or to the left. - final Vector2 scrollDelta; + final Vector2 scrollDelta = rawEvent.scrollDelta.toVector2(); @override String toString() => diff --git a/packages/flame/lib/src/events/messages/secondary_tap_cancel_event.dart b/packages/flame/lib/src/events/messages/secondary_tap_cancel_event.dart index 545b34db064..1fe885bf2fe 100644 --- a/packages/flame/lib/src/events/messages/secondary_tap_cancel_event.dart +++ b/packages/flame/lib/src/events/messages/secondary_tap_cancel_event.dart @@ -13,8 +13,8 @@ import 'package:flame/events.dart'; /// /// The [SecondaryTapCancelEvent] will only occur if there was a previous /// [SecondaryTapDownEvent]. -class SecondaryTapCancelEvent extends Event { - SecondaryTapCancelEvent() : super(raw: null); +class SecondaryTapCancelEvent() extends Event { + this : super(raw: null); @override String toString() => 'SecondaryTapCancel()'; diff --git a/packages/flame/lib/src/events/messages/secondary_tap_down_event.dart b/packages/flame/lib/src/events/messages/secondary_tap_down_event.dart index 120855ec611..d72c8c7630d 100644 --- a/packages/flame/lib/src/events/messages/secondary_tap_down_event.dart +++ b/packages/flame/lib/src/events/messages/secondary_tap_down_event.dart @@ -9,15 +9,16 @@ import 'package:flutter/gestures.dart'; /// /// In order for a component to be eligible to receive this event, it must add /// the [SecondaryTapCallbacks] mixin. -class SecondaryTapDownEvent extends PositionEvent { - SecondaryTapDownEvent(super.game, TapDownDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( +class SecondaryTapDownEvent(super.game, TapDownDetails details) + extends PositionEvent { + this + : super( raw: details, devicePosition: details.globalPosition.toVector2(), ); - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = + details.kind ?? PointerDeviceKind.unknown; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/secondary_tap_up_event.dart b/packages/flame/lib/src/events/messages/secondary_tap_up_event.dart index 8518c0a7de8..d2427f1b640 100644 --- a/packages/flame/lib/src/events/messages/secondary_tap_up_event.dart +++ b/packages/flame/lib/src/events/messages/secondary_tap_up_event.dart @@ -10,15 +10,15 @@ import 'package:flutter/gestures.dart'; /// /// The [SecondaryTapUpEvent] will only occur if there was a previous /// [SecondaryTapDownEvent]. -class SecondaryTapUpEvent extends PositionEvent { - SecondaryTapUpEvent(super.game, TapUpDetails details) - : deviceKind = details.kind, - super( +class SecondaryTapUpEvent(super.game, TapUpDetails details) + extends PositionEvent { + this + : super( raw: details, devicePosition: details.globalPosition.toVector2(), ); - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = details.kind; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/tap_cancel_event.dart b/packages/flame/lib/src/events/messages/tap_cancel_event.dart index 0798275e05a..01f736834c0 100644 --- a/packages/flame/lib/src/events/messages/tap_cancel_event.dart +++ b/packages/flame/lib/src/events/messages/tap_cancel_event.dart @@ -12,12 +12,12 @@ import 'package:flame/events.dart'; /// moved away from the point of contact. /// /// The [TapCancelEvent] will only occur if there was a previous [TapDownEvent]. -class TapCancelEvent extends Event { - TapCancelEvent(this.pointerId) : super(raw: null); - +class TapCancelEvent( /// The id of the event that has been cancelled. This id corresponds to the /// id of the previous [TapDownEvent]. - final int pointerId; + final int pointerId, +) extends Event { + this : super(raw: null); @override String toString() => 'TapCancelEvent(pointerId: $pointerId)'; diff --git a/packages/flame/lib/src/events/messages/tap_down_event.dart b/packages/flame/lib/src/events/messages/tap_down_event.dart index 49450887020..f3538f8c054 100644 --- a/packages/flame/lib/src/events/messages/tap_down_event.dart +++ b/packages/flame/lib/src/events/messages/tap_down_event.dart @@ -9,22 +9,24 @@ import 'package:flutter/gestures.dart'; /// /// In order for a component to be eligible to receive this event, it must add /// the [TapCallbacks] mixin. -class TapDownEvent extends PositionEvent { - TapDownEvent(this.pointerId, super.game, TapDownDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( - raw: details, - devicePosition: details.globalPosition.toVector2(), - ); - +class TapDownEvent( /// The unique identifier of the tap event. /// /// Subsequent [TapUpEvent] or [TapCancelEvent] will carry the same pointer /// id. This allows distinguishing multiple taps that may occur simultaneously /// on the same component. - final int pointerId; + final int pointerId, + super.game, + TapDownDetails details, +) extends PositionEvent { + this + : super( + raw: details, + devicePosition: details.globalPosition.toVector2(), + ); - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = + details.kind ?? PointerDeviceKind.unknown; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/tap_up_event.dart b/packages/flame/lib/src/events/messages/tap_up_event.dart index f1e181b441c..e4eecd9a9ce 100644 --- a/packages/flame/lib/src/events/messages/tap_up_event.dart +++ b/packages/flame/lib/src/events/messages/tap_up_event.dart @@ -9,18 +9,19 @@ import 'package:flutter/gestures.dart'; /// has last occurred. /// /// The [TapUpEvent] will only occur if there was a previous [TapDownEvent]. -class TapUpEvent extends PositionEvent { - TapUpEvent(this.pointerId, super.game, TapUpDetails details) - : deviceKind = details.kind, - super( +class TapUpEvent( + /// The id of the previous [TapDownEvent] to which this event corresponds. + final int pointerId, + super.game, + TapUpDetails details, +) extends PositionEvent { + this + : super( raw: details, devicePosition: details.globalPosition.toVector2(), ); - /// The id of the previous [TapDownEvent] to which this event corresponds. - final int pointerId; - - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = details.kind; TapCancelEvent toTapCancel() => TapCancelEvent(pointerId); diff --git a/packages/flame/lib/src/events/messages/tertiary_tap_cancel_event.dart b/packages/flame/lib/src/events/messages/tertiary_tap_cancel_event.dart index b9230426644..3e688435f76 100644 --- a/packages/flame/lib/src/events/messages/tertiary_tap_cancel_event.dart +++ b/packages/flame/lib/src/events/messages/tertiary_tap_cancel_event.dart @@ -13,8 +13,8 @@ import 'package:flame/events.dart'; /// /// The [TertiaryTapCancelEvent] will only occur if there was a previous /// [TertiaryTapDownEvent]. -class TertiaryTapCancelEvent extends Event { - TertiaryTapCancelEvent() : super(raw: null); +class TertiaryTapCancelEvent() extends Event { + this : super(raw: null); @override String toString() => 'TertiaryTapCancel()'; diff --git a/packages/flame/lib/src/events/messages/tertiary_tap_down_event.dart b/packages/flame/lib/src/events/messages/tertiary_tap_down_event.dart index 36af21e530a..cf6a35096a1 100644 --- a/packages/flame/lib/src/events/messages/tertiary_tap_down_event.dart +++ b/packages/flame/lib/src/events/messages/tertiary_tap_down_event.dart @@ -9,15 +9,16 @@ import 'package:flutter/gestures.dart'; /// /// In order for a component to be eligible to receive this event, it must add /// the [TertiaryTapCallbacks] mixin. -class TertiaryTapDownEvent extends PositionEvent { - TertiaryTapDownEvent(super.game, TapDownDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( +class TertiaryTapDownEvent(super.game, TapDownDetails details) + extends PositionEvent { + this + : super( raw: details, devicePosition: details.globalPosition.toVector2(), ); - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = + details.kind ?? PointerDeviceKind.unknown; @override String toString() => diff --git a/packages/flame/lib/src/events/messages/tertiary_tap_up_event.dart b/packages/flame/lib/src/events/messages/tertiary_tap_up_event.dart index 04a92d9709a..61ab39a1206 100644 --- a/packages/flame/lib/src/events/messages/tertiary_tap_up_event.dart +++ b/packages/flame/lib/src/events/messages/tertiary_tap_up_event.dart @@ -10,15 +10,15 @@ import 'package:flutter/gestures.dart'; /// /// The [TertiaryTapUpEvent] will only occur if there was a previous /// [TertiaryTapDownEvent]. -class TertiaryTapUpEvent extends PositionEvent { - TertiaryTapUpEvent(super.game, TapUpDetails details) - : deviceKind = details.kind, - super( +class TertiaryTapUpEvent(super.game, TapUpDetails details) + extends PositionEvent { + this + : super( raw: details, devicePosition: details.globalPosition.toVector2(), ); - final PointerDeviceKind deviceKind; + final PointerDeviceKind deviceKind = details.kind; @override String toString() => diff --git a/packages/flame/lib/src/events/multi_drag_scale_recognizer.dart b/packages/flame/lib/src/events/multi_drag_scale_recognizer.dart index 51ea1528cf5..227bb69e55a 100644 --- a/packages/flame/lib/src/events/multi_drag_scale_recognizer.dart +++ b/packages/flame/lib/src/events/multi_drag_scale_recognizer.dart @@ -1,4 +1,5 @@ import 'dart:math' as math; + import 'package:flutter/gestures.dart'; /// A gesture recognizer that can recognize both individual pointer drags @@ -12,26 +13,26 @@ import 'package:flutter/gestures.dart'; /// /// Use [hasDrag] and [hasScale] to enable only the features needed. Both /// default to false; the dispatcher sets them via enableDrag/enableScale. -class MultiDragScaleGestureRecognizer extends GestureRecognizer { +class MultiDragScaleGestureRecognizer({ + super.debugOwner, + super.supportedDevices, + AllowedButtonsFilter? allowedButtonsFilter, + + /// The threshold for determining when a scale gesture has occurred. + /// Default is 1.05 (5% change in scale). + final double scaleThreshold = 1.05, +}) extends GestureRecognizer { /// Create a gesture recognizer for tracking multi-drag and scale gestures. - MultiDragScaleGestureRecognizer({ - super.debugOwner, - super.supportedDevices, - AllowedButtonsFilter? allowedButtonsFilter, - this.scaleThreshold = 1.05, - }) : super( - allowedButtonsFilter: - allowedButtonsFilter ?? _defaultButtonAcceptBehavior, - ); + this + : super( + allowedButtonsFilter: + allowedButtonsFilter ?? _defaultButtonAcceptBehavior, + ); // Accept the input if, and only if, [kPrimaryButton] is pressed. static bool _defaultButtonAcceptBehavior(int buttons) => buttons == kPrimaryButton; - /// The threshold for determining when a scale gesture has occurred. - /// Default is 1.05 (5% change in scale). - final double scaleThreshold; - /// Whether drag callbacks should fire. Controlled by the dispatcher. bool hasDrag = false; @@ -400,13 +401,13 @@ class MultiDragScaleGestureRecognizer extends GestureRecognizer { /// Groups per-recognizer drag state. Per-pointer state lives in /// [_DragPointerState]. -class _DragState { +class _DragState() { final Map pointers = {}; int get count => pointers.length; } /// Groups all scale-tracking state for a [MultiDragScaleGestureRecognizer]. -class _ScaleState { +class _ScaleState() { bool active = false; Offset? initialFocalPoint; Offset? currentFocalPoint; @@ -441,21 +442,18 @@ class _ScaleState { } } -class _DragPointerState { - _DragPointerState({ - required this.recognizer, - required PointerDownEvent event, - }) : initialPosition = event.position, - currentPosition = event.position, - kind = event.kind { +class _DragPointerState({ + required final MultiDragScaleGestureRecognizer recognizer, + required PointerDownEvent event, +}) { + this { velocityTracker = VelocityTracker.withKind(kind); } - final MultiDragScaleGestureRecognizer recognizer; - final Offset initialPosition; - final PointerDeviceKind kind; + final Offset initialPosition = event.position; + final PointerDeviceKind kind = event.kind; - Offset currentPosition; + Offset currentPosition = event.position; late VelocityTracker velocityTracker; GestureArenaEntry? _arenaEntry; Drag? _drag; @@ -558,16 +556,9 @@ class _DragPointerState { } } -class _LineBetweenPointers { - _LineBetweenPointers({ - required this.pointerStartId, - required this.pointerStartLocation, - required this.pointerEndId, - required this.pointerEndLocation, - }); - - final int pointerStartId; - final Offset pointerStartLocation; - final int pointerEndId; - final Offset pointerEndLocation; -} +class _LineBetweenPointers({ + required final int pointerStartId, + required final Offset pointerStartLocation, + required final int pointerEndId, + required final Offset pointerEndLocation, +}); diff --git a/packages/flame/lib/src/events/tagged_component.dart b/packages/flame/lib/src/events/tagged_component.dart index 38509311ad5..108c53aa9c4 100644 --- a/packages/flame/lib/src/events/tagged_component.dart +++ b/packages/flame/lib/src/events/tagged_component.dart @@ -11,11 +11,10 @@ import 'package:meta/meta.dart'; /// components. @internal @immutable -class TaggedComponent { - const TaggedComponent(this.pointerId, this.component); - final int pointerId; - final T component; - +class const TaggedComponent( + final int pointerId, + final T component, +) { @override int get hashCode => Object.hash(pointerId, component); diff --git a/packages/flame/lib/src/events/tap_config.dart b/packages/flame/lib/src/events/tap_config.dart index 219a3cab6d6..b8c6368f1a5 100644 --- a/packages/flame/lib/src/events/tap_config.dart +++ b/packages/flame/lib/src/events/tap_config.dart @@ -2,9 +2,7 @@ import 'dart:math'; /// [TapConfig] is used to expose specific configurations /// related to the tap dispatcher. -final class TapConfig { - TapConfig._(); - +final class TapConfig._() { static double _longTapDelay = _defaultLongTapDelay; /// The delay (in seconds) after which a tap is considered a long tap. diff --git a/packages/flame/lib/src/experimental/column_component.dart b/packages/flame/lib/src/experimental/column_component.dart index c6140354126..723d18055ff 100644 --- a/packages/flame/lib/src/experimental/column_component.dart +++ b/packages/flame/lib/src/experimental/column_component.dart @@ -31,16 +31,16 @@ import 'package:flutter/rendering.dart'; /// ], /// ); /// ``` -class ColumnComponent extends LinearLayoutComponent { - ColumnComponent({ - super.key, - super.mainAxisAlignment = MainAxisAlignment.start, - super.crossAxisAlignment = CrossAxisAlignment.start, - super.gap = 0.0, - super.size, - super.position, - super.anchor, - super.priority, - super.children, - }) : super(direction: Direction.vertical); +class ColumnComponent({ + super.key, + super.mainAxisAlignment = MainAxisAlignment.start, + super.crossAxisAlignment = CrossAxisAlignment.start, + super.gap = 0.0, + super.size, + super.position, + super.anchor, + super.priority, + super.children, +}) extends LinearLayoutComponent { + this : super(direction: Direction.vertical); } diff --git a/packages/flame/lib/src/experimental/expanded_component.dart b/packages/flame/lib/src/experimental/expanded_component.dart index 2b1e71775a7..e789ff24c16 100644 --- a/packages/flame/lib/src/experimental/expanded_component.dart +++ b/packages/flame/lib/src/experimental/expanded_component.dart @@ -31,16 +31,15 @@ import 'package:flame/experimental.dart'; /// ], /// ); /// ``` -class ExpandedComponent extends SingleLayoutComponent - with ParentIsA { - ExpandedComponent({ - super.key, - super.position, - super.anchor, - super.priority, - super.inflateChild = true, - super.child, - }) : super(size: null); +class ExpandedComponent({ + super.key, + super.position, + super.anchor, + super.priority, + super.inflateChild = true, + super.child, +}) extends SingleLayoutComponent with ParentIsA { + this : super(size: null); @override void setLayoutAxisLength(LayoutAxis axis, double? value) { diff --git a/packages/flame/lib/src/experimental/geometry/shapes/circle.dart b/packages/flame/lib/src/experimental/geometry/shapes/circle.dart index b09ecede6df..8e33b1e45f6 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/circle.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/circle.dart @@ -16,19 +16,14 @@ import 'package:flame/src/math/random_fallback.dart'; /// a [Transform2D] that contains translations, rotations, and uniform scaling. /// Under a generic projection, a circle would turn into an ellipse, however, /// this is currently not implemented. -class Circle extends Shape { - Circle(Vector2 center, double radius) - : assert(radius >= 0, 'Radius cannot be negative: $radius'), - _center = center.clone(), - _radius = radius; +class Circle(Vector2 center, var double _radius) extends Shape { + this : assert(_radius >= 0, 'Radius cannot be negative: $_radius'); @override Vector2 get center => _center; - final Vector2 _center; + final Vector2 _center = center.clone(); double get radius => _radius; - double _radius; - @override Aabb2 get aabb => _aabb ??= _calculateAabb(); Aabb2? _aabb; diff --git a/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart b/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart index 337862ed682..b909cfe3684 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart @@ -15,7 +15,7 @@ import 'package:flame/src/math/tmp_vector2.dart'; /// /// A polygon can be either convex or not, the [containsPoint] method will work /// in both cases, however, the method used with convex polygon is faster. -class Polygon extends Shape { +class Polygon(final List _vertices, {bool? convex}) extends Shape { /// Constructs the polygon from the given list of vertices. /// /// If the list is not in the counter-clockwise order, then it will be @@ -24,8 +24,7 @@ class Polygon extends Shape { /// If the [convex] flag is provided, then it serves as a hint about whether /// the polygon is convex or not. With this flag the user promises that the /// vertices are already in the correct CCW order. - Polygon(this._vertices, {bool? convex}) - : assert(_vertices.length >= 3, 'At least 3 vertices are required') { + this : assert(_vertices.length >= 3, 'At least 3 vertices are required') { _initializeEdges(); if (convex == null) { _ensureProperOrientation(); @@ -61,7 +60,6 @@ class Polygon extends Shape { /// The user should treat this list as read-only and not attempt to modify /// either the list itself or individual points. List get vertices => _vertices; - final List _vertices; /// The edges (sides) of the polygon. /// diff --git a/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart b/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart index 0b1366cab99..9cecd6d2c93 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart @@ -18,12 +18,17 @@ import 'package:flame/src/math/random_fallback.dart'; /// /// The edges of a [Rectangle] can also coincide: the left edge can coincide /// with the right edge, and the top side with the bottom. -class Rectangle extends Shape { +class Rectangle.fromLTRB( + var double _left, + var double _top, + var double _right, + var double _bottom, +) extends Shape { /// Constructs the [Rectangle] from left, top, right and bottom edges. /// /// If the edges are given in the wrong order (e.g. `left` is to the right /// from `right`), then they will be swapped. - Rectangle.fromLTRB(this._left, this._top, this._right, this._bottom) { + this { if (_left > _right) { final tmp = _left; _left = _right; @@ -60,11 +65,6 @@ class Rectangle extends Shape { ); } - double _left; - double _top; - double _right; - double _bottom; - double get left => _left; double get right => _right; double get top => _top; diff --git a/packages/flame/lib/src/experimental/geometry/shapes/rounded_rectangle.dart b/packages/flame/lib/src/experimental/geometry/shapes/rounded_rectangle.dart index 15dce372269..68807867dfd 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/rounded_rectangle.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/rounded_rectangle.dart @@ -11,7 +11,13 @@ import 'package:vector_math/vector_math.dart'; /// /// The rounded parts of the rectangle are symmetrical in x- and y-directions, /// and across all corners. -class RoundedRectangle extends Shape { +class RoundedRectangle.fromLTRBR( + var double _left, + var double _top, + var double _right, + var double _bottom, + var double _radius, +) extends Shape { /// Constructs a [RoundedRectangle] with left, top, right and bottom edges, /// and the given radius. /// @@ -22,13 +28,7 @@ class RoundedRectangle extends Shape { /// it will be reduced so that the rounded edge can fit inside the rectangle. /// In other words, the radius will be adjusted to not exceed the half-width /// or half-height of the rectangle. - RoundedRectangle.fromLTRBR( - this._left, - this._top, - this._right, - this._bottom, - this._radius, - ) : assert(_radius >= 0, 'Radius cannot be negative: $_radius') { + this : assert(_radius >= 0, 'Radius cannot be negative: $_radius') { if (_left > _right) { final tmp = _left; _left = _right; @@ -75,12 +75,6 @@ class RoundedRectangle extends Shape { ); } - double _left; - double _top; - double _right; - double _bottom; - double _radius; - double get left => _left; double get right => _right; double get top => _top; diff --git a/packages/flame/lib/src/experimental/geometry/shapes/shape.dart b/packages/flame/lib/src/experimental/geometry/shapes/shape.dart index c906cee0b43..fc73828410a 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/shape.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/shape.dart @@ -16,7 +16,7 @@ import 'package:vector_math/vector_math.dart'; /// - [Polygon] /// - [Rectangle] /// - [RoundedRectangle] -abstract class Shape { +abstract class Shape() { /// True if the shape is "closed", in the sense that it has an interior. For /// example, a closed shape can be filled with a paint. bool get isClosed => true; diff --git a/packages/flame/lib/src/experimental/layout_component.dart b/packages/flame/lib/src/experimental/layout_component.dart index 0a0cf499998..b979f7ecc45 100644 --- a/packages/flame/lib/src/experimental/layout_component.dart +++ b/packages/flame/lib/src/experimental/layout_component.dart @@ -1,30 +1,27 @@ import 'package:flame/components.dart'; -enum LayoutAxis { - x(0), - y(1); - - const LayoutAxis(this.axisIndex); - +enum LayoutAxis( /// Necessary for use with LinearLayoutComponent's Direction - final int axisIndex; + final int axisIndex, +) { + x(0), + y(1), } -abstract class LayoutComponent extends PositionComponent { - LayoutComponent({ - required super.key, - required super.position, - required Vector2? size, - required super.anchor, - required super.priority, - super.children, - }) : _layoutSizeX = size?.x, - _layoutSizeY = size?.y { +abstract class LayoutComponent({ + required super.key, + required super.position, + required Vector2? size, + required super.anchor, + required super.priority, + super.children, +}) extends PositionComponent { + this { resetSize(); } - double? _layoutSizeX; - double? _layoutSizeY; + double? _layoutSizeX = size?.x; + double? _layoutSizeY = size?.y; double? get layoutSizeX => _layoutSizeX; double? get layoutSizeY => _layoutSizeY; diff --git a/packages/flame/lib/src/experimental/linear_layout_component.dart b/packages/flame/lib/src/experimental/linear_layout_component.dart index 221d2766f65..b7294ae9e72 100644 --- a/packages/flame/lib/src/experimental/linear_layout_component.dart +++ b/packages/flame/lib/src/experimental/linear_layout_component.dart @@ -5,7 +5,7 @@ import 'package:flame/experimental.dart'; import 'package:flame/image_composition.dart'; import 'package:flutter/rendering.dart'; -enum Direction { +enum Direction() { horizontal, vertical; @@ -73,20 +73,21 @@ enum Direction { /// [TextBoxComponent]'s [TextBoxComponent.boxConfig] to a copy such that /// [TextBoxConfig.maxWidth] is set to whatever value any other child's width /// would be set to. -abstract class LinearLayoutComponent extends LayoutComponent { - LinearLayoutComponent({ - required super.key, - required this.direction, - required this._crossAxisAlignment, - required this._mainAxisAlignment, - required this._gap, - required super.size, - required super.position, - required super.priority, - required super.anchor, - required super.children, - }); +abstract class LinearLayoutComponent({ + required super.key, + required final Direction direction, + required var CrossAxisAlignment _crossAxisAlignment, + required var MainAxisAlignment _mainAxisAlignment, + /// This reflects the value set explicitly and naively, without considering + /// the various values of [mainAxisAlignment]. + required var double _gap, + required super.size, + required super.position, + required super.priority, + required super.anchor, + required super.children, +}) extends LayoutComponent { factory LinearLayoutComponent.fromDirection( Direction direction, { CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.start, @@ -121,10 +122,6 @@ abstract class LinearLayoutComponent extends LayoutComponent { } } - final Direction direction; - - CrossAxisAlignment _crossAxisAlignment; - CrossAxisAlignment get crossAxisAlignment { return _crossAxisAlignment; } @@ -134,8 +131,6 @@ abstract class LinearLayoutComponent extends LayoutComponent { _layoutCrossAxis(); } - MainAxisAlignment _mainAxisAlignment; - MainAxisAlignment get mainAxisAlignment { if (isShrinkWrappedIn(direction.mainAxis)) { return MainAxisAlignment.start; @@ -148,10 +143,6 @@ abstract class LinearLayoutComponent extends LayoutComponent { _layoutMainAxis(); } - /// This reflects the value set explicitly and naively, without considering - /// the various values of [mainAxisAlignment]. - double _gap; - /// The gap between components, that will actually be used for positioning. /// If one or more [ExpandedComponent]s exist among the [children], or if /// [mainAxisAlignment] is not a member of [gapOverridingAlignments], then diff --git a/packages/flame/lib/src/experimental/padding_component.dart b/packages/flame/lib/src/experimental/padding_component.dart index f4ef9f925c3..429328f5332 100644 --- a/packages/flame/lib/src/experimental/padding_component.dart +++ b/packages/flame/lib/src/experimental/padding_component.dart @@ -27,22 +27,21 @@ import 'package:flutter/rendering.dart'; /// child: TextComponent(text: 'bar') /// ); /// ``` -class PaddingComponent extends SingleLayoutComponent { - PaddingComponent({ - super.key, - EdgeInsets? padding, - super.anchor, - super.position, - super.priority, - super.size, - super.inflateChild = false, - PositionComponent? child, - }) : _padding = padding ?? EdgeInsets.zero, - super(child: null) { +class PaddingComponent({ + super.key, + EdgeInsets? padding, + super.anchor, + super.position, + super.priority, + super.size, + super.inflateChild = false, + PositionComponent? child, +}) extends SingleLayoutComponent { + this : super(child: null) { this.child = child; } - EdgeInsets _padding; + EdgeInsets _padding = padding ?? EdgeInsets.zero; EdgeInsets get padding => _padding; diff --git a/packages/flame/lib/src/experimental/raycast_result.dart b/packages/flame/lib/src/experimental/raycast_result.dart index c1ce9e306e5..f947b28490e 100644 --- a/packages/flame/lib/src/experimental/raycast_result.dart +++ b/packages/flame/lib/src/experimental/raycast_result.dart @@ -10,17 +10,13 @@ import 'package:flame/src/geometry/ray2.dart'; /// /// NOTE: This class might be subject to breaking changes in an upcoming /// version, to make it possible to calculate the values lazily. -class RaycastResult> { - RaycastResult({ - this._hitbox, - Ray2? reflectionRay, - Vector2? normal, - double? distance, - this._isInsideHitbox = false, - }) : _reflectionRay = reflectionRay ?? Ray2.zero(), - _normal = normal ?? Vector2.zero(), - _distance = distance ?? double.maxFinite; - +class RaycastResult>({ + var T? _hitbox, + Ray2? reflectionRay, + Vector2? normal, + double? distance, + var bool _isInsideHitbox = false, +}) { /// Whether this result has active results in it. /// /// This is used so that the objects in there can continue to live even when @@ -29,20 +25,17 @@ class RaycastResult> { /// Whether the origin of the ray was inside the hitbox. bool get isInsideHitbox => _isInsideHitbox; - bool _isInsideHitbox; - - T? _hitbox; T? get hitbox => isActive ? _hitbox : null; - final Ray2 _reflectionRay; + final Ray2 _reflectionRay = reflectionRay ?? Ray2.zero(); Ray2? get reflectionRay => isActive ? _reflectionRay : null; Vector2? get intersectionPoint => reflectionRay?.origin; - double _distance; + double _distance = distance ?? double.maxFinite; double? get distance => isActive ? _distance : null; - final Vector2 _normal; + final Vector2 _normal = normal ?? Vector2.zero(); Vector2? get normal => isActive ? _normal : null; void reset() => _hitbox = null; diff --git a/packages/flame/lib/src/experimental/row_component.dart b/packages/flame/lib/src/experimental/row_component.dart index b35dd1f8994..a8991efa3e1 100644 --- a/packages/flame/lib/src/experimental/row_component.dart +++ b/packages/flame/lib/src/experimental/row_component.dart @@ -31,16 +31,16 @@ import 'package:flutter/rendering.dart'; /// ], /// ); /// ``` -class RowComponent extends LinearLayoutComponent { - RowComponent({ - super.key, - super.mainAxisAlignment = MainAxisAlignment.start, - super.crossAxisAlignment = CrossAxisAlignment.start, - super.gap = 0.0, - super.size, - super.position, - super.anchor, - super.priority, - super.children, - }) : super(direction: Direction.horizontal); +class RowComponent({ + super.key, + super.mainAxisAlignment = MainAxisAlignment.start, + super.crossAxisAlignment = CrossAxisAlignment.start, + super.gap = 0.0, + super.size, + super.position, + super.anchor, + super.priority, + super.children, +}) extends LinearLayoutComponent { + this : super(direction: Direction.horizontal); } diff --git a/packages/flame/lib/src/experimental/single_layout_component.dart b/packages/flame/lib/src/experimental/single_layout_component.dart index b4259294984..bc6bf1d372e 100644 --- a/packages/flame/lib/src/experimental/single_layout_component.dart +++ b/packages/flame/lib/src/experimental/single_layout_component.dart @@ -12,21 +12,19 @@ import 'package:flame/experimental.dart'; /// /// Setting [child] automatically manages removing the old child from this /// component, as well as adding the new child to this component. -abstract class SingleLayoutComponent extends LayoutComponent { - SingleLayoutComponent({ - required super.key, - required super.position, - required super.anchor, - required super.priority, - required super.size, - required this.inflateChild, - required PositionComponent? child, - }) { +abstract class SingleLayoutComponent({ + required super.key, + required super.position, + required super.anchor, + required super.priority, + required super.size, + required final bool inflateChild, + required PositionComponent? child, +}) extends LayoutComponent { + this { this.child = child; } - final bool inflateChild; - PositionComponent? _child; /// The component that will be positioned by this component. The [child] will diff --git a/packages/flame/lib/src/extensions/fragment_shader.dart b/packages/flame/lib/src/extensions/fragment_shader.dart index a7c06eb4244..a7ae63f2cb3 100644 --- a/packages/flame/lib/src/extensions/fragment_shader.dart +++ b/packages/flame/lib/src/extensions/fragment_shader.dart @@ -57,12 +57,7 @@ extension FragmentShaderExtension on ui.FragmentShader { } /// A helper class that allows you to set uniforms in a more convenient way. -class UniformsSetter { - UniformsSetter(this.shader, this._index); - - int _index; - final ui.FragmentShader shader; - +class UniformsSetter(final ui.FragmentShader shader, var int _index) { void setFloat(double value) { shader.setFloat(_index++, value); } diff --git a/packages/flame/lib/src/extensions/image.dart b/packages/flame/lib/src/extensions/image.dart index 20c345f8d66..89fca5461a2 100644 --- a/packages/flame/lib/src/extensions/image.dart +++ b/packages/flame/lib/src/extensions/image.dart @@ -73,7 +73,7 @@ extension ImageExtension on Image { newPixelData[i + 3] = pixelData[i + 3]; } - return fromPixels(newPixelData, width, height); + return await fromPixels(newPixelData, width, height); } /// Returns the bounding [Rect] of the image. @@ -91,7 +91,7 @@ extension ImageExtension on Image { }) async { assert(amount >= 0 && amount <= 1); - return transformPixels( + return await transformPixels( (color) => color.darken(amount), reversePremultipliedAlpha: reversePremultipliedAlpha, ); @@ -106,7 +106,7 @@ extension ImageExtension on Image { }) async { assert(amount >= 0 && amount <= 1); - return transformPixels( + return await transformPixels( (color) => color.brighten(amount), reversePremultipliedAlpha: reversePremultipliedAlpha, ); diff --git a/packages/flame/lib/src/extensions/path.dart b/packages/flame/lib/src/extensions/path.dart index d8dc00774a9..90b906be5cf 100644 --- a/packages/flame/lib/src/extensions/path.dart +++ b/packages/flame/lib/src/extensions/path.dart @@ -300,16 +300,14 @@ extension PathMetricExtension on PathMetric { /// out to be too far ahead is kept in [_ahead] until the walk reaches it. The /// indices of the corners and of the points where the contour reaches its /// bounds are collected in [anchors]. -class _ContourSampler { - _ContourSampler(this._metric, this._step, this._maxDeviation); - +class _ContourSampler( + final PathMetric _metric, + final double _step, + final double _maxDeviation, +) { static const _maxStepsPerStride = 32; static const _subdivisionsPerStep = 4; - final PathMetric _metric; - final double _step; - final double _maxDeviation; - final List points = []; final List anchors = []; bool isClosed = false; diff --git a/packages/flame/lib/src/flame.dart b/packages/flame/lib/src/flame.dart index 99808f8ab17..48c00a219a4 100644 --- a/packages/flame/lib/src/flame.dart +++ b/packages/flame/lib/src/flame.dart @@ -1,5 +1,3 @@ -library flame; - import 'package:flame/src/cache/assets_cache.dart'; import 'package:flame/src/cache/images.dart'; import 'package:flame/src/device.dart'; @@ -11,7 +9,7 @@ import 'package:flutter/services.dart'; /// You can access shared instances of [AssetsCache], [Images] and [Device]. /// Most games should need only one instance of each, and should use this class /// to manage that reference. -class Flame { +class Flame() { /// Flame asset bundle, defaults to the root bundle but can be globally /// changed. static AssetBundle bundle = rootBundle; diff --git a/packages/flame/lib/src/game/flame_game.dart b/packages/flame/lib/src/game/flame_game.dart index 2968e761c43..b6c0765c1ca 100644 --- a/packages/flame/lib/src/game/flame_game.dart +++ b/packages/flame/lib/src/game/flame_game.dart @@ -35,20 +35,19 @@ import 'package:meta/meta.dart'; /// /// When [W] is specified, a matching world instance **must** be passed to the /// constructor; otherwise, a runtime assertion error is thrown. -class FlameGame extends ComponentTreeRoot +class FlameGame({ + super.children, + W? world, + CameraComponent? camera, +}) extends ComponentTreeRoot with Game, CustomTraversal implements ReadOnlySizeProvider { - FlameGame({ - super.children, - W? world, - CameraComponent? camera, - }) : assert( - world != null || W == World, - 'The generics type $W does not conform to the type of ' - '${world?.runtimeType ?? 'World'}.', - ), - _world = world ?? World() as W, - _camera = camera ?? CameraComponent() { + this + : assert( + world != null || W == World, + 'The generics type $W does not conform to the type of ' + '${world?.runtimeType ?? 'World'}.', + ) { assert( Component.staticGameInstance == null, '$this instantiated, while another game ${Component.staticGameInstance} ' @@ -82,7 +81,7 @@ class FlameGame extends ComponentTreeRoot } } - W _world; + W _world = world ?? World() as W; /// The component that is responsible for rendering your [world]. /// @@ -104,7 +103,7 @@ class FlameGame extends ComponentTreeRoot _camera.world ??= world; } - CameraComponent _camera; + CameraComponent _camera = camera ?? CameraComponent(); @internal late final List notifiers = []; diff --git a/packages/flame/lib/src/game/game.dart b/packages/flame/lib/src/game/game.dart index 1d3742b3394..416b6d7fdc6 100644 --- a/packages/flame/lib/src/game/game.dart +++ b/packages/flame/lib/src/game/game.dart @@ -20,7 +20,7 @@ import 'package:meta/meta.dart'; /// /// Methods [update] and [render] need to be implemented in order to connect /// your class with the internal game loop. -abstract mixin class Game { +abstract mixin class Game() { /// The cache of all images loaded into the game. This defaults to the global /// [Flame.images] cache, but you can replace it with a new cache instance if /// needed. @@ -114,7 +114,7 @@ abstract mixin class Game { return true; }(), ); - return _onLoadFuture; + return await _onLoadFuture; } /// To be used for tests that needs to evaluate the game after it has been @@ -406,7 +406,7 @@ abstract mixin class Game { /// [overlays].remove. /// /// For example: - /// ``` + /// ```dart /// final pauseOverlayIdentifier = 'PauseMenu'; /// overlays.add(pauseOverlayIdentifier); // marks 'PauseMenu' to be rendered. /// overlays.remove(pauseOverlayIdentifier); // hides 'PauseMenu'. diff --git a/packages/flame/lib/src/game/game_loop.dart b/packages/flame/lib/src/game/game_loop.dart index 978282cac9f..b678d73199f 100644 --- a/packages/flame/lib/src/game/game_loop.dart +++ b/packages/flame/lib/src/game/game_loop.dart @@ -13,18 +13,18 @@ import 'package:flutter/scheduler.dart'; /// ... /// gameLoop.dispose(); /// ``` -class GameLoop { - GameLoop(this.callback) { - _ticker = Ticker(_tick); - } - +class GameLoop( /// Function to be called on every Flutter rendering frame. /// /// This function takes a single parameter `dt`, which is the amount of time /// passed since the previous invocation of this function. The time is /// measured in seconds, with microsecond precision. The argument will be /// equal to 0 on first invocation of the callback. - void Function(double dt) callback; + var void Function(double dt) callback, +) { + this { + _ticker = Ticker(_tick); + } /// Total amount of time passed since the game loop was started. /// diff --git a/packages/flame/lib/src/game/game_render_box.dart b/packages/flame/lib/src/game/game_render_box.dart index f9e9e0662b9..d174cedf252 100644 --- a/packages/flame/lib/src/game/game_render_box.dart +++ b/packages/flame/lib/src/game/game_render_box.dart @@ -18,19 +18,13 @@ import 'package:meta/meta.dart'; /// /// Its [children] are the widgets hosted by the [WidgetComponent]s that are /// currently mounted in the game, each wrapped in a [WidgetComponentHost]. -class RenderGameWidget extends MultiChildRenderObjectWidget { - const RenderGameWidget({ - required this.game, - required this.addRepaintBoundary, - required this.behavior, - super.children, - super.key, - }); - - final Game game; - final bool addRepaintBoundary; - final HitTestBehavior behavior; - +class const RenderGameWidget({ + required final Game game, + required final bool addRepaintBoundary, + required final HitTestBehavior behavior, + super.children, + super.key, +}) extends MultiChildRenderObjectWidget { @override RenderBox createRenderObject(BuildContext context) { return GameRenderBox( @@ -51,23 +45,17 @@ class RenderGameWidget extends MultiChildRenderObjectWidget { } } -class GameRenderBox extends RenderBox +class GameRenderBox( + var Game _game, + var BuildContext buildContext, { + required var bool _isRepaintBoundary, + var HitTestBehavior behavior = HitTestBehavior.opaque, +}) extends RenderBox with ContainerRenderObjectMixin, WidgetsBindingObserver { - GameRenderBox( - this._game, - this.buildContext, { - required this._isRepaintBoundary, - this.behavior = HitTestBehavior.opaque, - }); - GameLoop? gameLoop; - BuildContext buildContext; - - Game _game; - Game get game => _game; set game(Game value) { @@ -87,8 +75,6 @@ class GameRenderBox extends RenderBox } } - bool _isRepaintBoundary; - set isRepaintBoundary(bool value) { if (_isRepaintBoundary == value) { return; @@ -100,8 +86,6 @@ class GameRenderBox extends RenderBox @override bool get isRepaintBoundary => _isRepaintBoundary; - HitTestBehavior behavior; - final Map _childByComponent = {}; /// The widgets that were painted during the last paint, in paint order. @@ -418,22 +402,15 @@ class GameRenderBox extends RenderBox } } -class _PaintedWidget { - _PaintedWidget({ - required this.component, - required this.child, - required this.clip, - required this.localTransform, - }); - - final WidgetComponent component; - final RenderBox child; +class _PaintedWidget({ + required final WidgetComponent component, + required final RenderBox child, /// The clip that was active when the widget was painted, in the coordinate /// space of the canvas the game was rendered on. - final Rect clip; + required final Rect clip, /// The transform from the widget's coordinates to the local coordinates of /// the [GameRenderBox]. - final Matrix4 localTransform; -} + required final Matrix4 localTransform, +}); diff --git a/packages/flame/lib/src/game/game_widget/game_widget.dart b/packages/flame/lib/src/game/game_widget/game_widget.dart index 05d3eb94905..46cc6616808 100644 --- a/packages/flame/lib/src/game/game_widget/game_widget.dart +++ b/packages/flame/lib/src/game/game_widget/game_widget.dart @@ -206,7 +206,7 @@ class GameWidget extends StatefulWidget { } } -class GameWidgetState extends State> { +class GameWidgetState() extends State> { late T currentGame; Future get loaderFuture => _loaderFuture ??= (() async { @@ -499,10 +499,9 @@ typedef GameLoadingWidgetBuilder = Widget Function(BuildContext); typedef GameErrorWidgetBuilder = Widget Function(BuildContext, Object error); -typedef OverlayWidgetBuilder = - Widget Function( - BuildContext context, - T game, - ); +typedef OverlayWidgetBuilder = Widget Function( + BuildContext context, + T game, +); typedef GameFactory = T Function(); diff --git a/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart b/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart index d431558bde5..ca0cb2d45c6 100644 --- a/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart +++ b/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart @@ -2,11 +2,8 @@ import 'package:flame/src/game/game.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; -class GestureDetectorBuilder { - GestureDetectorBuilder([this._onChange]); - +class GestureDetectorBuilder([final void Function()? _onChange]) { final Map _factories = {}; - final void Function()? _onChange; /// Registers a gesture recognizer of type [T]. /// diff --git a/packages/flame/lib/src/game/notifying_vector2.dart b/packages/flame/lib/src/game/notifying_vector2.dart index 7c25662931c..c5671a1c59f 100644 --- a/packages/flame/lib/src/game/notifying_vector2.dart +++ b/packages/flame/lib/src/game/notifying_vector2.dart @@ -10,11 +10,11 @@ import 'package:vector_math/vector_math.dart'; /// order to avoid resource leaks. /// /// Direct modification of this vector's [storage] is not allowed. -class NotifyingVector2 extends Vector2 with ChangeNotifier { +class NotifyingVector2.zero() extends Vector2 with ChangeNotifier { factory NotifyingVector2(double x, double y) => NotifyingVector2.zero()..setValues(x, y); - NotifyingVector2.zero() : super.zero(); + this : super.zero(); factory NotifyingVector2.all(double v) => NotifyingVector2.zero()..splat(v); diff --git a/packages/flame/lib/src/game/overlay_manager.dart b/packages/flame/lib/src/game/overlay_manager.dart index c26fd3ad04c..10f6ba7c0b6 100644 --- a/packages/flame/lib/src/game/overlay_manager.dart +++ b/packages/flame/lib/src/game/overlay_manager.dart @@ -7,10 +7,7 @@ import 'package:meta/meta.dart'; /// A helper class used to control the visibility of overlays on a [Game] /// instance. See [Game.overlays]. @internal -class OverlayManager { - OverlayManager(this._game); - - final Game _game; +class OverlayManager(final Game _game) { final List<_OverlayData> _activeOverlays = []; final Map _builders = {}; @@ -150,19 +147,16 @@ class OverlayManager { } } -typedef OverlayBuilderFunction = - Widget Function( - BuildContext context, - Game game, - ); +typedef OverlayBuilderFunction = Widget Function( + BuildContext context, + Game game, +); @immutable -class _OverlayData { - final int priority; - final String name; - - const _OverlayData({required this.priority, required this.name}); - +class const _OverlayData({ + required final int priority, + required final String name, +}) { @override bool operator ==(Object other) => identical(this, other) || diff --git a/packages/flame/lib/src/game/proxy_canvas.dart b/packages/flame/lib/src/game/proxy_canvas.dart index 6552ec8d03d..135178d5ebf 100644 --- a/packages/flame/lib/src/game/proxy_canvas.dart +++ b/packages/flame/lib/src/game/proxy_canvas.dart @@ -28,18 +28,14 @@ import 'package:vector_math/vector_math_64.dart'; /// ancestors of the game render box through layers instead of drawing them on /// the shared canvas. @internal -class ProxyCanvas implements Canvas { - ProxyCanvas(this._canvas) - : _baseSaveCount = _canvas.getSaveCount(), - _initialTransform = _canvas.getTransform(), - _initialClip = _canvas.getDestinationClipBounds() { +class ProxyCanvas(var Canvas _canvas) implements Canvas { + this { _levels.add(_SaveLevel.plain()); } - Canvas _canvas; - int _baseSaveCount; - final Float64List _initialTransform; - final Rect _initialClip; + int _baseSaveCount = _canvas.getSaveCount(); + final Float64List _initialTransform = _canvas.getTransform(); + final Rect _initialClip = _canvas.getDestinationClipBounds(); final List<_SaveLevel> _levels = []; final Matrix4 _scratch = Matrix4.identity(); @@ -385,7 +381,7 @@ class _SaveLevel { } } -abstract class _ClipOperation { +abstract class _ClipOperation() { /// The transform that was accumulated between the previous clip (or the /// start of the save level) and this clip. final Matrix4 transformBefore = Matrix4.identity(); @@ -393,53 +389,37 @@ abstract class _ClipOperation { void apply(Canvas canvas); } -class _ClipRectOperation extends _ClipOperation { - _ClipRectOperation( - this.rect, { - required this.clipOp, - required this.doAntiAlias, - }); - - final Rect rect; - final ClipOp clipOp; - final bool doAntiAlias; - +class _ClipRectOperation( + final Rect rect, { + required final ClipOp clipOp, + required final bool doAntiAlias, +}) extends _ClipOperation { @override void apply(Canvas canvas) { canvas.clipRect(rect, clipOp: clipOp, doAntiAlias: doAntiAlias); } } -class _ClipRRectOperation extends _ClipOperation { - _ClipRRectOperation(this.rrect, {required this.doAntiAlias}); - - final RRect rrect; - final bool doAntiAlias; - +class _ClipRRectOperation(final RRect rrect, {required final bool doAntiAlias}) + extends _ClipOperation { @override void apply(Canvas canvas) { canvas.clipRRect(rrect, doAntiAlias: doAntiAlias); } } -class _ClipRSuperellipseOperation extends _ClipOperation { - _ClipRSuperellipseOperation(this.shape, {required this.doAntiAlias}); - - final RSuperellipse shape; - final bool doAntiAlias; - +class _ClipRSuperellipseOperation( + final RSuperellipse shape, { + required final bool doAntiAlias, +}) extends _ClipOperation { @override void apply(Canvas canvas) { canvas.clipRSuperellipse(shape, doAntiAlias: doAntiAlias); } } -class _ClipPathOperation extends _ClipOperation { - _ClipPathOperation(this.path, {required this.doAntiAlias}); - - final Path path; - final bool doAntiAlias; - +class _ClipPathOperation(final Path path, {required final bool doAntiAlias}) + extends _ClipOperation { @override void apply(Canvas canvas) { canvas.clipPath(path, doAntiAlias: doAntiAlias); diff --git a/packages/flame/lib/src/game/transform2d.dart b/packages/flame/lib/src/game/transform2d.dart index 1ca846ed977..203930f2177 100644 --- a/packages/flame/lib/src/game/transform2d.dart +++ b/packages/flame/lib/src/game/transform2d.dart @@ -28,7 +28,7 @@ import 'package:vector_math/vector_math.dart'; /// for notifications whenever the transform matrix changes. In addition, you /// can subscribe to get notified when individual components of the transform /// change: [position], [scale], and [offset] (but not [angle]). -class Transform2D extends ChangeNotifier { +class Transform2D() extends ChangeNotifier { final Matrix4 _transformMatrix; bool _recalculate; bool _recalculateRotation; @@ -40,7 +40,7 @@ class Transform2D extends ChangeNotifier { final NotifyingVector2 _scale; final NotifyingVector2 _offset; - Transform2D() + this : _transformMatrix = Matrix4.identity(), _recalculate = true, _recalculateRotation = false, diff --git a/packages/flame/lib/src/game/widget_components.dart b/packages/flame/lib/src/game/widget_components.dart index 8be4398d713..9e91bfd255a 100644 --- a/packages/flame/lib/src/game/widget_components.dart +++ b/packages/flame/lib/src/game/widget_components.dart @@ -7,7 +7,7 @@ import 'package:meta/meta.dart'; /// Parent data for the children of [GameRenderBox], linking each child render /// box to the [WidgetComponent] that hosts it. -class WidgetComponentParentData extends ContainerBoxParentData { +class WidgetComponentParentData() extends ContainerBoxParentData { WidgetComponent? component; /// The transform from the child's coordinates to the local coordinates of @@ -22,16 +22,11 @@ class WidgetComponentParentData extends ContainerBoxParentData { /// Wraps the widget of a [WidgetComponent] so that the [GameRenderBox] knows /// which component a child render box belongs to. @internal -class WidgetComponentParentDataWidget - extends ParentDataWidget { - const WidgetComponentParentDataWidget({ - required this.component, - required super.child, - super.key, - }); - - final WidgetComponent component; - +class const WidgetComponentParentDataWidget({ + required final WidgetComponent component, + required super.child, + super.key, +}) extends ParentDataWidget { @override void applyParentData(RenderObject renderObject) { final parentData = renderObject.parentData! as WidgetComponentParentData; @@ -51,16 +46,15 @@ class WidgetComponentParentDataWidget /// rebuilding the whole `GameWidget`, and excludes the subtree from focus and /// semantics while the component is not being painted. @internal -class WidgetComponentHost extends StatefulWidget { - const WidgetComponentHost({required this.component, super.key}); - - final WidgetComponent component; - +class const WidgetComponentHost({ + required final WidgetComponent component, + super.key, +}) extends StatefulWidget { @override State createState() => _WidgetComponentHostState(); } -class _WidgetComponentHostState extends State { +class _WidgetComponentHostState() extends State { bool _rebuildScheduled = false; @override diff --git a/packages/flame/lib/src/geometry/absolute_transform.dart b/packages/flame/lib/src/geometry/absolute_transform.dart index 143fc099849..fa2bbbae004 100644 --- a/packages/flame/lib/src/geometry/absolute_transform.dart +++ b/packages/flame/lib/src/geometry/absolute_transform.dart @@ -7,7 +7,7 @@ import 'package:meta/meta.dart'; /// /// A point maps to `(a * x + c * y + tx, b * x + d * y + ty)`. @internal -class AbsoluteTransform { +class AbsoluteTransform() { double _a = 1; double _b = 0; double _c = 0; diff --git a/packages/flame/lib/src/geometry/line.dart b/packages/flame/lib/src/geometry/line.dart index 7c3ba7f54bc..58f87e3b85d 100644 --- a/packages/flame/lib/src/geometry/line.dart +++ b/packages/flame/lib/src/geometry/line.dart @@ -6,13 +6,7 @@ import 'package:flame/extensions.dart'; /// of ax + by = c. /// /// If you just want to represent a part of a line, look into LineSegment. -class Line { - final double a; - final double b; - final double c; - - const Line(this.a, this.b, this.c); - +class const Line(final double a, final double b, final double c) { Line.fromPoints(Vector2 p1, Vector2 p2) : this( p2.y - p1.y, diff --git a/packages/flame/lib/src/geometry/line_segment.dart b/packages/flame/lib/src/geometry/line_segment.dart index 522150e3722..2c75261c159 100644 --- a/packages/flame/lib/src/geometry/line_segment.dart +++ b/packages/flame/lib/src/geometry/line_segment.dart @@ -6,14 +6,7 @@ import 'package:flame/src/math/solve_quadratic.dart'; /// A [LineSegment] represent a segment of an infinitely long line, it is the /// segment between the [from] and [to] vectors (inclusive). -class LineSegment { - final Vector2 from; - final Vector2 to; - - /// Creates a [LineSegment] given a start ([from]) point and an end ([to]) - /// point. - LineSegment(this.from, this.to); - +class LineSegment(final Vector2 from, final Vector2 to) { /// Creates a [LineSegment] starting at a given a [start] point and following /// a certain [direction] for a given [length]. LineSegment.withLength({ diff --git a/packages/flame/lib/src/geometry/path_component.dart b/packages/flame/lib/src/geometry/path_component.dart index d0bb411a4e1..3bb67ec430f 100644 --- a/packages/flame/lib/src/geometry/path_component.dart +++ b/packages/flame/lib/src/geometry/path_component.dart @@ -15,7 +15,29 @@ import 'package:meta/meta.dart'; /// [PolygonComponent.fromPath] follows a single contour, and they decide /// whether a point is inside of the component. Their vertices are available /// in [polygons]. -class PathComponent extends ShapeComponent { +class PathComponent({ + required Path path, + + /// The step used when sampling the contours of the [path]. + final double sampling = 1.0, + + /// The tolerance used when simplifying the sampled contours; if not given, + /// it is half the [sampling]. + final double? tolerance, + + /// Whether the polygons that lie inside of the largest one are left out. + final bool filter = true, + super.position, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, + super.paint, + super.paintLayers, + super.isSolid, +}) extends ShapeComponent { /// With this constructor you create a [PathComponent] from all the contours /// of the [path]. /// @@ -28,23 +50,7 @@ class PathComponent extends ShapeComponent { /// not become polygons. When [filter] is true, the polygons whose vertices /// all lie inside of the largest polygon are left out too, since they are /// details of the shape that it already covers, like the eyes of a face. - PathComponent({ - required Path path, - this.sampling = 1.0, - this.tolerance, - this.filter = true, - super.position, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - super.paint, - super.paintLayers, - super.isSolid, - }) : path = path.toOrigin, - super(size: path.getBounds().size.toVector2()) { + this : super(size: path.getBounds().size.toVector2()) { _polygons = _polygonsOf( this.path, sampling: sampling, @@ -72,17 +78,7 @@ class PathComponent extends ShapeComponent { } /// The path to display, already rooted at the origin. - final Path path; - - /// The step used when sampling the contours of the [path]. - final double sampling; - - /// The tolerance used when simplifying the sampled contours; if not given, - /// it is half the [sampling]. - final double? tolerance; - - /// Whether the polygons that lie inside of the largest one are left out. - final bool filter; + final Path path = path.toOrigin; late final List> _polygons; @@ -195,8 +191,8 @@ class PathComponent extends ShapeComponent { /// if [rect] is null return all edges as [LineSegment]s. List possibleIntersectionVertices(Rect? rect) { final rectIntersections = []; - if ((rect?.width == 0 || false) || - (rect?.height == 0 || false) || + if ((rect?.width == 0) || + (rect?.height == 0) || width == 0 || height == 0) { return rectIntersections; diff --git a/packages/flame/lib/src/geometry/polygon_component.dart b/packages/flame/lib/src/geometry/polygon_component.dart index 73f79bb56f7..0a46acfb3e9 100644 --- a/packages/flame/lib/src/geometry/polygon_component.dart +++ b/packages/flame/lib/src/geometry/polygon_component.dart @@ -8,8 +8,21 @@ import 'package:flame/geometry.dart'; import 'package:flame/src/geometry/absolute_transform.dart'; import 'package:meta/meta.dart'; -class PolygonComponent extends ShapeComponent { - final List _vertices; +class PolygonComponent( + final List _vertices, { + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.paint, + super.paintLayers, + super.key, + super.isSolid, + bool? shrinkToBounds, +}) extends ShapeComponent { UnmodifiableListView get vertices => UnmodifiableListView(_vertices); // These lists are used to minimize the amount of objects that are created, // and only change the contained object if the cached absolute transform is @@ -17,32 +30,17 @@ class PolygonComponent extends ShapeComponent { late final List _globalVertices; late final List _lineSegments; final Path _path = Path(); - final bool shrinkToBounds; - final bool manuallyPositioned; + final bool shrinkToBounds = shrinkToBounds ?? size == null; + final bool manuallyPositioned = position != null; /// With this constructor you create your [PolygonComponent] from positions /// anywhere in the 2d-space. It will automatically calculate the [size] of /// the Polygon (the bounding box) if no size is given. - PolygonComponent( - this._vertices, { - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.paint, - super.paintLayers, - super.key, - super.isSolid, - bool? shrinkToBounds, - }) : assert( - _vertices.length > 2, - 'Number of vertices are too few to create a polygon', - ), - shrinkToBounds = shrinkToBounds ?? size == null, - manuallyPositioned = position != null { + this + : assert( + _vertices.length > 2, + 'Number of vertices are too few to create a polygon', + ) { refreshVertices(newVertices: _vertices); final verticesLength = _vertices.length; @@ -339,8 +337,8 @@ class PolygonComponent extends ShapeComponent { /// is null return all vertices as [LineSegment]s. List possibleIntersectionVertices(Rect? rect) { final rectIntersections = []; - if ((rect?.width == 0 || false) || - (rect?.height == 0 || false) || + if ((rect?.width == 0) || + (rect?.height == 0) || width == 0 || height == 0) { return rectIntersections; diff --git a/packages/flame/lib/src/geometry/ray2.dart b/packages/flame/lib/src/geometry/ray2.dart index 8c0bab09614..30451e767bf 100644 --- a/packages/flame/lib/src/geometry/ray2.dart +++ b/packages/flame/lib/src/geometry/ray2.dart @@ -7,16 +7,17 @@ import 'package:meta/meta.dart'; /// A ray in the 2d plane. /// /// The [direction] should be normalized. -class Ray2 { - Ray2({required this.origin, required Vector2 direction}) { +class Ray2({ + /// The point where the ray originates from. + required var Vector2 origin, + required Vector2 direction, +}) { + this { this.direction = direction; } Ray2.zero() : this(origin: Vector2.zero(), direction: Vector2(1, 0)); - /// The point where the ray originates from. - Vector2 origin; - /// The normalized direction of the ray. /// /// The values within the direction object should not be updated manually, use diff --git a/packages/flame/lib/src/geometry/shape_component.dart b/packages/flame/lib/src/geometry/shape_component.dart index 3adc82b7b09..a3208e0fd33 100644 --- a/packages/flame/lib/src/geometry/shape_component.dart +++ b/packages/flame/lib/src/geometry/shape_component.dart @@ -6,29 +6,17 @@ import 'package:flame/components.dart'; /// and angle. It can also have an anchor if it shouldn't be rotated around its /// center. /// A point can be determined to be within of outside of a shape. -abstract class ShapeComponent extends PositionComponent with HasPaint { - ShapeComponent({ - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - Paint? paint, - List? paintLayers, - this.isSolid = false, - }) { - this.paint = paint ?? this.paint; - // Only read from this.paintLayers if paintLayers not null to prevent - // unnecessary creation of the paintLayers list. - if (paintLayers != null) { - this.paintLayers = paintLayers; - } - } - - bool renderShape = true; +abstract class ShapeComponent({ + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, + Paint? paint, + List? paintLayers, /// Whether the shape is solid or hollow. /// @@ -40,5 +28,16 @@ abstract class ShapeComponent extends PositionComponent with HasPaint { /// /// This field is not related to how the shape should be rendered, see /// [Paint.style] for that. - bool isSolid; + var bool isSolid = false, +}) extends PositionComponent with HasPaint { + this { + this.paint = paint ?? this.paint; + // Only read from this.paintLayers if paintLayers not null to prevent + // unnecessary creation of the paintLayers list. + if (paintLayers != null) { + this.paintLayers = paintLayers; + } + } + + bool renderShape = true; } diff --git a/packages/flame/lib/src/geometry/shape_intersections.dart b/packages/flame/lib/src/geometry/shape_intersections.dart index ac538846215..31d0c88d942 100644 --- a/packages/flame/lib/src/geometry/shape_intersections.dart +++ b/packages/flame/lib/src/geometry/shape_intersections.dart @@ -7,7 +7,7 @@ import 'package:flame/geometry.dart'; abstract class Intersections< T1 extends ShapeComponent, T2 extends ShapeComponent -> { +>() { List intersect(T1 shapeA, T2 shapeB, {Rect? overlappingRect}); bool supportsShapes(ShapeComponent shapeA, ShapeComponent shapeB) { @@ -81,7 +81,7 @@ Vector2? _vertexOf(PathComponent path) { return path.globalPolygons().firstOrNull?.first; } -class PathPathIntersections +class PathPathIntersections() extends Intersections { /// Returns the intersection points of the edges of all the polygons of /// [pathA] and [pathB]. @@ -102,7 +102,7 @@ class PathPathIntersections } } -class PathPolygonIntersections +class PathPolygonIntersections() extends Intersections { /// Returns the intersection points of the edges of all the polygons of /// [path] and the edges of [polygon]. @@ -128,7 +128,7 @@ class PathPolygonIntersections } } -class CirclePathIntersections +class CirclePathIntersections() extends Intersections { /// Returns the intersection points of [circle] and the edges of all the /// polygons of [path]. @@ -158,7 +158,7 @@ class CirclePathIntersections } } -class PolygonPolygonIntersections +class PolygonPolygonIntersections() extends Intersections { /// Returns the intersection points of [polygonA] and [polygonB] /// The polygons can be either convex or concave @@ -202,7 +202,7 @@ class PolygonPolygonIntersections } } -class CirclePolygonIntersections +class CirclePolygonIntersections() extends Intersections { @override List intersect( @@ -245,7 +245,7 @@ class CirclePolygonIntersections static const double _circleBoundsEpsilon = 0.01; } -class CircleCircleIntersections +class CircleCircleIntersections() extends Intersections { @override List intersect( diff --git a/packages/flame/lib/src/image_composition.dart b/packages/flame/lib/src/image_composition.dart index ff86f02e538..478f96b0da3 100644 --- a/packages/flame/lib/src/image_composition.dart +++ b/packages/flame/lib/src/image_composition.dart @@ -11,21 +11,16 @@ export '../extensions.dart'; /// /// **Note:** Composing images is a heavy async operation and should not be /// called inside the game loop. -class ImageComposition { - ImageComposition({ - this.defaultBlendMode = BlendMode.srcOver, - this.defaultAntiAlias = false, - }); - - /// The values that will be used to compose the image - final List<_Fragment> _composes = []; - +class ImageComposition({ /// The [defaultBlendMode] can be used to change how each image will be /// blended onto the composition. Defaults to [BlendMode.srcOver]. - final BlendMode defaultBlendMode; + final BlendMode defaultBlendMode = BlendMode.srcOver, /// The [defaultAntiAlias] can be used to if each image will be anti aliased. - final bool defaultAntiAlias; + final bool defaultAntiAlias = false, +}) { + /// The values that will be used to compose the image + final List<_Fragment> _composes = []; /// Add an image to the [ImageComposition]. /// @@ -149,47 +144,30 @@ class ImageComposition { } @immutable -class _ComposeResult { - const _ComposeResult({ - required this.picture, - required this.width, - required this.height, - }); - - final Picture picture; - final int width; - final int height; -} - -class _Fragment { - _Fragment( - this.image, - this.position, - this.source, - this.angle, - this.anchor, - this.blendMode, { - required this.antiAlias, - }); +class const _ComposeResult({ + required final Picture picture, + required final int width, + required final int height, +}); +class _Fragment( /// The image that will be composed. - final Image image; + final Image image, /// The position where the [image] will be composed. - final Vector2 position; + final Vector2 position, /// The source on the [image] that will be composed. - final Rect source; + final Rect source, /// The angle (in radians) used to rotate the [image] around it's [anchor]. - final double angle; + final double angle, /// The point around which the [image] will be rotated /// (defaults to the centre of the [source]). - final Vector2 anchor; - - final bool antiAlias; + final Vector2 anchor, /// The [BlendMode] that will be used when composing the [image]. - final BlendMode blendMode; -} + final BlendMode blendMode, { + required final bool antiAlias, +}); diff --git a/packages/flame/lib/src/layers/layer.dart b/packages/flame/lib/src/layers/layer.dart index 310eb8efde3..f68728338bc 100644 --- a/packages/flame/lib/src/layers/layer.dart +++ b/packages/flame/lib/src/layers/layer.dart @@ -3,7 +3,7 @@ import 'dart:ui'; import 'package:flame/src/layers/processors.dart'; import 'package:meta/meta.dart'; -abstract class Layer { +abstract class Layer() { List preProcessors = []; List postProcessors = []; @@ -55,8 +55,8 @@ abstract class Layer { void drawLayer(); } -abstract class PreRenderedLayer extends Layer { - PreRenderedLayer() { +abstract class PreRenderedLayer() extends Layer { + this { reRender(); } @@ -67,7 +67,7 @@ abstract class PreRenderedLayer extends Layer { } } -abstract class DynamicLayer extends Layer { +abstract class DynamicLayer() extends Layer { @override void render(Canvas canvas, {double x = 0.0, double y = 0.0}) { beginRendering(); diff --git a/packages/flame/lib/src/layers/processors.dart b/packages/flame/lib/src/layers/processors.dart index 18b830c2cda..9e3470d3c48 100644 --- a/packages/flame/lib/src/layers/processors.dart +++ b/packages/flame/lib/src/layers/processors.dart @@ -1,23 +1,19 @@ import 'dart:ui'; -abstract class LayerProcessor { +abstract class LayerProcessor() { void process(Picture pic, Canvas canvas); } -class ShadowProcessor extends LayerProcessor { - final Paint _shadowPaint; - - final Offset offset; - - ShadowProcessor({ - this.offset = const Offset(10, 10), - double opacity = 0.9, - Color color = const Color(0xFF000000), - }) : _shadowPaint = Paint() - ..colorFilter = ColorFilter.mode( - color.withValues(alpha: opacity), - BlendMode.srcATop, - ); +class ShadowProcessor({ + final Offset offset = const Offset(10, 10), + double opacity = 0.9, + Color color = const Color(0xFF000000), +}) extends LayerProcessor { + final Paint _shadowPaint = Paint() + ..colorFilter = ColorFilter.mode( + color.withValues(alpha: opacity), + BlendMode.srcATop, + ); @override void process(Picture pic, Canvas canvas) { diff --git a/packages/flame/lib/src/layout/align_component.dart b/packages/flame/lib/src/layout/align_component.dart index 8170ba25b79..5ccb4b21632 100644 --- a/packages/flame/lib/src/layout/align_component.dart +++ b/packages/flame/lib/src/layout/align_component.dart @@ -45,21 +45,33 @@ import 'package:flutter/widgets.dart'; /// ), /// ); /// ``` -class AlignComponent extends PositionComponent { +class AlignComponent({ + PositionComponent? child, + Anchor alignment = Anchor.topLeft, + + /// If `null`, then the component's width will be equal to the width of the + /// parent. Otherwise, the width will be equal to the child's width multiplied + /// by this factor. + final double? widthFactor, + + /// If `null`, then the component's height will be equal to the height of the + /// parent. Otherwise, the height will be equal to the child's height + /// multiplied by this factor. + final double? heightFactor, + + /// If `false` (default), then the child's `anchor` will be kept equal to the + /// [alignment] value. If `true`, then the [child] will be allowed to have + /// its own `anchor` value independent from the parent. + final bool keepChildAnchor = false, + super.priority, +}) extends PositionComponent { /// Creates a component that keeps its [child] positioned according to the /// [alignment] within this component's bounding box. /// /// More precisely, the child will be placed at [alignment] relative position /// within the current component's bounding box. The child's anchor will also /// be set to the [alignment], unless [keepChildAnchor] parameter is true. - AlignComponent({ - PositionComponent? child, - Anchor alignment = Anchor.topLeft, - this.widthFactor, - this.heightFactor, - this.keepChildAnchor = false, - super.priority, - }) { + this { this.alignment = alignment; this.child = child; } @@ -95,21 +107,6 @@ class AlignComponent extends PositionComponent { _updateChildPosition(); } - /// If `null`, then the component's width will be equal to the width of the - /// parent. Otherwise, the width will be equal to the child's width multiplied - /// by this factor. - final double? widthFactor; - - /// If `null`, then the component's height will be equal to the height of the - /// parent. Otherwise, the height will be equal to the child's height - /// multiplied by this factor. - final double? heightFactor; - - /// If `false` (default), then the child's `anchor` will be kept equal to the - /// [alignment] value. If `true`, then the [child] will be allowed to have - /// its own `anchor` value independent from the parent. - final bool keepChildAnchor; - @override set size(Vector2 value) { throw UnsupportedError('The size of AlignComponent cannot be set directly'); diff --git a/packages/flame/lib/src/math/block.dart b/packages/flame/lib/src/math/block.dart index 7e42518f941..da500c1652b 100644 --- a/packages/flame/lib/src/math/block.dart +++ b/packages/flame/lib/src/math/block.dart @@ -5,15 +5,13 @@ import 'package:meta/meta.dart'; /// /// Represents a position in a 2d-matrix or tilemap. @immutable -class Block { +class const Block( /// x coordinate in the matrix. - final int x; + final int x, /// y coordinate in the matrix. - final int y; - - const Block(this.x, this.y); - + final int y, +) { const Block.zero() : this(0, 0); Block.roundFromVector2(Vector2 position) diff --git a/packages/flame/lib/src/palette.dart b/packages/flame/lib/src/palette.dart index 7610b112957..e66415cd74a 100644 --- a/packages/flame/lib/src/palette.dart +++ b/packages/flame/lib/src/palette.dart @@ -2,13 +2,9 @@ import 'dart:ui'; import 'package:flame/extensions.dart'; -class PaletteEntry { - final Color color; - +class const PaletteEntry(final Color color) { Paint paint() => Paint()..color = color; - const PaletteEntry(this.color); - PaletteEntry withAlpha(int alpha) { return PaletteEntry(color.withAlpha(alpha)); } @@ -34,7 +30,7 @@ class PaletteEntry { } } -class BasicPalette { +class BasicPalette() { static const PaletteEntry transparent = PaletteEntry(Color(0x00FFFFFF)); static const PaletteEntry white = PaletteEntry(Color(0xFFFFFFFF)); static const PaletteEntry black = PaletteEntry(Color(0xFF000000)); diff --git a/packages/flame/lib/src/parallax.dart b/packages/flame/lib/src/parallax.dart index 062edaa51a9..917d7d00bd4 100644 --- a/packages/flame/lib/src/parallax.dart +++ b/packages/flame/lib/src/parallax.dart @@ -98,27 +98,22 @@ extension ParallaxExtension on Game { } } -abstract class ParallaxRenderer { +abstract class ParallaxRenderer({ + ImageRepeat? repeat, + Alignment? alignment, + LayerFill? fill, + FilterQuality? filterQuality, +}) { /// If and how the image should be repeated on the canvas - final ImageRepeat repeat; + final ImageRepeat repeat = repeat ?? ImageRepeat.repeatX; /// How to align the image in relation to the screen - final Alignment alignment; + final Alignment alignment = alignment ?? Alignment.bottomLeft; /// How to fill the screen with the image, always proportionally scaled. - final LayerFill fill; + final LayerFill fill = fill ?? LayerFill.height; - final FilterQuality filterQuality; - - ParallaxRenderer({ - ImageRepeat? repeat, - Alignment? alignment, - LayerFill? fill, - FilterQuality? filterQuality, - }) : repeat = repeat ?? ImageRepeat.repeatX, - alignment = alignment ?? Alignment.bottomLeft, - fill = fill ?? LayerFill.height, - filterQuality = filterQuality ?? FilterQuality.low; + final FilterQuality filterQuality = filterQuality ?? FilterQuality.low; void update(double dt); @@ -127,18 +122,14 @@ abstract class ParallaxRenderer { /// Specifications with a path to an image and how it should be drawn in /// relation to the device screen -class ParallaxImage extends ParallaxRenderer { +class ParallaxImage( /// The image - final Image _image; - - ParallaxImage( - this._image, { - super.repeat, - super.alignment, - super.fill, - super.filterQuality, - }); - + final Image _image, { + super.repeat, + super.alignment, + super.fill, + super.filterQuality, +}) extends ParallaxRenderer { /// Takes the full path of an image, and optionally arguments for how the /// image should repeat ([repeat]), which edge it should align with /// ([alignment]), which axis it should fill the image on ([fill]) and @@ -177,21 +168,18 @@ class ParallaxImage extends ParallaxRenderer { /// Specifications with a SpriteAnimation and how it should be drawn in /// relation to the device screen -class ParallaxAnimation extends ParallaxRenderer { - final SpriteAnimationTicker _animationTicker; +class ParallaxAnimation( + SpriteAnimation animation, /// The animation's frames pre-rendered into images so it can be used in the /// parallax. - final List _prerenderedFrames; - - ParallaxAnimation( - SpriteAnimation animation, - this._prerenderedFrames, { - super.repeat, - super.alignment, - super.fill, - super.filterQuality, - }) : _animationTicker = animation.createTicker(); + final List _prerenderedFrames, { + super.repeat, + super.alignment, + super.fill, + super.filterQuality, +}) extends ParallaxRenderer { + final SpriteAnimationTicker _animationTicker = animation.createTicker(); /// Takes the full path of an image, a SpriteAnimationData, and optionally /// arguments for how the image should repeat ([repeat]), which edge it should @@ -250,8 +238,10 @@ class ParallaxAnimation extends ParallaxRenderer { /// Represents one layer in the parallax, draws out an image on a canvas in the /// manner specified by the parallaxImage. -class ParallaxLayer { - final ParallaxRenderer parallaxRenderer; +class ParallaxLayer( + final ParallaxRenderer parallaxRenderer, { + Vector2? velocityMultiplier, +}) { late Vector2 velocityMultiplier; late Rect _paintArea; final Vector2 _scroll = Vector2.zero(); @@ -262,10 +252,7 @@ class ParallaxLayer { /// the layer should behave. /// [velocityMultiplier] will be used to determine the velocity of the layer /// by multiplying the [Parallax.baseVelocity] with the [velocityMultiplier]. - ParallaxLayer( - this.parallaxRenderer, { - Vector2? velocityMultiplier, - }) : velocityMultiplier = velocityMultiplier ?? Vector2.all(1.0); + this : velocityMultiplier = velocityMultiplier ?? Vector2.all(1.0); Vector2 currentOffset() => _scroll; @@ -377,9 +364,13 @@ class ParallaxLayer { } /// How to fill the screen with the image, always proportionally scaled. -enum LayerFill { height, width, none } +enum LayerFill() { + height, + width, + none, +} -abstract class ParallaxData { +abstract class ParallaxData() { Future load( ImageRepeat repeat, Alignment alignment, @@ -391,11 +382,7 @@ abstract class ParallaxData { } /// Contains the fields and logic to load a [ParallaxImage]. -class ParallaxImageData extends ParallaxData { - final String path; - - ParallaxImageData(this.path); - +class ParallaxImageData(final String path) extends ParallaxData { @override Future load( ImageRepeat repeat, @@ -418,12 +405,10 @@ class ParallaxImageData extends ParallaxData { } /// Contains the fields and logic to load a [ParallaxAnimation]. -class ParallaxAnimationData extends ParallaxData { - final String path; - final SpriteAnimationData animationData; - - ParallaxAnimationData(this.path, this.animationData); - +class ParallaxAnimationData( + final String path, + final SpriteAnimationData animationData, +) extends ParallaxData { @override Future load( ImageRepeat repeat, @@ -448,11 +433,13 @@ class ParallaxAnimationData extends ParallaxData { /// A full parallax, several layers of images drawn out on the screen and each /// layer moves with different velocities to give an effect of depth. -class Parallax { +class Parallax( + final List layers, { + Vector2? size, + Vector2? baseVelocity, +}) { late Vector2 baseVelocity; late Rect _clipRect; - final List layers; - bool isSized = false; late final Vector2 _size; @@ -463,11 +450,7 @@ class Parallax { resize(newSize); } - Parallax( - this.layers, { - Vector2? size, - Vector2? baseVelocity, - }) { + this { this.baseVelocity = baseVelocity ?? Vector2.zero(); if (size != null) { resize(size); diff --git a/packages/flame/lib/src/particles/circle_particle_renderer.dart b/packages/flame/lib/src/particles/circle_particle_renderer.dart index 148e4dc5659..456db8d2224 100644 --- a/packages/flame/lib/src/particles/circle_particle_renderer.dart +++ b/packages/flame/lib/src/particles/circle_particle_renderer.dart @@ -8,24 +8,23 @@ import 'package:flame/src/particles/particle_renderer.dart'; /// A circle texture is rasterized once when the renderer loads; every /// particle is then a transformed, tinted copy of it. The circle's color /// comes from the emitter's `colorOverLife` ramp (white when unset). -class CircleParticleRenderer extends TextureParticleRenderer { +class CircleParticleRenderer({ + /// How much the circle fades out towards its edge, from 0 (crisp) to 1 + /// (fully soft). + final double softness = 0, + super.blendMode, + super.paint, +}) extends TextureParticleRenderer { /// Creates a circle renderer. /// /// [softness] goes from 0 (a crisp edge) to 1 (fully faded from the /// center), which suits smoke and glow, especially combined with /// `blendMode: BlendMode.plus`. - CircleParticleRenderer({ - this.softness = 0, - super.blendMode, - super.paint, - }) : assert( - softness >= 0 && softness <= 1, - 'softness must be between 0 and 1', - ); - - /// How much the circle fades out towards its edge, from 0 (crisp) to 1 - /// (fully soft). - final double softness; + this + : assert( + softness >= 0 && softness <= 1, + 'softness must be between 0 and 1', + ); static const int _textureSize = 64; diff --git a/packages/flame/lib/src/particles/color_ramp.dart b/packages/flame/lib/src/particles/color_ramp.dart index ace910ce88f..5764d649f2a 100644 --- a/packages/flame/lib/src/particles/color_ramp.dart +++ b/packages/flame/lib/src/particles/color_ramp.dart @@ -5,13 +5,13 @@ import 'dart:ui'; /// /// The gradient is baked into a lookup table when constructed, so evaluating /// it per particle per frame is a single array read. -class ColorRamp { +class ColorRamp(List colors, {List? stops}) { /// Creates a ramp that interpolates through [colors] over the particle's /// lifetime. /// /// [stops] optionally positions each color on the 0...1 life progress /// axis; when omitted the colors are spaced evenly. - ColorRamp(List colors, {List? stops}) + this : assert(colors.isNotEmpty, 'colors must not be empty'), assert( stops == null || stops.length == colors.length, diff --git a/packages/flame/lib/src/particles/emitter_shape.dart b/packages/flame/lib/src/particles/emitter_shape.dart index 9c9fab4fb6c..5fc28b37476 100644 --- a/packages/flame/lib/src/particles/emitter_shape.dart +++ b/packages/flame/lib/src/particles/emitter_shape.dart @@ -7,36 +7,26 @@ import 'package:flame/src/geometry/constants.dart'; /// spawn. /// /// Subclass this to spawn particles in custom patterns. -abstract class EmitterShape { - /// Allows subclasses to have const constructors. - const EmitterShape(); - +abstract class const EmitterShape() { /// Writes a spawn offset, relative to the emitter, into [out]. void samplePosition(Random random, Vector2 out); } /// Spawns every particle exactly at the emitter's position. -class PointEmitterShape extends EmitterShape { - /// Spawns every particle exactly at the emitter's position. - const PointEmitterShape(); - +class const PointEmitterShape() extends EmitterShape { @override void samplePosition(Random random, Vector2 out) => out.setZero(); } /// Spawns particles uniformly inside a circle, or on its edge when /// [edgeOnly] is true. -class CircleEmitterShape extends EmitterShape { - /// Spawns particles inside (or on the edge of) a circle with the given - /// [radius]. - const CircleEmitterShape(this.radius, {this.edgeOnly = false}); - +class const CircleEmitterShape( /// The radius of the spawn circle, in local units. - final double radius; + final double radius, { /// When true, particles spawn on the circle's edge instead of inside it. - final bool edgeOnly; - + final bool edgeOnly = false, +}) extends EmitterShape { @override void samplePosition(Random random, Vector2 out) { final angle = random.nextDouble() * tau; @@ -46,16 +36,13 @@ class CircleEmitterShape extends EmitterShape { } /// Spawns particles uniformly inside a rectangle centered on the emitter. -class RectangleEmitterShape extends EmitterShape { - /// Spawns particles inside a centered rectangle of [width] by [height]. - const RectangleEmitterShape(this.width, this.height); - +class const RectangleEmitterShape( /// The width of the spawn rectangle, in local units. - final double width; + final double width, /// The height of the spawn rectangle, in local units. - final double height; - + final double height, +) extends EmitterShape { @override void samplePosition(Random random, Vector2 out) { out.setValues( diff --git a/packages/flame/lib/src/particles/particle_buffer.dart b/packages/flame/lib/src/particles/particle_buffer.dart index 5d5965498f9..80fe490f389 100644 --- a/packages/flame/lib/src/particles/particle_buffer.dart +++ b/packages/flame/lib/src/particles/particle_buffer.dart @@ -9,58 +9,46 @@ import 'dart:typed_data'; /// The particles at indices `0` to `length - 1` are alive. Removing a /// particle swaps the last live particle into its slot, so iteration while /// removing must not advance the index after a removal. -class ParticleBuffer { - /// Creates a buffer with room for [capacity] simultaneous particles. - ParticleBuffer(this.capacity) - : assert(capacity > 0, 'capacity must be positive'), - posX = Float32List(capacity), - posY = Float32List(capacity), - velX = Float32List(capacity), - velY = Float32List(capacity), - age = Float32List(capacity), - invLifespan = Float32List(capacity), - baseSize = Float32List(capacity), - size = Float32List(capacity), - rotation = Float32List(capacity), - spin = Float32List(capacity), - color = Int32List(capacity); - +class ParticleBuffer( /// The maximum number of simultaneous particles. - final int capacity; + final int capacity, +) { + /// Creates a buffer with room for [capacity] simultaneous particles. + this : assert(capacity > 0, 'capacity must be positive'); /// The x position, in the emitter's local coordinate system. - final Float32List posX; + final Float32List posX = Float32List(capacity); /// The y position, in the emitter's local coordinate system. - final Float32List posY; + final Float32List posY = Float32List(capacity); /// The x velocity, in local units per second. - final Float32List velX; + final Float32List velX = Float32List(capacity); /// The y velocity, in local units per second. - final Float32List velY; + final Float32List velY = Float32List(capacity); /// Time in seconds since the particle spawned. - final Float32List age; + final Float32List age = Float32List(capacity); /// The reciprocal of the particle's lifespan; `age[i] * invLifespan[i]` /// is the life progress from 0 (spawn) to 1 (death). - final Float32List invLifespan; + final Float32List invLifespan = Float32List(capacity); /// The size the particle had when it spawned, in local units. - final Float32List baseSize; + final Float32List baseSize = Float32List(capacity); /// The current rendered size (width and height) in local units. - final Float32List size; + final Float32List size = Float32List(capacity); /// The current rotation in radians. - final Float32List rotation; + final Float32List rotation = Float32List(capacity); /// The angular velocity in radians per second. - final Float32List spin; + final Float32List spin = Float32List(capacity); /// The current color as a 32-bit ARGB value. - final Int32List color; + final Int32List color = Int32List(capacity); int _length = 0; diff --git a/packages/flame/lib/src/particles/particle_curve.dart b/packages/flame/lib/src/particles/particle_curve.dart index 7128b66ffac..671d6bdbf07 100644 --- a/packages/flame/lib/src/particles/particle_curve.dart +++ b/packages/flame/lib/src/particles/particle_curve.dart @@ -8,7 +8,7 @@ import 'package:flutter/animation.dart'; /// evaluating it for thousands of particles per frame costs only an array /// read and one interpolation, no matter how expensive the source function /// is. -class ParticleCurve { +class ParticleCurve.custom(double Function(double t) f) { /// Interpolates from [from] at spawn to [to] at death, optionally shaped /// by an animation [curve] (for example [Curves.easeOut]). ParticleCurve(double from, double to, {Curve curve = Curves.linear}) @@ -19,8 +19,7 @@ class ParticleCurve { /// Bakes an arbitrary function of the life progress `t`, where `t` goes /// from 0 at spawn to 1 at death. - ParticleCurve.custom(double Function(double t) f) - : _samples = Float32List(_resolution + 1) { + this : _samples = Float32List(_resolution + 1) { for (var i = 0; i <= _resolution; i++) { _samples[i] = f(i / _resolution); } diff --git a/packages/flame/lib/src/particles/particle_emitter.dart b/packages/flame/lib/src/particles/particle_emitter.dart index 71c8ef2213a..2c0a6bb549d 100644 --- a/packages/flame/lib/src/particles/particle_emitter.dart +++ b/packages/flame/lib/src/particles/particle_emitter.dart @@ -7,17 +7,17 @@ import 'package:flame/src/particles/particle_range.dart'; /// A one-off release of [count] particles, [time] seconds after emission /// starts. -class EmitterBurst { - /// Releases [count] particles [time] seconds after emission starts. - const EmitterBurst(this.time, this.count) - : assert(time >= 0, 'time must not be negative'), - assert(count > 0, 'count must be positive'); - +class const EmitterBurst( /// Seconds after emission start at which the burst fires. - final double time; + final double time, /// The number of particles released by the burst. - final int count; + final int count, +) { + /// Releases [count] particles [time] seconds after emission starts. + this + : assert(time >= 0, 'time must not be negative'), + assert(count > 0, 'count must be positive'); } /// A declarative description of how particles are spawned and how they @@ -26,117 +26,98 @@ class EmitterBurst { /// A [ParticleEmitter] is a reusable preset: the same instance can be shared /// by any number of emitter components. All distances are in the emitter /// component's local units, all angles in radians, and all times in seconds. -class ParticleEmitter { - /// Creates an emitter preset. - /// - /// Emission is continuous through [rate] (particles per second) and/or - /// discrete through [bursts]. An emitter with only bursts finishes after - /// the last burst has fired; an emitter with a positive [rate] keeps - /// emitting until [duration] has passed, or forever when [duration] is - /// null. With [loop] enabled the emission timeline restarts after - /// [duration], which must then be set. - ParticleEmitter({ - this.maxParticles = 1024, - this.rate = 0, - this.bursts = const [], - this.duration, - this.loop = false, - this.lifespan = (1, 1), - this.shape = const PointEmitterShape(), - this.speed = (0, 0), - this.direction = 0, - this.spread = tau, - Vector2? gravity, - this.drag = 0, - this.size = (8, 8), - this.rotation = (0, 0), - this.spin = (0, 0), - this.rotateToVelocity = false, - this.scaleOverLife, - this.opacityOverLife, - this.colorOverLife, - }) : assert(maxParticles > 0, 'maxParticles must be positive'), - assert(rate >= 0, 'rate must not be negative'), - assert(spread >= 0, 'spread must not be negative'), - assert(drag >= 0, 'drag must not be negative'), - assert(duration == null || duration > 0, 'duration must be positive'), - assert( - !loop || duration != null, - 'loop requires duration to be set', - ), - gravity = gravity ?? Vector2.zero(); - +class ParticleEmitter({ /// The maximum number of simultaneous particles. Storage for all of them /// is allocated up front; spawns beyond this limit are dropped until /// older particles die. - final int maxParticles; + final int maxParticles = 1024, /// Particles spawned per second, continuously. Zero means burst-only. - final double rate; + final double rate = 0, /// One-off releases of particles at fixed times on the emission timeline. - final List bursts; + final List bursts = const [], /// How long emission lasts. When null, a [rate]-based emitter emits /// forever, and a burst-only emitter finishes after its last burst. - final double? duration; + final double? duration, /// Whether the emission timeline restarts after [duration]. - final bool loop; + final bool loop = false, /// The lifespan of each particle, in seconds. - final ParticleRange lifespan; + final ParticleRange lifespan = (1, 1), /// The area in which particles spawn, relative to the emitter's position. - final EmitterShape shape; + final EmitterShape shape = const PointEmitterShape(), /// The initial speed of each particle, in local units per second. - final ParticleRange speed; + final ParticleRange speed = (0, 0), /// The center of the emission direction, in radians. Zero points along /// the positive x-axis; `-tau / 4` points up. - final double direction; + final double direction = 0, /// The angle, in radians, over which emission directions are spread, /// centered on [direction]. The default `tau` emits in all directions. - final double spread; - - /// A constant acceleration applied to every particle, in local units per - /// second squared. - final Vector2 gravity; + final double spread = tau, + Vector2? gravity, /// Velocity damping: each second, velocity is scaled by roughly /// `1 / (1 + drag)`. Zero means no damping. - final double drag; + final double drag = 0, /// The rendered size (width and height) of each particle when it spawns, /// in local units. - final ParticleRange size; + final ParticleRange size = (8, 8), /// The initial rotation of each particle, in radians. Ignored when /// [rotateToVelocity] is true. - final ParticleRange rotation; + final ParticleRange rotation = (0, 0), /// The angular velocity of each particle, in radians per second. Ignored /// when [rotateToVelocity] is true. - final ParticleRange spin; + final ParticleRange spin = (0, 0), /// When true, each particle is rotated to point along its velocity, /// which suits directional particles such as sparks or arrows. - final bool rotateToVelocity; + final bool rotateToVelocity = false, /// How the particle's size scales over its lifetime, as a multiplier of /// its spawn [size]. When null the size stays constant. - final ParticleCurve? scaleOverLife; + final ParticleCurve? scaleOverLife, /// How the particle's opacity changes over its lifetime, as a multiplier /// of the alpha from [colorOverLife] (or of full opacity when /// [colorOverLife] is null). Values are clamped to 0...1. - final ParticleCurve? opacityOverLife; + final ParticleCurve? opacityOverLife, /// The particle's color over its lifetime. When null, particles are /// white; with texture renderers this leaves the texture untinted. - final ColorRamp? colorOverLife; + final ColorRamp? colorOverLife, +}) { + /// Creates an emitter preset. + /// + /// Emission is continuous through [rate] (particles per second) and/or + /// discrete through [bursts]. An emitter with only bursts finishes after + /// the last burst has fired; an emitter with a positive [rate] keeps + /// emitting until [duration] has passed, or forever when [duration] is + /// null. With [loop] enabled the emission timeline restarts after + /// [duration], which must then be set. + this + : assert(maxParticles > 0, 'maxParticles must be positive'), + assert(rate >= 0, 'rate must not be negative'), + assert(spread >= 0, 'spread must not be negative'), + assert(drag >= 0, 'drag must not be negative'), + assert(duration == null || duration > 0, 'duration must be positive'), + assert( + !loop || duration != null, + 'loop requires duration to be set', + ); + + /// A constant acceleration applied to every particle, in local units per + /// second squared. + final Vector2 gravity = gravity ?? Vector2.zero(); /// The time at which emission naturally ends: [duration] when set, /// infinity for an endless [rate]-based emitter, and the time of the last diff --git a/packages/flame/lib/src/particles/particle_emitter_component.dart b/packages/flame/lib/src/particles/particle_emitter_component.dart index 95ff72db61d..30600e93356 100644 --- a/packages/flame/lib/src/particles/particle_emitter_component.dart +++ b/packages/flame/lib/src/particles/particle_emitter_component.dart @@ -37,63 +37,49 @@ import 'package:flame/src/particles/particle_renderer.dart'; /// the component moves all live particles with it. Set [worldSpace] to true /// to leave already-spawned particles behind instead, which is what trails /// and exhaust effects want. -class ParticleEmitterComponent extends PositionComponent { - /// Creates a particle emitter component. - /// - /// [emitter] describes what to spawn and how it behaves; [renderer] - /// describes how it is drawn. When [removeOnFinish] is true (the - /// default), the component removes itself once emission has naturally - /// finished and the last particle has died; endless emitters are never - /// removed automatically. Pass a seeded [random] for deterministic - /// behavior. - ParticleEmitterComponent({ - required this.emitter, - required this.renderer, - this.removeOnFinish = true, - this.worldSpace = false, - bool emitting = true, - Random? random, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }) : // `this._emitting` requires Dart 3.12, but the minimum SDK is 3.11. - // ignore: prefer_initializing_formals - _emitting = emitting, - random = random ?? Random(), - _buffer = ParticleBuffer(emitter.maxParticles), - _burstFired = List.filled(emitter.bursts.length, false); - +/// +/// [emitter] describes what to spawn and how it behaves; [renderer] +/// describes how it is drawn. When [removeOnFinish] is true (the +/// default), the component removes itself once emission has naturally +/// finished and the last particle has died; endless emitters are never +/// removed automatically. Pass a seeded [random] for deterministic +/// behavior. +class ParticleEmitterComponent({ /// The description of what to spawn and how particles behave. - final ParticleEmitter emitter; + required final ParticleEmitter emitter, /// The renderer that draws the live particles. - final ParticleRenderer renderer; + required final ParticleRenderer renderer, /// Whether the component removes itself once emission has finished and no /// particles are alive. - bool removeOnFinish; + var bool removeOnFinish = true, /// When true, live particles keep their world position while the /// component moves, so a moving emitter leaves a trail behind. /// /// Only translation is compensated: ancestors of the component (and the /// component itself) should not be rotated or scaled. - final bool worldSpace; - + final bool worldSpace = false, + var bool _emitting = true, + Random? random, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { /// The random source used for all sampling; seed it for determinism. - final Random random; + final Random random = random ?? Random(); - final ParticleBuffer _buffer; - final List _burstFired; + final ParticleBuffer _buffer = ParticleBuffer(emitter.maxParticles); + final List _burstFired = List.filled(emitter.bursts.length, false); final Vector2 _sampledPosition = Vector2.zero(); Vector2? _lastAbsolutePosition; - bool _emitting; bool _completed = false; double _clock = 0; double _emitDebt = 0; diff --git a/packages/flame/lib/src/particles/particle_renderer.dart b/packages/flame/lib/src/particles/particle_renderer.dart index 581870997ae..f9744216ccc 100644 --- a/packages/flame/lib/src/particles/particle_renderer.dart +++ b/packages/flame/lib/src/particles/particle_renderer.dart @@ -9,7 +9,7 @@ import 'package:flame/src/particles/particle_buffer.dart'; /// /// Extend [TextureParticleRenderer] for batched texture rendering, or extend /// this class (or use [CallbackParticleRenderer]) for full canvas access. -abstract class ParticleRenderer { +abstract class ParticleRenderer() { /// Called once when the owning component loads. Override to prepare /// textures or other resources. FutureOr onLoad() {} @@ -24,14 +24,11 @@ abstract class ParticleRenderer { /// /// Nothing is batched, so this is slower than the texture renderers; prefer /// those for large particle counts. -class CallbackParticleRenderer extends ParticleRenderer { - /// Creates a renderer that calls [renderCallback] every frame. - CallbackParticleRenderer(this.renderCallback); - +class CallbackParticleRenderer( /// Called every frame with the canvas, already transformed to the emitter /// component's local coordinate system, and the live particles. - final void Function(Canvas canvas, ParticleBuffer particles) renderCallback; - + final void Function(Canvas canvas, ParticleBuffer particles) renderCallback, +) extends ParticleRenderer { @override void render(Canvas canvas, ParticleBuffer particles) { renderCallback(canvas, particles); @@ -47,21 +44,21 @@ class CallbackParticleRenderer extends ParticleRenderer { /// current size. The particle's color tints the texture through /// [BlendMode.modulate], so white texture pixels take on the particle color /// exactly. -abstract class TextureParticleRenderer extends ParticleRenderer { +abstract class TextureParticleRenderer({BlendMode? blendMode, Paint? paint}) + extends ParticleRenderer { /// Creates a texture renderer. /// /// [blendMode] controls how particles composite onto the canvas; use /// [BlendMode.plus] for additive glow effects. [paint] can be provided to /// customize other paint properties. - TextureParticleRenderer({BlendMode? blendMode, Paint? paint}) - : paint = paint ?? Paint() { + this { if (blendMode != null) { this.paint.blendMode = blendMode; } } /// The paint used for the batched draw call. - final Paint paint; + final Paint paint = paint ?? Paint(); /// The texture to draw, or null while the renderer has not loaded yet. Image? get texture; diff --git a/packages/flame/lib/src/particles/sprite_particle_renderer.dart b/packages/flame/lib/src/particles/sprite_particle_renderer.dart index 1f43ae59e91..e7514039774 100644 --- a/packages/flame/lib/src/particles/sprite_particle_renderer.dart +++ b/packages/flame/lib/src/particles/sprite_particle_renderer.dart @@ -9,10 +9,12 @@ import 'package:flame/src/sprite.dart'; /// The sprite is drawn centered on the particle, scaled so its width matches /// the particle's current size, and tinted by the emitter's `colorOverLife` /// ramp (untinted when unset). -class SpriteParticleRenderer extends TextureParticleRenderer { - /// Renders every particle as [sprite]. - SpriteParticleRenderer(this.sprite, {super.blendMode, super.paint}); - +class SpriteParticleRenderer( + /// The sprite drawn for every particle. + final Sprite sprite, { + super.blendMode, + super.paint, +}) extends TextureParticleRenderer { /// Renders every particle as the full [image]. SpriteParticleRenderer.fromImage( Image image, { @@ -20,9 +22,6 @@ class SpriteParticleRenderer extends TextureParticleRenderer { Paint? paint, }) : this(Sprite(image), blendMode: blendMode, paint: paint); - /// The sprite drawn for every particle. - final Sprite sprite; - @override Image get texture => sprite.image; diff --git a/packages/flame/lib/src/post_process/post_process.dart b/packages/flame/lib/src/post_process/post_process.dart index d3f76f06a35..b7e35de9ee7 100644 --- a/packages/flame/lib/src/post_process/post_process.dart +++ b/packages/flame/lib/src/post_process/post_process.dart @@ -52,17 +52,13 @@ import 'package:meta/meta.dart'; /// shaders /// - [PostProcessingContextFinder] for a way to access the post process /// context from within a component during rendering -abstract class PostProcess { - PostProcess({double? pixelRatio}) - : pixelRatio = - pixelRatio ?? - PlatformDispatcher.instance.views.first.devicePixelRatio; - +abstract class PostProcess({double? pixelRatio}) { /// The pixel ratio of the screen. This is used to scale the image generated /// by [rasterizeSubtree] to the correct size. /// /// Defaults to [FlutterView.devicePixelRatio]. - double pixelRatio; + double pixelRatio = + pixelRatio ?? PlatformDispatcher.instance.views.first.devicePixelRatio; /// Similarly to components, post processes can be loaded asynchronously. /// @@ -183,13 +179,9 @@ abstract class PostProcess { /// - [PostProcessSequentialGroup] for a group of post processes that will be /// applied in sequence where each post process will be considered part of the /// subtree of the next one. -class PostProcessGroup extends PostProcess { - PostProcessGroup({ - required this.postProcesses, - }); - - final List postProcesses; - +class PostProcessGroup({ + required final List postProcesses, +}) extends PostProcess { @override Future onLoad() async { for (final postProcess in postProcesses) { @@ -235,11 +227,9 @@ class PostProcessGroup extends PostProcess { /// - [PostProcessGroup] for a group of post processes that will be applied /// in parallel where all the post processes will be rendered with the same /// subtree. -class PostProcessSequentialGroup extends PostProcessGroup { - PostProcessSequentialGroup({ - required super.postProcesses, - }); - +class PostProcessSequentialGroup({ + required super.postProcesses, +}) extends PostProcessGroup { @override void render( Canvas canvas, diff --git a/packages/flame/lib/src/post_process/post_process_component.dart b/packages/flame/lib/src/post_process/post_process_component.dart index cfa597b261a..d33df59286b 100644 --- a/packages/flame/lib/src/post_process/post_process_component.dart +++ b/packages/flame/lib/src/post_process/post_process_component.dart @@ -29,20 +29,18 @@ import 'package:meta/meta.dart'; /// in parallel /// - [CameraComponent.postProcess] for a way to apply post processes to the /// whole screen. -class PostProcessComponent extends PositionComponent { - PostProcessComponent({ - required this.postProcess, - super.position, - super.size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - }); - +class PostProcessComponent({ + required final T postProcess, + super.position, + super.size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { @override PostProcessComponentRenderContext get renderContext => _renderContext; @@ -50,13 +48,11 @@ class PostProcessComponent extends PositionComponent { postProcess: null, ); - final T postProcess; - @override @mustCallSuper Future onLoad() async { await postProcess.onLoad(); - return super.onLoad(); + await super.onLoad(); } @override @@ -68,7 +64,7 @@ class PostProcessComponent extends PositionComponent { @override @mustCallSuper - void onChildrenChanged(_, __) { + void onChildrenChanged(_, _) { _recalculateBoundingSize(); } @@ -124,14 +120,9 @@ class PostProcessComponent extends PositionComponent { } } -class PostProcessComponentRenderContext - extends ComponentRenderContext { - PostProcessComponentRenderContext({ - required this.postProcess, - }); - - T? postProcess; -} +class PostProcessComponentRenderContext({ + required var T? postProcess, +}) extends ComponentRenderContext; extension PostProcessingContextFinder on Component { T? findPostProcessFromContext() { diff --git a/packages/flame/lib/src/rendering/decorator.dart b/packages/flame/lib/src/rendering/decorator.dart index b9457223ef1..3b2009a9a9e 100644 --- a/packages/flame/lib/src/rendering/decorator.dart +++ b/packages/flame/lib/src/rendering/decorator.dart @@ -27,7 +27,7 @@ import 'package:meta/meta.dart'; /// - [Rotate3DDecorator] /// - [Shadow3DDecorator] /// - [Transform2DDecorator] -class Decorator { +class Decorator() { /// The next decorator in the chain, or null if there is none. Decorator? _next; diff --git a/packages/flame/lib/src/rendering/hue_decorator.dart b/packages/flame/lib/src/rendering/hue_decorator.dart index 7a0f63d6476..6812ceb1dc8 100644 --- a/packages/flame/lib/src/rendering/hue_decorator.dart +++ b/packages/flame/lib/src/rendering/hue_decorator.dart @@ -43,11 +43,8 @@ List hueRotationMatrix(double angle) { /// **Performance Note**: This decorator uses `canvas.saveLayer()` which has /// significant overhead compared to direct [Paint] manipulation (like /// `HueEffect`). Prefer `HueEffect` for high-density rendering. -class HueDecorator extends Decorator { - HueDecorator({this._hue = 0.0}); - +class HueDecorator({var double _hue = 0.0}) extends Decorator { final _paint = Paint(); - double _hue; bool _isDirty = true; /// The hue shift in radians. diff --git a/packages/flame/lib/src/rendering/mutable_transform.dart b/packages/flame/lib/src/rendering/mutable_transform.dart index d8f42c65a40..e85a4ce7d9e 100644 --- a/packages/flame/lib/src/rendering/mutable_transform.dart +++ b/packages/flame/lib/src/rendering/mutable_transform.dart @@ -5,25 +5,23 @@ import 'package:flame/components.dart'; import 'package:flame/effects.dart'; /// A mutable version of [RSTransform] for custom batch manipulation. -class MutableRSTransform implements RSTransform, PositionProvider { - final _values = Float32List(4); +class MutableRSTransform( + double scos, + double ssin, + double tx, + double ty, /// This is a cache of `-scos * anchorX + ssin * anchorY` - final double _anchorX; + final double _anchorX, /// This is a cache of `-ssin * anchorX - scos * anchorY` - final double _anchorY; + final double _anchorY, +) implements RSTransform, PositionProvider { + final _values = Float32List(4); - final Vector2 _position; + final Vector2 _position = Vector2(tx, ty); - MutableRSTransform( - double scos, - double ssin, - double tx, - double ty, - this._anchorX, - this._anchorY, - ) : _position = Vector2(tx, ty) { + this { _values[0] = scos; _values[1] = ssin; _values[2] = tx + _anchorX; diff --git a/packages/flame/lib/src/rendering/rotate3d_decorator.dart b/packages/flame/lib/src/rendering/rotate3d_decorator.dart index a4e812732da..7097c78fe8d 100644 --- a/packages/flame/lib/src/rendering/rotate3d_decorator.dart +++ b/packages/flame/lib/src/rendering/rotate3d_decorator.dart @@ -7,35 +7,29 @@ import 'package:flame/src/rendering/decorator.dart'; /// /// The angles of rotation can be changed dynamically, allowing you to rotate /// the content continuously at the desired angular speeds. -class Rotate3DDecorator extends Decorator { - Rotate3DDecorator({ - Vector2? center, - this.angleX = 0.0, - this.angleY = 0.0, - this.angleZ = 0.0, - this.perspective = 0.001, - }) : center = center ?? Vector2.zero(); - - /// The center of rotation, in the **parent** coordinate space. - Vector2 center; +class Rotate3DDecorator({ + Vector2? center, /// Angle of rotation around the X axis. This rotation is usually described as /// "vertical". - double angleX; + var double angleX = 0.0, /// Angle of rotation around the Y axis. This rotation is typically described /// as "horizontal". - double angleY; + var double angleY = 0.0, /// Angle of rotation around the Z axis. This is a regular "2D" rotation /// because it occurs entirely inside the plane in which the component is /// normally drawn. - double angleZ; + var double angleZ = 0.0, /// The strength of the perspective effect. In other words, how much the /// elements that are "behind" the canvas are shrunk, and those in front of /// it are expanded. - double perspective; + var double perspective = 0.001, +}) extends Decorator { + /// The center of rotation, in the **parent** coordinate space. + Vector2 center = center ?? Vector2.zero(); /// Returns `true` if the component is currently being rendered from its /// back side, and `false` if it shows the front side. diff --git a/packages/flame/lib/src/rendering/shadow3d_decorator.dart b/packages/flame/lib/src/rendering/shadow3d_decorator.dart index 123b8bc766c..4e898177eed 100644 --- a/packages/flame/lib/src/rendering/shadow3d_decorator.dart +++ b/packages/flame/lib/src/rendering/shadow3d_decorator.dart @@ -19,25 +19,16 @@ import 'package:vector_math/vector_math.dart'; /// terrain, so many limitations apply. For example, the shadow must fall on /// the flat ground, having the sun too high in the sky is undesirable as it /// would betray the fact that the component is really flat, etc. -class Shadow3DDecorator extends Decorator { - Shadow3DDecorator({ - Vector2? base, - double? ascent, - double? angle, - double? xShift, - double? yScale, - double? blur, - double? opacity, - Color? baseColor, - }) : _base = base?.clone() ?? Vector2.zero(), - _ascent = ascent ?? 0, - _angle = angle ?? -1.4, - _shift = xShift ?? 100.0, - _scale = yScale ?? 1.0, - _blur = blur ?? 0, - _opacity = opacity ?? 0.6, - _baseColor = baseColor ?? BasicPalette.black.color; - +class Shadow3DDecorator({ + Vector2? base, + double? ascent, + double? angle, + double? xShift, + double? yScale, + double? blur, + double? opacity, + Color? baseColor, +}) extends Decorator { /// Coordinates of the point where the component "touches the ground". If the /// component is airborne (i.e. [ascent] is non-zero), then this should be the /// coordinate of the point where the component would have touched the ground @@ -45,7 +36,7 @@ class Shadow3DDecorator extends Decorator { /// /// This point is in the parent's coordinate space. Vector2 get base => _base; - final Vector2 _base; + final Vector2 _base = base?.clone() ?? Vector2.zero(); set base(Vector2 value) { _base.setFrom(value); _transformMatrix = null; @@ -53,7 +44,7 @@ class Shadow3DDecorator extends Decorator { /// How high is the component above the ground. double get ascent => _ascent; - double _ascent; + double _ascent = ascent ?? 0; set ascent(double value) { _ascent = value; _transformMatrix = null; @@ -67,7 +58,7 @@ class Shadow3DDecorator extends Decorator { /// /// This property should be determined by the meridian position of the sun. double get xShift => _shift; - double _shift; + double _shift = xShift ?? 100.0; set xShift(double value) { _shift = value; _transformMatrix = null; @@ -78,7 +69,7 @@ class Shadow3DDecorator extends Decorator { /// the sky, the scale factor should be less than 1, and when the sun is /// lower, the scale factor ought to be greater than 1. double get yScale => _scale; - double _scale; + double _scale = yScale ?? 1.0; set yScale(double value) { _scale = value; _transformMatrix = null; @@ -90,7 +81,7 @@ class Shadow3DDecorator extends Decorator { /// objects. Use positive angles that are slightly above τ/4 to make shadows /// that are in front of the objects. double get angle => _angle; - double _angle; + double _angle = angle ?? -1.4; set angle(double value) { _angle = value; _transformMatrix = null; @@ -106,7 +97,7 @@ class Shadow3DDecorator extends Decorator { /// of blur proportional to the height of the object, or dependent on its /// ascent above the ground. double get blur => _blur; - double _blur; + double _blur = blur ?? 0; set blur(double value) { _blur = value; _paint = null; @@ -117,7 +108,7 @@ class Shadow3DDecorator extends Decorator { /// a cave). Values close to 0 will make the shadow barely visible, such as /// on a cloudy day. double get opacity => _opacity; - double _opacity; + double _opacity = opacity ?? 0.6; set opacity(double value) { _opacity = value; _paint = null; @@ -125,7 +116,7 @@ class Shadow3DDecorator extends Decorator { /// Shadow's base color before opacity. This defaults to pitch-black. Color get baseColor => _baseColor; - Color _baseColor; + Color _baseColor = baseColor ?? BasicPalette.black.color; set baseColor(Color value) { _baseColor = value; _paint = null; diff --git a/packages/flame/lib/src/rendering/transform2d_decorator.dart b/packages/flame/lib/src/rendering/transform2d_decorator.dart index b73188f045d..115547c409b 100644 --- a/packages/flame/lib/src/rendering/transform2d_decorator.dart +++ b/packages/flame/lib/src/rendering/transform2d_decorator.dart @@ -7,11 +7,8 @@ import 'package:flame/src/rendering/decorator.dart'; /// the canvas. /// /// This decorator is used internally by the [PositionComponent]. -class Transform2DDecorator extends Decorator { - Transform2DDecorator([Transform2D? transform]) - : transform2d = transform ?? Transform2D(); - - final Transform2D transform2d; +class Transform2DDecorator([Transform2D? transform]) extends Decorator { + final Transform2D transform2d = transform ?? Transform2D(); @override void apply(void Function(Canvas) draw, Canvas canvas) { diff --git a/packages/flame/lib/src/sprite.dart b/packages/flame/lib/src/sprite.dart index ff1562daea2..da994efcb47 100644 --- a/packages/flame/lib/src/sprite.dart +++ b/packages/flame/lib/src/sprite.dart @@ -15,16 +15,15 @@ import 'package:flame/src/palette.dart'; /// in the Canvas the sprite is rendered). /// It also has a [paint] field that can be overwritten to apply a tint to this /// [Sprite] (default is white, meaning no tint). -class Sprite { +class Sprite( + var Image image, { + Vector2? srcPosition, + Vector2? srcSize, +}) { Paint paint = BasicPalette.white.paint(); - Image image; Rect src = Rect.zero; - Sprite( - this.image, { - Vector2? srcPosition, - Vector2? srcSize, - }) { + this { this.srcSize = srcSize; this.srcPosition = srcPosition; } diff --git a/packages/flame/lib/src/sprite_animation.dart b/packages/flame/lib/src/sprite_animation.dart index c77e41caa76..14580c6010a 100644 --- a/packages/flame/lib/src/sprite_animation.dart +++ b/packages/flame/lib/src/sprite_animation.dart @@ -9,22 +9,16 @@ import 'package:flame/src/sprite_animation_ticker.dart'; export 'sprite.dart'; -class SpriteAnimationFrameData { +class SpriteAnimationFrameData({ /// Coordinates of the sprite of this Frame - final Vector2 srcPosition; + required final Vector2 srcPosition, /// Size of the sprite of this Frame - final Vector2 srcSize; + required final Vector2 srcSize, /// The duration to display it, in seconds. - final double stepTime; - - SpriteAnimationFrameData({ - required this.srcPosition, - required this.srcSize, - required this.stepTime, - }); -} + required final double stepTime, +}); class SpriteAnimationData { late List frames; @@ -127,21 +121,25 @@ class SpriteAnimationData { } /// Represents a single sprite animation frame. -class SpriteAnimationFrame { +class SpriteAnimationFrame( /// The [Sprite] to be displayed. - Sprite sprite; + var Sprite sprite, /// The duration to display it, in seconds. - double stepTime; - - /// Create based on the parameters. - SpriteAnimationFrame(this.sprite, this.stepTime); -} + var double stepTime, +); /// Represents a sprite animation, that is, a list of sprites that change with /// time. -class SpriteAnimation { - SpriteAnimation(this.frames, {this.loop = true}) +class SpriteAnimation( + /// The frames that compose this animation. + var List frames, { + + /// Whether the animation loops after the last sprite of the list, going back + /// to the first, or keeps returning the last when done. + var bool loop = true, +}) { + this : assert(frames.isNotEmpty, 'There must be at least one animation frame'), assert( frames.every((frame) => frame.stepTime > 0), @@ -251,13 +249,6 @@ class SpriteAnimation { return SpriteAnimation.fromFrameData(image, data); } - /// The frames that compose this animation. - List frames = []; - - /// Whether the animation loops after the last sprite of the list, going back - /// to the first, or keeps returning the last when done. - bool loop = true; - /// Sets a different step time to each frame. /// The sizes of the arrays must match. set variableStepTimes(List stepTimes) { diff --git a/packages/flame/lib/src/sprite_animation_ticker.dart b/packages/flame/lib/src/sprite_animation_ticker.dart index 289cb7d5214..572e0020544 100644 --- a/packages/flame/lib/src/sprite_animation_ticker.dart +++ b/packages/flame/lib/src/sprite_animation_ticker.dart @@ -4,12 +4,7 @@ import 'package:flame/components.dart'; import 'package:meta/meta.dart'; /// A helper class to make the [spriteAnimation] tick. -class SpriteAnimationTicker { - SpriteAnimationTicker(this.spriteAnimation); - - // The current sprite animation. - final SpriteAnimation spriteAnimation; - +class SpriteAnimationTicker(final SpriteAnimation spriteAnimation) { /// Index of the current frame that should be displayed. int currentIndex = 0; diff --git a/packages/flame/lib/src/sprite_batch.dart b/packages/flame/lib/src/sprite_batch.dart index dbc72f26237..7904bdeed4d 100644 --- a/packages/flame/lib/src/sprite_batch.dart +++ b/packages/flame/lib/src/sprite_batch.dart @@ -35,41 +35,16 @@ extension SpriteBatchExtension on Game { /// A single item in a SpriteBatch. /// /// Holds all the important information of a batch item. -class BatchItem { - BatchItem({ - required this.source, - required this.transform, - Color? color, - this.flip = false, - this.bleed = 0, - }) : assert(bleed >= 0, 'Bleed must be non-negative'), - color = color ?? const Color(0x00000000), - paint = Paint()..color = color ?? const Color(0x00000000), - destination = bleed > 0 - ? Rect.fromLTWH( - -bleed, - -bleed, - source.width + bleed * 2, - source.height + bleed * 2, - ) - : Offset.zero & source.size; - +class BatchItem({ /// The source rectangle on the [SpriteBatch.atlas]. - Rect source; - - /// The destination rectangle for the Canvas, used in the non-atlas rendering - /// path. - /// - /// It will be transformed by [matrix]. When [bleed] is greater than zero, - /// this rect extends [bleed] pixels in each direction beyond the source - /// size to prevent edge artifacts in the non-atlas rendering path. - Rect destination; + required var Rect source, /// The transform values for this batch item. - RSTransform transform; + required var RSTransform transform, + Color? color, /// The flip value for this batch item. - bool flip; + var bool flip = false, /// The bleed value for this batch item in pixels. /// @@ -82,10 +57,27 @@ class BatchItem { /// For non-square source rects this means the shorter axis is scaled /// slightly more than the requested [bleed]. The non-atlas path always /// expands by exactly [bleed] pixels on every side. - double bleed; + var double bleed = 0, +}) { + this : assert(bleed >= 0, 'Bleed must be non-negative'); + + /// The destination rectangle for the Canvas, used in the non-atlas rendering + /// path. + /// + /// It will be transformed by [matrix]. When [bleed] is greater than zero, + /// this rect extends [bleed] pixels in each direction beyond the source + /// size to prevent edge artifacts in the non-atlas rendering path. + Rect destination = bleed > 0 + ? Rect.fromLTWH( + -bleed, + -bleed, + source.width + bleed * 2, + source.height + bleed * 2, + ) + : Offset.zero & source.size; /// The color of the batch item (used for building the drawAtlas color list). - Color color; + Color color = color ?? const Color(0x00000000); /// Fallback matrix for the web. /// @@ -118,11 +110,11 @@ class BatchItem { void _invalidateMatrix() => _cachedMatrix = null; /// Paint object used for the web. - Paint paint; + Paint paint = Paint()..color = color ?? const Color(0x00000000); } @internal -enum FlippedAtlasStatus { +enum FlippedAtlasStatus() { /// There is no need to generate a flipped atlas yet. none, @@ -153,17 +145,32 @@ enum FlippedAtlasStatus { /// To activate this mode, pass in `useAtlas = false` to the constructor or /// load method that you are using and each [BatchItem] will be rendered using /// the [Canvas.drawImageRect] method instead. -class SpriteBatch { - SpriteBatch( - this.atlas, { - this.defaultTransform, - this.useAtlas = true, - this.defaultColor, - this.defaultBlendMode, - this._imageCache, - this._imageKey, - }); +class SpriteBatch( + /// The atlas used by the [SpriteBatch]. + var Image atlas, { + + /// The default transform, used when a transform was not supplied for a + /// [BatchItem]. + final RSTransform? defaultTransform, + + /// Whether to use [Canvas.drawAtlas] or not. + final bool useAtlas = true, + + /// The default color, used as a background color for a [BatchItem] on web. + /// + /// Note: The drawAtlas color list uses [_defaultColor] + /// unless an explicit per-item color is provided. + final Color? defaultColor, + + /// The default blend mode, used for blending a batch item. + final BlendMode? defaultBlendMode, + /// The image cache used by the [SpriteBatch] to store image assets. + final Images? _imageCache, + + /// The root key use by the [SpriteBatch] to store image assets. + final String? _imageKey, +}) { /// Takes the full path of an image, and optional arguments for the /// SpriteBatch. /// @@ -244,18 +251,9 @@ class SpriteBatch { _freeHandles.addFirst(handle); } - /// The atlas used by the [SpriteBatch]. - Image atlas; - - /// The image cache used by the [SpriteBatch] to store image assets. - final Images? _imageCache; - /// When the [_imageCache] isn't specified, the global [Flame.images] is used. Images get imageCache => _imageCache ?? Flame.images; - /// The root key use by the [SpriteBatch] to store image assets. - final String? _imageKey; - /// When the [_imageKey] isn't specified [imageKey] will return either the key /// for the [atlas] stored in [imageCache] or a key generated from the /// identityHashCode. @@ -264,19 +262,6 @@ class SpriteBatch { imageCache.findKeyForImage(atlas) ?? 'image[${identityHashCode(atlas)}]'; - /// The default color, used as a background color for a [BatchItem] on web. - /// - /// Note: The drawAtlas color list uses [_defaultColor] - /// unless an explicit per-item color is provided. - final Color? defaultColor; - - /// The default transform, used when a transform was not supplied for a - /// [BatchItem]. - final RSTransform? defaultTransform; - - /// The default blend mode, used for blending a batch item. - final BlendMode? defaultBlendMode; - /// The width of the [atlas]. int get width => atlas.width; @@ -286,9 +271,6 @@ class SpriteBatch { /// The size of the [atlas]. Vector2 get size => atlas.size; - /// Whether to use [Canvas.drawAtlas] or not. - final bool useAtlas; - /// Does this batch contain any operations? bool get isEmpty => _batchItems.isEmpty; diff --git a/packages/flame/lib/src/text/common/glyph.dart b/packages/flame/lib/src/text/common/glyph.dart index 87098ceae75..f94f64a3877 100644 --- a/packages/flame/lib/src/text/common/glyph.dart +++ b/packages/flame/lib/src/text/common/glyph.dart @@ -20,47 +20,39 @@ import 'package:meta/meta.dart'; /// flourish that trespasses upon other characters' space; or smaller if the /// characters are packed too tightly in the source image, or if you're trying /// to improve rendering performance by not copying empty pixels. -class Glyph { - Glyph( - this.char, { - required this.left, - required this.top, - double? width, - double? height, - double? srcLeft, - double? srcTop, - double? srcRight, - double? srcBottom, - }) : assert((width ?? 0) >= 0, 'The `width` parameter cannot be negative'), - assert((height ?? 0) >= 0, 'The `height` parameter cannot be negative'), - assert( - (srcLeft == null && - srcTop == null && - srcRight == null && - srcBottom == null) || - (srcLeft != null && - srcTop != null && - srcRight != null && - srcBottom != null), - 'Either all or none of parameters `srcLeft`, `srcTop`, `srcRight` ' - 'and `srcBottom` must be specified', - ), - width = width ?? -1, - height = height ?? -1, - srcLeft = srcLeft ?? -1, - srcTop = srcTop ?? -1, - srcRight = srcRight ?? -1, - srcBottom = srcBottom ?? -1; +class Glyph( + final String char, { + required final double left, + required final double top, + double? width, + double? height, + double? srcLeft, + double? srcTop, + double? srcRight, + double? srcBottom, +}) { + this + : assert((width ?? 0) >= 0, 'The `width` parameter cannot be negative'), + assert((height ?? 0) >= 0, 'The `height` parameter cannot be negative'), + assert( + (srcLeft == null && + srcTop == null && + srcRight == null && + srcBottom == null) || + (srcLeft != null && + srcTop != null && + srcRight != null && + srcBottom != null), + 'Either all or none of parameters `srcLeft`, `srcTop`, `srcRight` ' + 'and `srcBottom` must be specified', + ); - final String char; - final double left; - final double top; - double width; - double height; - double srcLeft; - double srcTop; - double srcRight; - double srcBottom; + double width = width ?? -1; + double height = height ?? -1; + double srcLeft = srcLeft ?? -1; + double srcTop = srcTop ?? -1; + double srcRight = srcRight ?? -1; + double srcBottom = srcBottom ?? -1; @internal void initialize(double defaultCharWidth, double charHeight) { diff --git a/packages/flame/lib/src/text/common/line_metrics.dart b/packages/flame/lib/src/text/common/line_metrics.dart index e6e5e90c18a..72b172a3aee 100644 --- a/packages/flame/lib/src/text/common/line_metrics.dart +++ b/packages/flame/lib/src/text/common/line_metrics.dart @@ -9,40 +9,36 @@ import 'package:flame/extensions.dart'; /// The [LineMetrics] box surrounding a piece of text is not necessarily tight: /// there's usually some amount of space above and below the text glyphs to /// improve legibility of multi-line text. -class LineMetrics { - LineMetrics({ - this._left = 0, - this._baseline = 0, - this._width = 0, - double? ascent, - double? descent, - double? height, - }) : _ascent = ascent ?? (height == null ? 0 : height - (descent ?? 0)), - _descent = - descent ?? (height == null ? 0 : height - (ascent ?? height)) { +class LineMetrics({ + var double _left = 0, + var double _baseline = 0, + var double _width = 0, + double? ascent, + double? descent, + double? height, +}) { + this { _updateSize(); } /// X-coordinate of the left edge of the box. double get left => _left; - double _left; /// Y-coordinate of the baseline of the box. When several line fragments are /// placed next to each other, their baselines will match. double get baseline => _baseline; - double _baseline; /// The total width of the box. double get width => _width; - double _width; /// The distance from the baseline to the top of the box. double get ascent => _ascent; - double _ascent; + double _ascent = ascent ?? (height == null ? 0 : height - (descent ?? 0)); /// The distance from the baseline to the bottom of the box. double get descent => _descent; - double _descent; + double _descent = + descent ?? (height == null ? 0 : height - (ascent ?? height)); double get right => left + width; double get top => baseline - ascent; diff --git a/packages/flame/lib/src/text/common/sprite_font.dart b/packages/flame/lib/src/text/common/sprite_font.dart index 112c54e293b..930ef39ab71 100644 --- a/packages/flame/lib/src/text/common/sprite_font.dart +++ b/packages/flame/lib/src/text/common/sprite_font.dart @@ -23,14 +23,18 @@ import 'package:meta/meta.dart'; /// The [SpriteFont] can be either variable-width or monospace. For a monospace /// font you can pass the `defaultCharWidth` parameter in the constructor so /// that you wouldn't have to specify the width of each glyph. -class SpriteFont { - SpriteFont({ - required this.source, - required this.size, - required this.ascent, - required List glyphs, - double? defaultCharWidth, - }) : _data = {} { +class SpriteFont({ + required final Image source, + + /// The font size, i.e. the height of all characters in the font. + required final double size, + + /// The distance from the top of every character to its baseline. + required final double ascent, + required List glyphs, + double? defaultCharWidth, +}) { + this : _data = {} { for (final glyph in glyphs) { var data = _data; for (var i = 0; i < glyph.char.length - 1; i++) { @@ -48,14 +52,6 @@ class SpriteFont { } } - final Image source; - - /// The font size, i.e. the height of all characters in the font. - final double size; - - /// The distance from the top of every character to its baseline. - final double ascent; - /// Contains information about the characters of the font. The keys in this /// map are the characters' code points. If a particular "character" has a /// length greater than 1, then the key will be the first code point of this @@ -95,7 +91,7 @@ class SpriteFont { } } -class _Chain { +class _Chain() { Glyph? glyph; Map? followOn; } diff --git a/packages/flame/lib/src/text/elements/block_element.dart b/packages/flame/lib/src/text/elements/block_element.dart index 362f4f8b233..c5210a1e5b9 100644 --- a/packages/flame/lib/src/text/elements/block_element.dart +++ b/packages/flame/lib/src/text/elements/block_element.dart @@ -5,9 +5,5 @@ import 'package:flame/text.dart'; /// /// Within HTML, this corresponds to elements with `display: block` property, /// such as `
` or `
`. -abstract class BlockElement extends TextElement { - BlockElement(this.width, this.height); - - final double width; - final double height; -} +abstract class BlockElement(final double width, final double height) + extends TextElement; diff --git a/packages/flame/lib/src/text/elements/group_element.dart b/packages/flame/lib/src/text/elements/group_element.dart index f5e08eb327a..ed5d0ac8876 100644 --- a/packages/flame/lib/src/text/elements/group_element.dart +++ b/packages/flame/lib/src/text/elements/group_element.dart @@ -1,14 +1,12 @@ import 'package:flame/extensions.dart'; import 'package:flame/text.dart'; -class GroupElement extends BlockElement { - GroupElement({ - required double width, - required double height, - required this.children, - }) : super(width, height); - - final List children; +class GroupElement({ + required double width, + required double height, + required final List children, +}) extends BlockElement { + this : super(width, height); @override void translate(double dx, double dy) { diff --git a/packages/flame/lib/src/text/elements/inline_text_element.dart b/packages/flame/lib/src/text/elements/inline_text_element.dart index 5ad2b94aae3..4c260f72650 100644 --- a/packages/flame/lib/src/text/elements/inline_text_element.dart +++ b/packages/flame/lib/src/text/elements/inline_text_element.dart @@ -4,7 +4,7 @@ import 'package:flame/text.dart'; /// [InlineTextElement] is the base class that represents a single line of text, /// laid out and prepared for rendering. -abstract class InlineTextElement extends TextElement { +abstract class InlineTextElement() extends TextElement { /// The dimensions of this line. LineMetrics get metrics; diff --git a/packages/flame/lib/src/text/elements/paragraph_text_element.dart b/packages/flame/lib/src/text/elements/paragraph_text_element.dart index 92dcd3f5bfe..1b98fa282e8 100644 --- a/packages/flame/lib/src/text/elements/paragraph_text_element.dart +++ b/packages/flame/lib/src/text/elements/paragraph_text_element.dart @@ -10,10 +10,9 @@ import 'package:meta/meta.dart'; /// /// The element owns the laid out [TextPainter]; call [dispose] once the /// element is no longer needed to release it. -class ParagraphTextElement extends TextElement { - /// Wraps a [textPainter] that has already had `layout` called on it. - ParagraphTextElement(this._textPainter); - +/// +/// Wraps a text painter that has already had `layout` called on it. +class ParagraphTextElement(final TextPainter _textPainter) extends TextElement { /// Lays out [text] within [maxWidth] and wraps the resulting painter. ParagraphTextElement.layout( InlineSpan text, { @@ -28,7 +27,6 @@ class ParagraphTextElement extends TextElement { )..layout(maxWidth: maxWidth), ); - final TextPainter _textPainter; Offset _offset = Offset.zero; @visibleForTesting diff --git a/packages/flame/lib/src/text/elements/rect_element.dart b/packages/flame/lib/src/text/elements/rect_element.dart index c1394904756..abbd583cf83 100644 --- a/packages/flame/lib/src/text/elements/rect_element.dart +++ b/packages/flame/lib/src/text/elements/rect_element.dart @@ -2,13 +2,9 @@ import 'dart:ui'; import 'package:flame/text.dart'; -class RectElement extends TextElement { - RectElement(double width, double height, this._paint) - : _rect = Rect.fromLTWH(0, 0, width, height); - - Rect _rect; - final Paint _paint; - +class RectElement(double width, double height, final Paint _paint) + extends TextElement { + Rect _rect = Rect.fromLTWH(0, 0, width, height); @override void translate(double dx, double dy) { _rect = _rect.translate(dx, dy); diff --git a/packages/flame/lib/src/text/elements/rrect_element.dart b/packages/flame/lib/src/text/elements/rrect_element.dart index 4c81145e97a..3c8f9b1a5cb 100644 --- a/packages/flame/lib/src/text/elements/rrect_element.dart +++ b/packages/flame/lib/src/text/elements/rrect_element.dart @@ -2,17 +2,13 @@ import 'dart:ui'; import 'package:flame/text.dart'; -class RRectElement extends TextElement { - RRectElement( - double width, - double height, - double radius, - this._paint, - ) : _rrect = RRect.fromLTRBR(0, 0, width, height, Radius.circular(radius)); - - RRect _rrect; - final Paint _paint; - +class RRectElement( + double width, + double height, + double radius, + final Paint _paint, +) extends TextElement { + RRect _rrect = RRect.fromLTRBR(0, 0, width, height, Radius.circular(radius)); @override void translate(double dx, double dy) { _rrect = _rrect.shift(Offset(dx, dy)); diff --git a/packages/flame/lib/src/text/elements/sprite_font_text_element.dart b/packages/flame/lib/src/text/elements/sprite_font_text_element.dart index 1d1299883ca..460dd632ac7 100644 --- a/packages/flame/lib/src/text/elements/sprite_font_text_element.dart +++ b/packages/flame/lib/src/text/elements/sprite_font_text_element.dart @@ -3,20 +3,14 @@ import 'dart:ui'; import 'package:flame/text.dart'; -class SpriteFontTextElement extends InlineTextElement { - SpriteFontTextElement({ - required this.source, - required this.transforms, - required this.rects, - required this.paint, - required LineMetrics metrics, - }) : _box = metrics; - - final Image source; - final Float32List transforms; - final Float32List rects; - final Paint paint; - final LineMetrics _box; +class SpriteFontTextElement({ + required final Image source, + required final Float32List transforms, + required final Float32List rects, + required final Paint paint, + required LineMetrics metrics, +}) extends InlineTextElement { + final LineMetrics _box = metrics; @override LineMetrics get metrics => _box; diff --git a/packages/flame/lib/src/text/elements/text_element.dart b/packages/flame/lib/src/text/elements/text_element.dart index 4dc3d325239..f053620cc23 100644 --- a/packages/flame/lib/src/text/elements/text_element.dart +++ b/packages/flame/lib/src/text/elements/text_element.dart @@ -1,4 +1,5 @@ import 'dart:ui'; + import 'package:flame/extensions.dart'; import 'package:flame/text.dart'; @@ -11,7 +12,7 @@ import 'package:flame/text.dart'; /// /// Elements are at the final stage of the text rendering pipeline, they are /// created during the layout step. -abstract class TextElement { +abstract class TextElement() { /// Moves the element by ([dx], [dy]) relative to its current location. void translate(double dx, double dy); diff --git a/packages/flame/lib/src/text/elements/text_painter_text_element.dart b/packages/flame/lib/src/text/elements/text_painter_text_element.dart index a846b902f9c..1e814b22ac8 100644 --- a/packages/flame/lib/src/text/elements/text_painter_text_element.dart +++ b/packages/flame/lib/src/text/elements/text_painter_text_element.dart @@ -4,18 +4,15 @@ import 'package:flame/text.dart'; import 'package:flutter/rendering.dart' as flutter; import 'package:meta/meta.dart'; -class TextPainterTextElement extends InlineTextElement { - TextPainterTextElement(this._textPainter) - : _box = LineMetrics( - ascent: _textPainter.computeDistanceToActualBaseline( - flutter.TextBaseline.alphabetic, - ), - width: _textPainter.width, - height: _textPainter.height, - ); - - final flutter.TextPainter _textPainter; - final LineMetrics _box; +class TextPainterTextElement(final flutter.TextPainter _textPainter) + extends InlineTextElement { + final LineMetrics _box = LineMetrics( + ascent: _textPainter.computeDistanceToActualBaseline( + flutter.TextBaseline.alphabetic, + ), + width: _textPainter.width, + height: _textPainter.height, + ); @visibleForTesting flutter.TextPainter get textPainter => _textPainter; diff --git a/packages/flame/lib/src/text/nodes/block_node.dart b/packages/flame/lib/src/text/nodes/block_node.dart index 3b3f383c83c..b17cf94ea36 100644 --- a/packages/flame/lib/src/text/nodes/block_node.dart +++ b/packages/flame/lib/src/text/nodes/block_node.dart @@ -11,7 +11,7 @@ import 'package:flame/text.dart'; /// Implementations include: /// * ColumnNode /// * TextBlockNode (which itself can be a HeaderNode or ParagraphNode) -abstract class BlockNode implements TextNode { +abstract class BlockNode() implements TextNode { /// The runtime style applied to this node, this will be set by [fillStyles]. @override late BlockStyle style; diff --git a/packages/flame/lib/src/text/nodes/column_node.dart b/packages/flame/lib/src/text/nodes/column_node.dart index dec83329f5e..594a565099f 100644 --- a/packages/flame/lib/src/text/nodes/column_node.dart +++ b/packages/flame/lib/src/text/nodes/column_node.dart @@ -7,11 +7,7 @@ import 'package:meta/meta.dart'; /// /// During formatting, produces an element which is as wide as the available /// width, and tall enough to fit all the available children elements. -abstract class ColumnNode extends BlockNode { - ColumnNode(this.children); - - final List children; - +abstract class ColumnNode(final List children) extends BlockNode { @override GroupElement format(double availableWidth) { final out = []; diff --git a/packages/flame/lib/src/text/nodes/document_root.dart b/packages/flame/lib/src/text/nodes/document_root.dart index b8e69338881..dd4e9c47179 100644 --- a/packages/flame/lib/src/text/nodes/document_root.dart +++ b/packages/flame/lib/src/text/nodes/document_root.dart @@ -4,11 +4,7 @@ import 'package:flame/src/text/common/utils.dart'; import 'package:flame/text.dart'; import 'package:flutter/painting.dart'; -class DocumentRoot { - DocumentRoot(this.children); - - final List children; - +class DocumentRoot(final List children) { /// Applies [style] to this document, producing an Element that can be /// rendered on a canvas. Parameters [width] and [height] serve as the /// fallback values if they were not specified in the style itself. diff --git a/packages/flame/lib/src/text/nodes/group_text_node.dart b/packages/flame/lib/src/text/nodes/group_text_node.dart index 2a1ad81e364..05fc18cd6f3 100644 --- a/packages/flame/lib/src/text/nodes/group_text_node.dart +++ b/packages/flame/lib/src/text/nodes/group_text_node.dart @@ -2,11 +2,8 @@ import 'package:flame/text.dart'; import 'package:flutter/painting.dart' show InlineSpan, TextSpan; /// An [InlineTextNode] to group other [InlineTextNode]s. -class GroupTextNode extends InlineTextNode { - GroupTextNode(this.children); - - final List children; - +class GroupTextNode(final List children) + extends InlineTextNode { @override void fillStyles(DocumentStyle stylesheet, InlineTextStyle parentTextStyle) { style = parentTextStyle; diff --git a/packages/flame/lib/src/text/nodes/inline_text_node.dart b/packages/flame/lib/src/text/nodes/inline_text_node.dart index 3ab8e585768..ee747162e42 100644 --- a/packages/flame/lib/src/text/nodes/inline_text_node.dart +++ b/packages/flame/lib/src/text/nodes/inline_text_node.dart @@ -13,7 +13,7 @@ import 'package:flutter/painting.dart' show InlineSpan; /// * CustomTextNode - applies arbitrary attributes to a span of text /// * GroupTextNode - collection of multiple [InlineTextNode]'s to be joined one /// after the other. -abstract class InlineTextNode extends TextNode { +abstract class InlineTextNode() extends TextNode { @override late InlineTextStyle style; diff --git a/packages/flame/lib/src/text/nodes/plain_text_node.dart b/packages/flame/lib/src/text/nodes/plain_text_node.dart index 34fc586b4e8..8904d599b23 100644 --- a/packages/flame/lib/src/text/nodes/plain_text_node.dart +++ b/packages/flame/lib/src/text/nodes/plain_text_node.dart @@ -2,11 +2,7 @@ import 'package:flame/text.dart'; import 'package:flutter/painting.dart' show InlineSpan, TextSpan; /// An [InlineTextNode] representing plain text. -class PlainTextNode extends InlineTextNode { - PlainTextNode(this.text); - - final String text; - +class PlainTextNode(final String text) extends InlineTextNode { @override void fillStyles(DocumentStyle stylesheet, InlineTextStyle parentTextStyle) { style = parentTextStyle; diff --git a/packages/flame/lib/src/text/nodes/text_block_node.dart b/packages/flame/lib/src/text/nodes/text_block_node.dart index bd4874fc559..38541fbc557 100644 --- a/packages/flame/lib/src/text/nodes/text_block_node.dart +++ b/packages/flame/lib/src/text/nodes/text_block_node.dart @@ -5,11 +5,7 @@ import 'package:flame/text.dart'; import 'package:flutter/painting.dart' hide TextStyle; import 'package:meta/meta.dart'; -abstract class TextBlockNode extends BlockNode { - TextBlockNode(this.child); - - final InlineTextNode child; - +abstract class TextBlockNode(final InlineTextNode child) extends BlockNode { @mustCallSuper @override void fillStyles(DocumentStyle stylesheet, InlineTextStyle parentTextStyle) { diff --git a/packages/flame/lib/src/text/nodes/text_node.dart b/packages/flame/lib/src/text/nodes/text_node.dart index 5b54d2139bf..91b5c60f350 100644 --- a/packages/flame/lib/src/text/nodes/text_node.dart +++ b/packages/flame/lib/src/text/nodes/text_node.dart @@ -1,6 +1,6 @@ import 'package:flame/text.dart'; -abstract class TextNode { +abstract class TextNode() { T get style; void fillStyles(DocumentStyle stylesheet, InlineTextStyle parentTextStyle); diff --git a/packages/flame/lib/src/text/renderers/text_paint.dart b/packages/flame/lib/src/text/renderers/text_paint.dart index 1202523cd83..4ce66fa8b29 100644 --- a/packages/flame/lib/src/text/renderers/text_paint.dart +++ b/packages/flame/lib/src/text/renderers/text_paint.dart @@ -4,15 +4,11 @@ import 'package:flutter/rendering.dart'; /// [TextPaint] applies a Flutter [TextStyle] to a string of /// text, creating a [TextPainterTextElement]. -class TextPaint extends TextRenderer { - TextPaint({ - TextStyle? style, - this.textDirection = TextDirection.ltr, - }) : style = style ?? defaultTextStyle; - - final TextStyle style; - final TextDirection textDirection; - +class TextPaint({ + TextStyle? style, + final TextDirection textDirection = TextDirection.ltr, +}) extends TextRenderer { + final TextStyle style = style ?? defaultTextStyle; @override TextPainterTextElement format(String text) { final tp = toTextPainter(text); diff --git a/packages/flame/lib/src/text/renderers/text_renderer.dart b/packages/flame/lib/src/text/renderers/text_renderer.dart index 1d442de8757..44d5ab34f7d 100644 --- a/packages/flame/lib/src/text/renderers/text_renderer.dart +++ b/packages/flame/lib/src/text/renderers/text_renderer.dart @@ -6,7 +6,7 @@ import 'package:flame/text.dart'; /// [TextRenderer] is an abstract interface for a class that can convert an /// arbitrary string of text into a renderable [InlineTextElement]. -abstract class TextRenderer { +abstract class TextRenderer() { InlineTextElement format(String text); LineMetrics getLineMetrics(String text) { diff --git a/packages/flame/lib/src/text/renderers/text_renderer_factory.dart b/packages/flame/lib/src/text/renderers/text_renderer_factory.dart index 67684a05e7a..391b73b3d93 100644 --- a/packages/flame/lib/src/text/renderers/text_renderer_factory.dart +++ b/packages/flame/lib/src/text/renderers/text_renderer_factory.dart @@ -1,6 +1,6 @@ import 'package:flame/text.dart'; -class TextRendererFactory { +class TextRendererFactory() { /// A registry containing default providers for every [TextRenderer] subclass; /// used by [createDefault] to create default parameter values. /// diff --git a/packages/flame/lib/src/text/styles/background_style.dart b/packages/flame/lib/src/text/styles/background_style.dart index 5dd7fe4454d..decfd661aa7 100644 --- a/packages/flame/lib/src/text/styles/background_style.dart +++ b/packages/flame/lib/src/text/styles/background_style.dart @@ -3,32 +3,30 @@ import 'package:flutter/rendering.dart'; import 'package:meta/meta.dart'; @immutable -class BackgroundStyle extends FlameTextStyle { - BackgroundStyle({ - Color? color, - Paint? paint, - Color? borderColor, - double? borderRadius, - double? borderWidth, - }) : assert( - paint == null || color == null, - 'Parameters `paint` and `color` are exclusive', - ), - borderWidths = EdgeInsets.all(borderWidth ?? 0), - borderRadius = borderRadius ?? 0, - backgroundPaint = - paint ?? (color != null ? (Paint()..color = color) : null), - borderPaint = borderColor != null - ? (Paint() - ..color = borderColor - ..style = PaintingStyle.stroke - ..strokeWidth = borderWidth ?? 0) - : null; +// ignore: prefer_const_constructors_in_immutables +class BackgroundStyle({ + Color? color, + Paint? paint, + Color? borderColor, + double? borderRadius, + double? borderWidth, +}) extends FlameTextStyle { + this + : assert( + paint == null || color == null, + 'Parameters `paint` and `color` are exclusive', + ); - final Paint? backgroundPaint; - final Paint? borderPaint; - final double borderRadius; - final EdgeInsets borderWidths; + final Paint? backgroundPaint = + paint ?? (color != null ? (Paint()..color = color) : null); + final Paint? borderPaint = borderColor != null + ? (Paint() + ..color = borderColor + ..style = PaintingStyle.stroke + ..strokeWidth = borderWidth ?? 0) + : null; + final double borderRadius = borderRadius ?? 0; + final EdgeInsets borderWidths = EdgeInsets.all(borderWidth ?? 0); @override BackgroundStyle copyWith(BackgroundStyle other) { diff --git a/packages/flame/lib/src/text/styles/block_style.dart b/packages/flame/lib/src/text/styles/block_style.dart index 3d2a9eb1c43..170654aeabe 100644 --- a/packages/flame/lib/src/text/styles/block_style.dart +++ b/packages/flame/lib/src/text/styles/block_style.dart @@ -5,21 +5,13 @@ import 'package:meta/meta.dart'; /// [BlockStyle] is a generic descriptor for a visual appearance of a block- /// level element. @immutable -class BlockStyle extends FlameTextStyle { - const BlockStyle({ - this._margin, - this._padding, - this.background, - this.text, - this.textAlign, - }); - - final EdgeInsets? _margin; - final EdgeInsets? _padding; - final BackgroundStyle? background; - final InlineTextStyle? text; - final TextAlign? textAlign; - +class const BlockStyle({ + final EdgeInsets? _margin, + final EdgeInsets? _padding, + final BackgroundStyle? background, + final InlineTextStyle? text, + final TextAlign? textAlign, +}) extends FlameTextStyle { EdgeInsets get margin => _margin ?? EdgeInsets.zero; EdgeInsets get padding => _padding ?? EdgeInsets.zero; diff --git a/packages/flame/lib/src/text/styles/document_style.dart b/packages/flame/lib/src/text/styles/document_style.dart index e88ce05a896..187e16bf3d4 100644 --- a/packages/flame/lib/src/text/styles/document_style.dart +++ b/packages/flame/lib/src/text/styles/document_style.dart @@ -11,58 +11,7 @@ import 'package:flutter/painting.dart' show EdgeInsets; /// /// All styles that collectively describe how to render text are organized into /// a tree, with [DocumentStyle] at the root. -class DocumentStyle extends FlameTextStyle { - DocumentStyle({ - this.width, - this.height, - this.padding = EdgeInsets.zero, - this.background, - InlineTextStyle? text, - InlineTextStyle? boldText, - InlineTextStyle? italicText, - InlineTextStyle? codeText, - InlineTextStyle? strikethroughText, - this._customStyles, - BlockStyle? paragraph, - BlockStyle? header1, - BlockStyle? header2, - BlockStyle? header3, - BlockStyle? header4, - BlockStyle? header5, - BlockStyle? header6, - }) : _text = FlameTextStyle.merge(DocumentStyle.defaultTextStyle, text), - _boldText = FlameTextStyle.merge(BoldTextNode.defaultStyle, boldText), - _italicText = FlameTextStyle.merge( - ItalicTextNode.defaultStyle, - italicText, - ), - _codeText = FlameTextStyle.merge(CodeTextNode.defaultStyle, codeText), - _strikethroughText = FlameTextStyle.merge( - StrikethroughTextNode.defaultStyle, - strikethroughText, - ), - _paragraph = FlameTextStyle.merge(ParagraphNode.defaultStyle, paragraph), - _header1 = FlameTextStyle.merge(HeaderNode.defaultStyleH1, header1), - _header2 = FlameTextStyle.merge(HeaderNode.defaultStyleH2, header2), - _header3 = FlameTextStyle.merge(HeaderNode.defaultStyleH3, header3), - _header4 = FlameTextStyle.merge(HeaderNode.defaultStyleH4, header4), - _header5 = FlameTextStyle.merge(HeaderNode.defaultStyleH5, header5), - _header6 = FlameTextStyle.merge(HeaderNode.defaultStyleH6, header6); - - final InlineTextStyle? _text; - final InlineTextStyle? _boldText; - final InlineTextStyle? _italicText; - final InlineTextStyle? _codeText; - final InlineTextStyle? _strikethroughText; - final Map? _customStyles; - final BlockStyle? _paragraph; - final BlockStyle? _header1; - final BlockStyle? _header2; - final BlockStyle? _header3; - final BlockStyle? _header4; - final BlockStyle? _header5; - final BlockStyle? _header6; - +class DocumentStyle({ /// Outer width of the document page. /// /// This width is the distance between the left edge of the left border, and @@ -71,7 +20,7 @@ class DocumentStyle extends FlameTextStyle { /// /// If this property is `null`, then the page width must be provided when /// formatting a document. - final double? width; + final double? width, /// Outer height of the document page. /// @@ -82,12 +31,7 @@ class DocumentStyle extends FlameTextStyle { /// If this property is `null`, then the page height must be provided when /// formatting a document (except for the overflow-expand mode, when the /// value of [height] defaults to 0). - final double? height; - - /// Behavior of the document when the amount of content that needs to be laid - /// out exceeds the provided [height]. See the [Overflow] enum description for - /// more details. - Overflow get overflow => Overflow.expand; + final double? height, /// The distance from the outer edges of the page to the inner content box of /// the document. @@ -97,11 +41,78 @@ class DocumentStyle extends FlameTextStyle { /// /// If the document's horizontal padding exceeds its width, an exception will /// be thrown. - final EdgeInsets padding; + final EdgeInsets padding = EdgeInsets.zero, /// If present, describes what kind of background and borders to draw for the /// document page(s). - final BackgroundStyle? background; + final BackgroundStyle? background, + InlineTextStyle? text, + InlineTextStyle? boldText, + InlineTextStyle? italicText, + InlineTextStyle? codeText, + InlineTextStyle? strikethroughText, + final Map? _customStyles, + BlockStyle? paragraph, + BlockStyle? header1, + BlockStyle? header2, + BlockStyle? header3, + BlockStyle? header4, + BlockStyle? header5, + BlockStyle? header6, +}) extends FlameTextStyle { + final InlineTextStyle? _text = FlameTextStyle.merge( + DocumentStyle.defaultTextStyle, + text, + ); + final InlineTextStyle? _boldText = FlameTextStyle.merge( + BoldTextNode.defaultStyle, + boldText, + ); + final InlineTextStyle? _italicText = FlameTextStyle.merge( + ItalicTextNode.defaultStyle, + italicText, + ); + final InlineTextStyle? _codeText = FlameTextStyle.merge( + CodeTextNode.defaultStyle, + codeText, + ); + final InlineTextStyle? _strikethroughText = FlameTextStyle.merge( + StrikethroughTextNode.defaultStyle, + strikethroughText, + ); + final BlockStyle? _paragraph = FlameTextStyle.merge( + ParagraphNode.defaultStyle, + paragraph, + ); + final BlockStyle? _header1 = FlameTextStyle.merge( + HeaderNode.defaultStyleH1, + header1, + ); + final BlockStyle? _header2 = FlameTextStyle.merge( + HeaderNode.defaultStyleH2, + header2, + ); + final BlockStyle? _header3 = FlameTextStyle.merge( + HeaderNode.defaultStyleH3, + header3, + ); + final BlockStyle? _header4 = FlameTextStyle.merge( + HeaderNode.defaultStyleH4, + header4, + ); + final BlockStyle? _header5 = FlameTextStyle.merge( + HeaderNode.defaultStyleH5, + header5, + ); + final BlockStyle? _header6 = FlameTextStyle.merge( + HeaderNode.defaultStyleH6, + header6, + ); + + /// Behavior of the document when the amount of content that needs to be laid + /// out exceeds the provided [height]. See the [Overflow] enum description for + /// more details. + Overflow get overflow => Overflow.expand; InlineTextStyle get text => _text!; InlineTextStyle get boldText => _boldText!; diff --git a/packages/flame/lib/src/text/styles/flame_text_style.dart b/packages/flame/lib/src/text/styles/flame_text_style.dart index 465edac96b9..433f9fef539 100644 --- a/packages/flame/lib/src/text/styles/flame_text_style.dart +++ b/packages/flame/lib/src/text/styles/flame_text_style.dart @@ -12,9 +12,7 @@ import 'package:flame/text.dart'; /// [DocumentStyle] at the root. /// /// The tree of [FlameTextStyle]s is roughly equivalent to a CSS stylesheet. -abstract class FlameTextStyle { - const FlameTextStyle(); - +abstract class const FlameTextStyle() { /// Creates a new [FlameTextStyle], preferring the properties of [other] /// if present, falling back to the properties of `this`. FlameTextStyle copyWith(covariant FlameTextStyle other); diff --git a/packages/flame/lib/src/text/styles/inline_text_style.dart b/packages/flame/lib/src/text/styles/inline_text_style.dart index 51e2cb748e0..e97695041d4 100644 --- a/packages/flame/lib/src/text/styles/inline_text_style.dart +++ b/packages/flame/lib/src/text/styles/inline_text_style.dart @@ -7,49 +7,28 @@ import 'package:meta/meta.dart'; /// Note: the fields on this class are equivalent to the fields on Flutter's /// [TextStyle] class; check its documentation for more details. @immutable -class InlineTextStyle extends FlameTextStyle { - InlineTextStyle({ - this.color, - this.fontFamily, - this.fontSize, - this.fontScale, - this.fontWeight, - this.fontStyle, - this.letterSpacing, - this.wordSpacing, - this.height, - this.leadingDistribution, - this.shadows, - this.fontFeatures, - this.fontVariations, - this.decoration, - this.decorationColor, - this.decorationStyle, - this.decorationThickness, - this.background, - this.foreground, - }); - - final Color? color; - final String? fontFamily; - final double? fontSize; - final double? fontScale; - final FontWeight? fontWeight; - final FontStyle? fontStyle; - final double? letterSpacing; - final double? wordSpacing; - final double? height; - final TextLeadingDistribution? leadingDistribution; - final List? shadows; - final List? fontFeatures; - final List? fontVariations; - final TextDecoration? decoration; - final Color? decorationColor; - final TextDecorationStyle? decorationStyle; - final double? decorationThickness; - final Paint? background; - final Paint? foreground; - +// ignore: prefer_const_constructors_in_immutables +class InlineTextStyle({ + final Color? color, + final String? fontFamily, + final double? fontSize, + final double? fontScale, + final FontWeight? fontWeight, + final FontStyle? fontStyle, + final double? letterSpacing, + final double? wordSpacing, + final double? height, + final TextLeadingDistribution? leadingDistribution, + final List? shadows, + final List? fontFeatures, + final List? fontVariations, + final TextDecoration? decoration, + final Color? decorationColor, + final TextDecorationStyle? decorationStyle, + final double? decorationThickness, + final Paint? background, + final Paint? foreground, +}) extends FlameTextStyle { late final TextRenderer renderer = asTextRenderer(); @override diff --git a/packages/flame/lib/src/text/styles/overflow.dart b/packages/flame/lib/src/text/styles/overflow.dart index 4528efd9205..7058c6df5ca 100644 --- a/packages/flame/lib/src/text/styles/overflow.dart +++ b/packages/flame/lib/src/text/styles/overflow.dart @@ -1,4 +1,4 @@ -enum Overflow { +enum Overflow() { /// Any content that doesn't fit into the document box will be clipped. hidden, diff --git a/packages/flame/lib/src/timer.dart b/packages/flame/lib/src/timer.dart index fcb636f2f2e..38e0076e9e4 100644 --- a/packages/flame/lib/src/timer.dart +++ b/packages/flame/lib/src/timer.dart @@ -9,26 +9,22 @@ import 'dart:ui'; /// NOTE: You can change the [period], but keep in mind that the timer /// won't start automatically if the period is raised and the timer currently /// is stopped. -class Timer { - double period; - VoidCallback? onTick; - bool repeat; +class Timer({ + required var double period, + var VoidCallback? onTick, + var bool repeat = false, + bool autoStart = true, + final int? tickCount, +}) { double _current = 0; - bool _running; - final int? tickCount; + bool _running = autoStart; int _currentTick = 0; - Timer({ - required this.period, - this.onTick, - this.repeat = false, - bool autoStart = true, - this.tickCount, - }) : assert( - tickCount == null || tickCount > 0, - 'tickCount must be null or bigger than 0', - ), - _running = autoStart; + this + : assert( + tickCount == null || tickCount > 0, + 'tickCount must be null or bigger than 0', + ); /// The current amount of seconds that has passed on this iteration double get current => _current; diff --git a/packages/flame/lib/src/widgets/animation_widget.dart b/packages/flame/lib/src/widgets/animation_widget.dart index 7819c6fa68f..bb0e1a6993a 100644 --- a/packages/flame/lib/src/widgets/animation_widget.dart +++ b/packages/flame/lib/src/widgets/animation_widget.dart @@ -84,7 +84,7 @@ class SpriteAnimationWidget extends StatefulWidget { State createState() => _SpriteAnimationWidgetState(); } -class _SpriteAnimationWidgetState extends State { +class _SpriteAnimationWidgetState() extends State { late FutureOr _animationFuture = widget._animationFuture; late SpriteAnimationTicker? _animationTicker = widget._animationTicker; @@ -162,35 +162,26 @@ class _SpriteAnimationWidgetState extends State { /// A [StatefulWidget] that render a [SpriteAnimation]. @visibleForTesting -class InternalSpriteAnimationWidget extends StatefulWidget { +class const InternalSpriteAnimationWidget({ /// The [SpriteAnimation] to be rendered - final SpriteAnimation animation; + required final SpriteAnimation animation, /// The [SpriteAnimationTicker] use for updating the [animation]. - final SpriteAnimationTicker animationTicker; - - /// The positioning [Anchor] - final Anchor anchor; + required final SpriteAnimationTicker animationTicker, /// Should the [animation] be playing or not - final bool playing; - - final Paint? paint; - - const InternalSpriteAnimationWidget({ - required this.animation, - required this.animationTicker, - this.playing = true, - this.anchor = Anchor.topLeft, - this.paint, - super.key, - }); + final bool playing = true, + /// The positioning [Anchor] + final Anchor anchor = Anchor.topLeft, + final Paint? paint, + super.key, +}) extends StatefulWidget { @override State createState() => _InternalSpriteAnimationWidgetState(); } -class _InternalSpriteAnimationWidgetState +class _InternalSpriteAnimationWidgetState() extends State with SingleTickerProviderStateMixin { AnimationController? _controller; diff --git a/packages/flame/lib/src/widgets/base_future_builder.dart b/packages/flame/lib/src/widgets/base_future_builder.dart index bc319e29813..12d5c11cf5b 100644 --- a/packages/flame/lib/src/widgets/base_future_builder.dart +++ b/packages/flame/lib/src/widgets/base_future_builder.dart @@ -2,20 +2,13 @@ import 'dart:async'; import 'package:material_ui/material_ui.dart'; -class BaseFutureBuilder extends StatelessWidget { - final FutureOr future; - final Widget Function(BuildContext, T) builder; - final WidgetBuilder? errorBuilder; - final WidgetBuilder? loadingBuilder; - - const BaseFutureBuilder({ - required this.future, - required this.builder, - this.loadingBuilder, - this.errorBuilder, - super.key, - }); - +class const BaseFutureBuilder({ + required final FutureOr future, + required final Widget Function(BuildContext, T) builder, + final WidgetBuilder? loadingBuilder, + final WidgetBuilder? errorBuilder, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { if (future is Future) { diff --git a/packages/flame/lib/src/widgets/components_notifier_builder.dart b/packages/flame/lib/src/widgets/components_notifier_builder.dart index 38b60262832..675e4d015c0 100644 --- a/packages/flame/lib/src/widgets/components_notifier_builder.dart +++ b/packages/flame/lib/src/widgets/components_notifier_builder.dart @@ -2,23 +2,18 @@ import 'package:flame/components.dart'; import 'package:material_ui/material_ui.dart'; /// A widget that rebuilds every time the given [notifier] changes. -class ComponentsNotifierBuilder extends StatefulWidget { - const ComponentsNotifierBuilder({ - required this.notifier, - required this.builder, - super.key, - }); - - final ComponentsNotifier notifier; - final Widget Function(BuildContext, ComponentsNotifier) builder; - +class const ComponentsNotifierBuilder({ + required final ComponentsNotifier notifier, + required final Widget Function(BuildContext, ComponentsNotifier) builder, + super.key, +}) extends StatefulWidget { @override State createState() { return _ComponentsNotifierBuilderState(); } } -class _ComponentsNotifierBuilderState +class _ComponentsNotifierBuilderState() extends State> { @override void initState() { diff --git a/packages/flame/lib/src/widgets/nine_tile_box.dart b/packages/flame/lib/src/widgets/nine_tile_box.dart index 4b122e4d65d..4e2c9d9d397 100644 --- a/packages/flame/lib/src/widgets/nine_tile_box.dart +++ b/packages/flame/lib/src/widgets/nine_tile_box.dart @@ -11,21 +11,19 @@ import 'package:material_ui/material_ui.dart' hide Image; export '../nine_tile_box.dart'; export '../sprite.dart'; -class _Painter extends CustomPainter { - final Image image; - final double tileSize; - final double destTileSize; +class _Painter({ + required final Image image, + required final double tileSize, + required final double destTileSize, +}) extends CustomPainter { late final non_widget.NineTileBox _nineTileBox; - _Painter({ - required this.image, - required this.tileSize, - required this.destTileSize, - }) : _nineTileBox = non_widget.NineTileBox( - Sprite(image), - tileSize: tileSize.toInt(), - destTileSize: destTileSize.toInt(), - ); + this + : _nineTileBox = non_widget.NineTileBox( + Sprite(image), + tileSize: tileSize.toInt(), + destTileSize: destTileSize.toInt(), + ); @override void paint(Canvas canvas, Size size) { @@ -100,7 +98,7 @@ class NineTileBoxWidget extends StatefulWidget { State createState() => _NineTileBoxWidgetState(); } -class _NineTileBoxWidgetState extends State { +class _NineTileBoxWidgetState() extends State { late FutureOr _imageFuture = widget._imageFuture; @override @@ -146,28 +144,16 @@ class _NineTileBoxWidgetState extends State { } @visibleForTesting -class InternalNineTileBox extends StatelessWidget { - final Image image; - final double tileSize; - final double destTileSize; - final double? width; - final double? height; - - final Widget? child; - - final EdgeInsetsGeometry? padding; - - const InternalNineTileBox({ - required this.image, - required this.tileSize, - required this.destTileSize, - this.child, - this.width, - this.height, - this.padding, - super.key, - }); - +class const InternalNineTileBox({ + required final Image image, + required final double tileSize, + required final double destTileSize, + final Widget? child, + final double? width, + final double? height, + final EdgeInsetsGeometry? padding, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return Container( diff --git a/packages/flame/lib/src/widgets/sprite_button.dart b/packages/flame/lib/src/widgets/sprite_button.dart index f2632c4eba1..28f2ccf3cfa 100644 --- a/packages/flame/lib/src/widgets/sprite_button.dart +++ b/packages/flame/lib/src/widgets/sprite_button.dart @@ -76,7 +76,7 @@ class SpriteButton extends StatelessWidget { }) : _buttonsFuture = [ sprite, pressedSprite, - if (disabledSprite != null) disabledSprite, + ?disabledSprite, ]; SpriteButton.future({ @@ -100,7 +100,7 @@ class SpriteButton extends StatelessWidget { }) : _buttonsFuture = Future.wait([ sprite, pressedSprite, - if (disabledSprite != null) disabledSprite, + ?disabledSprite, ]); /// Loads the images from the asset [path] and [pressedPath] and renders @@ -247,33 +247,22 @@ class SpriteButton extends StatelessWidget { } @visibleForTesting -class InternalSpriteButton extends StatefulWidget { - final void Function()? onPressed; - final Widget? label; - final Sprite sprite; - final Sprite pressedSprite; - final Sprite? disabledSprite; - final EdgeInsets pressedInsets; - final double width; - final double height; - - const InternalSpriteButton({ - required this.onPressed, - required this.sprite, - required this.pressedSprite, - this.disabledSprite, - this.pressedInsets = const EdgeInsets.only(top: 5), - this.label, - this.width = 200, - this.height = 50, - super.key, - }); - +class const InternalSpriteButton({ + required final void Function()? onPressed, + required final Sprite sprite, + required final Sprite pressedSprite, + final Sprite? disabledSprite, + final EdgeInsets pressedInsets = const EdgeInsets.only(top: 5), + final Widget? label, + final double width = 200, + final double height = 50, + super.key, +}) extends StatefulWidget { @override State createState() => _ButtonState(); } -class _ButtonState extends State { +class _ButtonState() extends State { bool _pressed = false; @override @@ -326,11 +315,7 @@ class _ButtonState extends State { } } -class _ButtonPainter extends CustomPainter { - final Sprite _sprite; - - _ButtonPainter(this._sprite); - +class _ButtonPainter(final Sprite _sprite) extends CustomPainter { @override bool shouldRepaint(_ButtonPainter old) => old._sprite != _sprite; diff --git a/packages/flame/lib/src/widgets/sprite_painter.dart b/packages/flame/lib/src/widgets/sprite_painter.dart index 01e6a5e48be..0b738fa9e80 100644 --- a/packages/flame/lib/src/widgets/sprite_painter.dart +++ b/packages/flame/lib/src/widgets/sprite_painter.dart @@ -5,14 +5,12 @@ import 'package:flame/src/anchor.dart'; import 'package:flame/src/sprite.dart'; import 'package:flutter/widgets.dart'; -class SpritePainter extends CustomPainter { - final Sprite _sprite; - final Anchor _anchor; - final Paint? _paint; - final double _angle; - - SpritePainter(this._sprite, this._anchor, this._paint, {this._angle = 0}); - +class SpritePainter( + final Sprite _sprite, + final Anchor _anchor, + final Paint? _paint, { + final double _angle = 0, +}) extends CustomPainter { @override bool shouldRepaint(SpritePainter oldDelegate) { return oldDelegate._sprite != _sprite || diff --git a/packages/flame/lib/src/widgets/sprite_widget.dart b/packages/flame/lib/src/widgets/sprite_widget.dart index 18685d6b8c0..7d734c17584 100644 --- a/packages/flame/lib/src/widgets/sprite_widget.dart +++ b/packages/flame/lib/src/widgets/sprite_widget.dart @@ -87,16 +87,16 @@ class SpriteWidget extends StatefulWidget { State createState() => _SpriteWidgetState(); } -class _SpriteWidgetState extends State { +class _SpriteWidgetState() extends State { late FutureOr _spriteFuture = _initializeFuture(); FutureOr _initializeFuture() async { if (!widget.rasterize) { - return widget._spriteFuture; + return await widget._spriteFuture; } final sprite = await widget._spriteFuture; - return sprite.rasterize(); + return await sprite.rasterize(); } @override @@ -171,26 +171,18 @@ class _SpriteWidgetState extends State { /// A [StatefulWidget] that renders a still [Sprite]. @visibleForTesting -class InternalSpriteWidget extends StatelessWidget { +class const InternalSpriteWidget({ /// The [Sprite] to be rendered - final Sprite sprite; + required final Sprite sprite, /// The positioning [Anchor] for the [sprite] - final Anchor anchor; + final Anchor anchor = Anchor.topLeft, /// The angle to rotate this [sprite], in rad. (default = 0) - final double angle; - - final Paint? paint; - - const InternalSpriteWidget({ - required this.sprite, - this.anchor = Anchor.topLeft, - this.angle = 0, - this.paint, - super.key, - }); - + final double angle = 0, + final Paint? paint, + super.key, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return CustomPaint( diff --git a/packages/flame/pubspec.yaml b/packages/flame/pubspec.yaml index c33775907e9..5732ab51f07 100644 --- a/packages/flame/pubspec.yaml +++ b/packages/flame/pubspec.yaml @@ -14,8 +14,8 @@ topics: - animations environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.18.0 diff --git a/packages/flame/test/_resources/custom_flame_game.dart b/packages/flame/test/_resources/custom_flame_game.dart index 85a869c12a4..88b78a6f8e2 100644 --- a/packages/flame/test/_resources/custom_flame_game.dart +++ b/packages/flame/test/_resources/custom_flame_game.dart @@ -1,15 +1,10 @@ import 'package:flame/game.dart'; -class CustomFlameGame extends FlameGame { - CustomFlameGame({ - super.children, - this._onLoad, - this._onMount, - }); - - final Future? Function(FlameGame)? _onLoad; - final void Function(FlameGame)? _onMount; - +class CustomFlameGame({ + super.children, + final Future? Function(FlameGame)? _onLoad, + final void Function(FlameGame)? _onMount, +}) extends FlameGame { @override Future? onLoad() => _onLoad?.call(this); diff --git a/packages/flame/test/cache/assets_cache_test.dart b/packages/flame/test/cache/assets_cache_test.dart index b1677884374..676bf4d041e 100644 --- a/packages/flame/test/cache/assets_cache_test.dart +++ b/packages/flame/test/cache/assets_cache_test.dart @@ -7,7 +7,7 @@ import 'package:mocktail/mocktail.dart'; import '../fixtures/fixture_reader.dart'; -class _MockAssetBundle extends Mock implements AssetBundle {} +class _MockAssetBundle() extends Mock implements AssetBundle; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame/test/cache/images_test.dart b/packages/flame/test/cache/images_test.dart index 412accad7c6..b4ad97659ca 100644 --- a/packages/flame/test/cache/images_test.dart +++ b/packages/flame/test/cache/images_test.dart @@ -9,7 +9,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockAssetBundle extends Mock implements AssetBundle {} +class _MockAssetBundle() extends Mock implements AssetBundle; void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -252,12 +252,10 @@ void main() { }); } -class _ManifestAssetBundle extends CachingAssetBundle { - _ManifestAssetBundle(this.assetPaths, this.pixelBytes); - - final List assetPaths; - final Uint8List pixelBytes; - +class _ManifestAssetBundle( + final List assetPaths, + final Uint8List pixelBytes, +) extends CachingAssetBundle { final List loadedKeys = []; @override @@ -272,7 +270,7 @@ class _ManifestAssetBundle extends CachingAssetBundle { } } -class _MockImage extends Mock implements Image { +class _MockImage() extends Mock implements Image { int disposedCount = 0; @override diff --git a/packages/flame/test/camera/camera_component_test.dart b/packages/flame/test/camera/camera_component_test.dart index 18709c3c4be..e2b0f2b4fbb 100644 --- a/packages/flame/test/camera/camera_component_test.dart +++ b/packages/flame/test/camera/camera_component_test.dart @@ -639,21 +639,18 @@ void main() { }); } -class _SolidBackground extends Component with HasPaint { - _SolidBackground(this.color); - final Color color; +class _SolidBackground(final Color color) extends Component with HasPaint { @override void render(Canvas canvas) => canvas.drawColor(color, BlendMode.src); } -class _RenderCounter extends PositionComponent { - _RenderCounter({super.size, super.position}); +class _RenderCounter({super.size, super.position}) extends PositionComponent { int renderCount = 0; @override void render(Canvas canvas) => renderCount++; } -class _PostProcessChecker extends PostProcess { +class _PostProcessChecker() extends PostProcess { bool isLoaded = false; @override diff --git a/packages/flame/test/camera/camera_test_helpers.dart b/packages/flame/test/camera/camera_test_helpers.dart index 784259f9cdc..edce2570572 100644 --- a/packages/flame/test/camera/camera_test_helpers.dart +++ b/packages/flame/test/camera/camera_test_helpers.dart @@ -2,11 +2,13 @@ import 'dart:ui'; import 'package:flame/components.dart'; -class CrossHair extends PositionComponent { - CrossHair({super.size, super.position, this.color = const Color(0xFFFF0000)}) - : super(anchor: Anchor.center); +class CrossHair({ + super.size, + super.position, + final Color color = const Color(0xFFFF0000), +}) extends PositionComponent { + this : super(anchor: Anchor.center); - final Color color; Paint get _paint => Paint() ..style = PaintingStyle.stroke ..strokeWidth = 2.0 diff --git a/packages/flame/test/camera/viewfinder_test.dart b/packages/flame/test/camera/viewfinder_test.dart index 12d79760cd9..71e7ee48f9a 100644 --- a/packages/flame/test/camera/viewfinder_test.dart +++ b/packages/flame/test/camera/viewfinder_test.dart @@ -230,8 +230,8 @@ void main() { } /// Simple rectangle with default size 80x60. -class _Rect extends PositionComponent { - _Rect() : super(size: Vector2(80, 60)); +class _Rect() extends PositionComponent { + this : super(size: Vector2(80, 60)); @override void render(Canvas canvas) { diff --git a/packages/flame/test/camera/viewports/circular_viewport_test.dart b/packages/flame/test/camera/viewports/circular_viewport_test.dart index 4b2a691ecfc..e576127607d 100644 --- a/packages/flame/test/camera/viewports/circular_viewport_test.dart +++ b/packages/flame/test/camera/viewports/circular_viewport_test.dart @@ -168,7 +168,7 @@ void main() { }); } -class _MyWorld extends World { +class _MyWorld() extends World { @override void render(Canvas canvas) { canvas.drawColor(const Color(0xFFFFFFFF), BlendMode.src); diff --git a/packages/flame/test/camera/viewports/fixed_aspect_ratio_viewport_test.dart b/packages/flame/test/camera/viewports/fixed_aspect_ratio_viewport_test.dart index 8ce0ae3d3bb..d85a1c601e5 100644 --- a/packages/flame/test/camera/viewports/fixed_aspect_ratio_viewport_test.dart +++ b/packages/flame/test/camera/viewports/fixed_aspect_ratio_viewport_test.dart @@ -104,7 +104,7 @@ void main() { }); } -class _MyWorld extends World { +class _MyWorld() extends World { @override void render(Canvas canvas) { canvas.drawColor(const Color(0xFF777777), BlendMode.src); diff --git a/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart b/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart index ad7315b3738..d14ee1583d1 100644 --- a/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart +++ b/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart @@ -41,9 +41,7 @@ void main() { }); } -class _OnParentResizeTesterComponent extends PositionComponent { - _OnParentResizeTesterComponent(); - +class _OnParentResizeTesterComponent() extends PositionComponent { Vector2? _parentSize; @override diff --git a/packages/flame/test/camera/viewports/max_viewport_test.dart b/packages/flame/test/camera/viewports/max_viewport_test.dart index 04c5c6069b4..8e5f6114789 100644 --- a/packages/flame/test/camera/viewports/max_viewport_test.dart +++ b/packages/flame/test/camera/viewports/max_viewport_test.dart @@ -64,7 +64,7 @@ void main() { }); } -class _MyMaxViewport extends MaxViewport { +class _MyMaxViewport() extends MaxViewport { int onViewportResizeCalled = 0; @override diff --git a/packages/flame/test/collisions/collision_callback_benchmark_test.dart b/packages/flame/test/collisions/collision_callback_benchmark_test.dart index 867e6d9b3bf..a79afd0f55a 100644 --- a/packages/flame/test/collisions/collision_callback_benchmark_test.dart +++ b/packages/flame/test/collisions/collision_callback_benchmark_test.dart @@ -8,15 +8,14 @@ import 'package:test/test.dart'; import 'collision_test_helpers.dart'; -class _TestBlock extends PositionComponent with CollisionCallbacks { - final Vector2 velocity; +class _TestBlock({ + required final Vector2 velocity, + required super.position, + required super.size, +}) extends PositionComponent with CollisionCallbacks { static int collisionCounter = 0; - _TestBlock({ - required this.velocity, - required super.position, - required super.size, - }) { + this { add(CircleHitbox()); } diff --git a/packages/flame/test/collisions/collision_detection_test.dart b/packages/flame/test/collisions/collision_detection_test.dart index b780b533903..b84ab8095d7 100644 --- a/packages/flame/test/collisions/collision_detection_test.dart +++ b/packages/flame/test/collisions/collision_detection_test.dart @@ -2749,4 +2749,4 @@ void main() { }); } -class _CollisionDetectionGame extends FlameGame with HasCollisionDetection {} +class _CollisionDetectionGame() extends FlameGame with HasCollisionDetection; diff --git a/packages/flame/test/collisions/collision_passthrough_test.dart b/packages/flame/test/collisions/collision_passthrough_test.dart index 91dbf3a9a61..ac766d1beab 100644 --- a/packages/flame/test/collisions/collision_passthrough_test.dart +++ b/packages/flame/test/collisions/collision_passthrough_test.dart @@ -5,8 +5,8 @@ import 'package:test/test.dart'; import 'collision_test_helpers.dart'; -class _Passthrough extends TestBlock with CollisionPassthrough { - _Passthrough() : super(Vector2.zero(), Vector2.all(10)); +class _Passthrough() extends TestBlock with CollisionPassthrough { + this : super(Vector2.zero(), Vector2.all(10)); } void main() { diff --git a/packages/flame/test/collisions/collision_test_helpers.dart b/packages/flame/test/collisions/collision_test_helpers.dart index 56b3544d4c1..42f29cb7c5f 100644 --- a/packages/flame/test/collisions/collision_test_helpers.dart +++ b/packages/flame/test/collisions/collision_test_helpers.dart @@ -5,12 +5,13 @@ import 'package:flame/image_composition.dart'; import 'package:flame_test/flame_test.dart'; import 'package:meta/meta.dart'; -class HasCollidablesGame extends FlameGame with HasCollisionDetection {} +class HasCollidablesGame() extends FlameGame with HasCollisionDetection; -class HasQuadTreeCollidablesGame extends FlameGame - with HasQuadTreeCollisionDetection {} +class HasQuadTreeCollidablesGame() + extends FlameGame + with HasQuadTreeCollisionDetection; -class CollisionDetectionWorld extends World with HasCollisionDetection {} +class CollisionDetectionWorld() extends World with HasCollisionDetection; @isTest void testCollisionDetectionGame( @@ -49,17 +50,15 @@ Future runCollisionTestRegistry( } } -class TestHitbox extends RectangleHitbox { +class TestHitbox([var String? name]) extends RectangleHitbox { int startCounter = 0; int onCollisionCounter = 0; int endCounter = 0; - String? name; - - TestHitbox([this.name]) { - onCollisionCallback = (_, __) { + this { + onCollisionCallback = (_, _) { onCollisionCounter++; }; - onCollisionStartCallback = (_, __) { + onCollisionStartCallback = (_, _) { startCounter++; }; onCollisionEndCallback = (_) { @@ -75,16 +74,17 @@ class TestHitbox extends RectangleHitbox { } } -class CompositeTestHitbox extends CompositeHitbox { +class CompositeTestHitbox({super.size, super.children}) + extends CompositeHitbox { int startCounter = 0; int onCollisionCounter = 0; int endCounter = 0; - CompositeTestHitbox({super.size, super.children}) { - onCollisionCallback = (_, __) { + this { + onCollisionCallback = (_, _) { onCollisionCounter++; }; - onCollisionStartCallback = (_, __) { + onCollisionStartCallback = (_, _) { startCounter++; }; onCollisionEndCallback = (_) { @@ -93,27 +93,25 @@ class CompositeTestHitbox extends CompositeHitbox { } } -class TestBlock extends PositionComponent with CollisionCallbacks { - String? name; +class TestBlock( + Vector2 position, + Vector2 size, { + CollisionType type = CollisionType.active, + bool addTestHitbox = true, + super.children, + var String? name, + final bool Function(PositionComponent other)? _onComponentTypeCheck, +}) extends PositionComponent with CollisionCallbacks { final hitbox = TestHitbox(); int startCounter = 0; int onCollisionCounter = 0; int endCounter = 0; - final bool Function(PositionComponent other)? _onComponentTypeCheck; - - TestBlock( - Vector2 position, - Vector2 size, { - CollisionType type = CollisionType.active, - bool addTestHitbox = true, - super.children, - this.name, - this._onComponentTypeCheck, - }) : super( - position: position, - size: size, - ) { + this + : super( + position: position, + size: size, + ) { children.register(); if (addTestHitbox) { add(hitbox..collisionType = type); @@ -176,10 +174,8 @@ class TestBlock extends PositionComponent with CollisionCallbacks { } } -class Water extends PositionComponent { - Water({super.position, super.size, super.children}); -} +class Water({super.position, super.size, super.children}) + extends PositionComponent; -class Brick extends PositionComponent { - Brick({super.position, super.size, super.children}); -} +class Brick({super.position, super.size, super.children}) + extends PositionComponent; diff --git a/packages/flame/test/components/advanced_button_component_test.dart b/packages/flame/test/components/advanced_button_component_test.dart index 7267f30e20d..79ee0ca6c0f 100644 --- a/packages/flame/test/components/advanced_button_component_test.dart +++ b/packages/flame/test/components/advanced_button_component_test.dart @@ -260,13 +260,9 @@ void main() { }); } -class _SimpleStatelessWidget extends StatelessWidget { - const _SimpleStatelessWidget({ - required this._build, - }); - - final Widget Function(BuildContext) _build; - +class const _SimpleStatelessWidget({ + required final Widget Function(BuildContext) _build, +}) extends StatelessWidget { @override Widget build(BuildContext context) => _build(context); } diff --git a/packages/flame/test/components/button_component_test.dart b/packages/flame/test/components/button_component_test.dart index 20f6eb7e50c..037b92b920a 100644 --- a/packages/flame/test/components/button_component_test.dart +++ b/packages/flame/test/components/button_component_test.dart @@ -177,13 +177,9 @@ void main() { }); } -class _SimpleStatelessWidget extends StatelessWidget { - const _SimpleStatelessWidget({ - required this._build, - }); - - final Widget Function(BuildContext) _build; - +class const _SimpleStatelessWidget({ + required final Widget Function(BuildContext) _build, +}) extends StatelessWidget { @override Widget build(BuildContext context) => _build(context); } diff --git a/packages/flame/test/components/clip_component_test.dart b/packages/flame/test/components/clip_component_test.dart index fabebb87879..a414e2e7881 100644 --- a/packages/flame/test/components/clip_component_test.dart +++ b/packages/flame/test/components/clip_component_test.dart @@ -3,8 +3,8 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _Rectangle extends RectangleComponent { - _Rectangle() +class _Rectangle() extends RectangleComponent { + this : super( size: Vector2(200, 200), anchor: Anchor.center, diff --git a/packages/flame/test/components/component_pool_test.dart b/packages/flame/test/components/component_pool_test.dart index 4b1ea20cb2f..88a50fc4c21 100644 --- a/packages/flame/test/components/component_pool_test.dart +++ b/packages/flame/test/components/component_pool_test.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _TestComponent extends PositionComponent { +class _TestComponent() extends PositionComponent { int mountCount = 0; @override diff --git a/packages/flame/test/components/component_render_context_test.dart b/packages/flame/test/components/component_render_context_test.dart index 7d43a70f305..c2dc5e7a6f9 100644 --- a/packages/flame/test/components/component_render_context_test.dart +++ b/packages/flame/test/components/component_render_context_test.dart @@ -79,26 +79,19 @@ void main() { }); } -class _IntContext extends ComponentRenderContext { - int value; +class _IntContext(var int value) extends ComponentRenderContext; - _IntContext(this.value); -} - -class _ParentWithContext extends Component { - final int startingValue; +class _ParentWithContext({ + required final int startingValue, + super.children, +}) extends Component { late final _IntContext _myContext = _IntContext(startingValue); - _ParentWithContext({ - required this.startingValue, - super.children, - }); - @override _IntContext get renderContext => _myContext; } -class _ChildReadsContext extends Component { +class _ChildReadsContext() extends Component { int? myContext; @override diff --git a/packages/flame/test/components/component_test.dart b/packages/flame/test/components/component_test.dart index ec6a01dc78d..4b561713a94 100644 --- a/packages/flame/test/components/component_test.dart +++ b/packages/flame/test/components/component_test.dart @@ -2334,15 +2334,11 @@ void main() { }); } -class _ComponentA extends Component { - _ComponentA({super.key}); -} +class _ComponentA({super.key}) extends Component; -class _ComponentB extends Component { - _ComponentB(); -} +class _ComponentB() extends Component; -class _ComponentWithSizeHistory extends Component { +class _ComponentWithSizeHistory() extends Component { List history = []; @override @@ -2352,17 +2348,15 @@ class _ComponentWithSizeHistory extends Component { } } -class _Visitor extends Component { +class _Visitor() extends Component { bool visited = false; } -class _IntComponent extends Component { +class _IntComponent() extends Component { int value = 0; } -class _TwoChildrenComponent extends Component { - _TwoChildrenComponent({super.children}); - +class _TwoChildrenComponent({super.children}) extends Component { late final Component child1; late final Component child2; @@ -2375,12 +2369,8 @@ class _TwoChildrenComponent extends Component { } } -class _LifecycleComponent extends Component { +class _LifecycleComponent([final String name = '']) extends Component { final List events = []; - final String name; - - _LifecycleComponent([this.name = '']); - int countEvents(String event) { return events.where((e) => e == event).length; } @@ -2421,11 +2411,9 @@ class _LifecycleComponent extends Component { String toString() => 'LifecycleComponent($name)'; } -class _LoadException implements Exception { - const _LoadException(); -} +class const _LoadException() implements Exception; -class _FailingLoadComponent extends Component { +class _FailingLoadComponent() extends Component { @override Future onLoad() async { await Future.delayed(const Duration(milliseconds: 10)); @@ -2433,12 +2421,12 @@ class _FailingLoadComponent extends Component { } } -class _FailingSyncLoadComponent extends Component { +class _FailingSyncLoadComponent() extends Component { @override void onLoad() => throw const _LoadException(); } -class _SlowLoadingComponent extends Component { +class _SlowLoadingComponent() extends Component { int onLoadCalledCount = 0; @override @@ -2448,11 +2436,8 @@ class _SlowLoadingComponent extends Component { } } -class _SlowComponent extends Component { - _SlowComponent(this.name, this.loadTime); - final double loadTime; - final String name; - +class _SlowComponent(final String name, final double loadTime) + extends Component { @override Future onLoad() async { final ms = (loadTime * 1000).toInt(); @@ -2463,19 +2448,13 @@ class _SlowComponent extends Component { String toString() => 'SlowComponent($name, loadTime=$loadTime)'; } -class _GatedLoadComponent extends Component { - _GatedLoadComponent(this.loadGate); - - final Completer loadGate; - +class _GatedLoadComponent(final Completer loadGate) extends Component { @override Future onLoad() => loadGate.future; } -class _ParentWithGatedChild extends Component { - _ParentWithGatedChild(this.childLoadGate); - - final Completer childLoadGate; +class _ParentWithGatedChild(final Completer childLoadGate) + extends Component { late final _GatedLoadComponent child; @override @@ -2485,7 +2464,7 @@ class _ParentWithGatedChild extends Component { } } -class _ParentWithFailingChild extends Component { +class _ParentWithFailingChild() extends Component { late final _FailingLoadComponent child; @override @@ -2495,10 +2474,8 @@ class _ParentWithFailingChild extends Component { } } -class _GrandParentWithGatedGrandChild extends Component { - _GrandParentWithGatedGrandChild(this.grandChildLoadGate); - - final Completer grandChildLoadGate; +class _GrandParentWithGatedGrandChild(final Completer grandChildLoadGate) + extends Component { late final _ParentWithGatedChild child; @override @@ -2508,7 +2485,7 @@ class _GrandParentWithGatedGrandChild extends Component { } } -class _SelfRemovingOnLoadComponent extends Component { +class _SelfRemovingOnLoadComponent() extends Component { @override Future? onLoad() { removeFromParent(); @@ -2516,17 +2493,16 @@ class _SelfRemovingOnLoadComponent extends Component { } } -class _SelfRemovingOnMountComponent extends Component { +class _SelfRemovingOnMountComponent() extends Component { @override void onMount() { removeFromParent(); } } -class _SiblingRemovingOnMountComponent extends _LifecycleComponent { - _SiblingRemovingOnMountComponent(this.sibling) : super('remover'); - - final Component sibling; +class _SiblingRemovingOnMountComponent(final Component sibling) + extends _LifecycleComponent { + this : super('remover'); @override void onMount() { @@ -2535,24 +2511,16 @@ class _SiblingRemovingOnMountComponent extends _LifecycleComponent { } } -class _ReAddingOnMountComponent extends Component { - _ReAddingOnMountComponent(this.component); - - final Component component; - +class _ReAddingOnMountComponent(final Component component) extends Component { @override void onMount() { parent!.add(component); } } -class _Pair { - _Pair(this.component, this.points); - final Component component; - final List points; -} +class _Pair(final Component component, final List points); -class _PrepareGame extends FlameGame { +class _PrepareGame() extends FlameGame { late final _ParentOnPrepareComponent prepareParent; @override @@ -2561,7 +2529,7 @@ class _PrepareGame extends FlameGame { } } -class _OnPrepareComponent extends Component { +class _OnPrepareComponent() extends Component { int onMountRuns = 0; @override @@ -2571,31 +2539,25 @@ class _OnPrepareComponent extends Component { } } -class _ParentOnPrepareComponent extends _OnPrepareComponent { +class _ParentOnPrepareComponent() extends _OnPrepareComponent { @override Future onLoad() async { add(_OnPrepareComponent()); } } -class _IdentifiableComponent extends Component { - final int id; +class _IdentifiableComponent(final int id) extends Component; - _IdentifiableComponent(this.id); -} - -class _AsyncLoadingChild extends Component { +class _AsyncLoadingChild() extends Component { @override Future onLoad() async { await super.onLoad(); - return Future.value(); } } -class _GameResizeComponent extends PositionComponent { - _GameResizeComponent(this.name) : super(size: Vector2.all(2.0)); +class _GameResizeComponent(var String name) extends PositionComponent { + this : super(size: Vector2.all(2.0)); - String name; late Vector2 gameSize; @override @@ -2605,7 +2567,7 @@ class _GameResizeComponent extends PositionComponent { } } -class _OnChildrenChangedComponent extends PositionComponent { +class _OnChildrenChangedComponent() extends PositionComponent { int onChangedChildrenRuns = 0; ChildrenChangeType? lastChangeType; @@ -2616,7 +2578,7 @@ class _OnChildrenChangedComponent extends PositionComponent { } } -class _RemoveWhereComponent extends Component { +class _RemoveWhereComponent() extends Component { @override Future onLoad() async { add(Component()); @@ -2624,20 +2586,15 @@ class _RemoveWhereComponent extends Component { } } -class _Wrapper extends StatefulWidget { - const _Wrapper({ - required this.child, - this.open = false, - }); - - final Widget child; - final bool open; - +class const _Wrapper({ + required final Widget child, + final bool open = false, +}) extends StatefulWidget { @override State<_Wrapper> createState() => _WrapperState(); } -class _WrapperState extends State<_Wrapper> { +class _WrapperState() extends State<_Wrapper> { late bool _open; @override @@ -2667,7 +2624,7 @@ class _WrapperState extends State<_Wrapper> { } } -class _DetachableFlameGame extends FlameGame { +class _DetachableFlameGame() extends FlameGame { bool onAttachCalled = false; bool onDetachCalled = false; @@ -2698,7 +2655,7 @@ FlameTester<_DetachableFlameGame> _myDetachableGame({required bool open}) { ); } -class _ComponentWithChildrenRemoveAll extends Component { +class _ComponentWithChildrenRemoveAll() extends Component { @override void onMount() { super.onMount(); @@ -2708,7 +2665,7 @@ class _ComponentWithChildrenRemoveAll extends Component { } } -class _RemoveAllChildrenComponent extends Component { +class _RemoveAllChildrenComponent() extends Component { @override void onRemove() { super.onRemove(); @@ -2716,12 +2673,12 @@ class _RemoveAllChildrenComponent extends Component { } } -class _CustomListComponent extends Component { +class _CustomListComponent() extends Component { @override ComponentList createComponentList() => ComponentList(strictMode: true); } -class _ReverseOrderedComponent extends Component { +class _ReverseOrderedComponent() extends Component { @override ComponentList createComponentList() { return ComponentList( diff --git a/packages/flame/test/components/component_tree_ordering_test.dart b/packages/flame/test/components/component_tree_ordering_test.dart index c4d4aab1157..56f5aa3babb 100644 --- a/packages/flame/test/components/component_tree_ordering_test.dart +++ b/packages/flame/test/components/component_tree_ordering_test.dart @@ -192,7 +192,7 @@ void main() { }); } -class _EventLogComponent extends Component { +class _EventLogComponent() extends Component { final List events = []; @override @@ -206,16 +206,12 @@ class _EventLogComponent extends Component { } } -class _HittablePositionComponent extends PositionComponent { - _HittablePositionComponent({super.priority}) : super(size: Vector2.all(10)); +class _HittablePositionComponent({super.priority}) extends PositionComponent { + this : super(size: Vector2.all(10)); } -class _UpdateLogComponent extends Component { - _UpdateLogComponent(this.id, this.order); - - final int id; - final List order; - +class _UpdateLogComponent(final int id, final List order) + extends Component { @override void update(double dt) { order.add(id); diff --git a/packages/flame/test/components/components_notifier_test.dart b/packages/flame/test/components/components_notifier_test.dart index cccfd2b6f2b..b49cc2966c8 100644 --- a/packages/flame/test/components/components_notifier_test.dart +++ b/packages/flame/test/components/components_notifier_test.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:test/test.dart'; -class _Enemy extends PositionComponent with Notifier {} +class _Enemy() extends PositionComponent with Notifier; void main() { group('ComponentsNotifier', () { diff --git a/packages/flame/test/components/core/custom_traversal_test.dart b/packages/flame/test/components/core/custom_traversal_test.dart index 61979f0256a..2d7a2f6ab45 100644 --- a/packages/flame/test/components/core/custom_traversal_test.dart +++ b/packages/flame/test/components/core/custom_traversal_test.dart @@ -59,7 +59,7 @@ void main() { }); } -class _DtRecorder extends Component { +class _DtRecorder() extends Component { final List recordedDts = []; @override @@ -68,19 +68,19 @@ class _DtRecorder extends Component { } } -class _PlainBarrier extends Component with CustomTraversal { - _PlainBarrier({super.children}); -} - -class _HalfSpeedBarrier extends Component with CustomTraversal { - _HalfSpeedBarrier({super.children}); +class _PlainBarrier({super.children}) extends Component with CustomTraversal; +class _HalfSpeedBarrier({super.children}) + extends Component + with CustomTraversal { @override void updateSubtree(double dt) => super.updateSubtree(dt / 2); } -class _FrozenBarrier extends _DtRecorder with CustomTraversal { - _FrozenBarrier({List? children}) { +class _FrozenBarrier({List? children}) + extends _DtRecorder + with CustomTraversal { + this { if (children != null) { addAll(children); } diff --git a/packages/flame/test/components/custom_painter_component_test.dart b/packages/flame/test/components/custom_painter_component_test.dart index a13fc6a2f46..c09215f3fce 100644 --- a/packages/flame/test/components/custom_painter_component_test.dart +++ b/packages/flame/test/components/custom_painter_component_test.dart @@ -4,7 +4,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; -class _MockCustomPainter extends Mock implements CustomPainter {} +class _MockCustomPainter() extends Mock implements CustomPainter; void main() { group('CustomPainterComponent', () { diff --git a/packages/flame/test/components/has_auto_batched_children_test.dart b/packages/flame/test/components/has_auto_batched_children_test.dart index 3efab2c801e..899d28857bd 100644 --- a/packages/flame/test/components/has_auto_batched_children_test.dart +++ b/packages/flame/test/components/has_auto_batched_children_test.dart @@ -6,11 +6,11 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockCanvas extends Mock implements Canvas {} +class _MockCanvas() extends Mock implements Canvas; -class _FakeImage extends Fake implements Image {} +class _FakeImage() extends Fake implements Image; -class _AutoBatchGroup extends PositionComponent with HasAutoBatchedChildren {} +class _AutoBatchGroup() extends PositionComponent with HasAutoBatchedChildren; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame/test/components/hud_button_component_test.dart b/packages/flame/test/components/hud_button_component_test.dart index 847c24f4409..c6f36841db7 100644 --- a/packages/flame/test/components/hud_button_component_test.dart +++ b/packages/flame/test/components/hud_button_component_test.dart @@ -167,7 +167,7 @@ void main() { }); } -class _CustomHudButtonComponent extends HudButtonComponent { +class _CustomHudButtonComponent() extends HudButtonComponent { @override Future onLoad() async { super.onLoad(); diff --git a/packages/flame/test/components/icon_component_test.dart b/packages/flame/test/components/icon_component_test.dart index 451f552b6a0..df2e395f39b 100644 --- a/packages/flame/test/components/icon_component_test.dart +++ b/packages/flame/test/components/icon_component_test.dart @@ -138,7 +138,7 @@ void main() { testWithFlameGame('asserts icon is set on mount', (game) async { final component = IconComponent(); expect( - () async => game.ensureAdd(component), + () async => await game.ensureAdd(component), throwsAssertionError, ); }); diff --git a/packages/flame/test/components/input/sprite_button_component_test.dart b/packages/flame/test/components/input/sprite_button_component_test.dart index 8482c464d01..4579ed8261d 100644 --- a/packages/flame/test/components/input/sprite_button_component_test.dart +++ b/packages/flame/test/components/input/sprite_button_component_test.dart @@ -10,7 +10,7 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -enum _ButtonState { +enum _ButtonState() { up, down, } @@ -445,21 +445,13 @@ Future main() async { /// This is used to test [SpriteButtonComponent] without using the constructor /// and setting properties in [onLoad] of an extending class instead. -class _CustomSpriteButtonComponent extends SpriteButtonComponent { - final Sprite customButton; - final Sprite customButtonDown; - final void Function()? customOnPressed; - final Vector2? customPosition; - final Vector2? customSize; - - _CustomSpriteButtonComponent({ - required this.customButton, - required this.customButtonDown, - this.customOnPressed, - this.customPosition, - this.customSize, - }); - +class _CustomSpriteButtonComponent({ + required final Sprite customButton, + required final Sprite customButtonDown, + final void Function()? customOnPressed, + final Vector2? customPosition, + final Vector2? customSize, +}) extends SpriteButtonComponent { @override Future onLoad() async { position = customPosition ?? Vector2(0.0, 0.0); @@ -469,13 +461,9 @@ class _CustomSpriteButtonComponent extends SpriteButtonComponent { } } -class _SimpleStatelessWidget extends StatelessWidget { - const _SimpleStatelessWidget({ - required this._build, - }); - - final Widget Function(BuildContext) _build; - +class const _SimpleStatelessWidget({ + required final Widget Function(BuildContext) _build, +}) extends StatelessWidget { @override Widget build(BuildContext context) => _build(context); } diff --git a/packages/flame/test/components/isometric_tile_map_component_test.dart b/packages/flame/test/components/isometric_tile_map_component_test.dart index 7325a0871ea..837b17dbae0 100644 --- a/packages/flame/test/components/isometric_tile_map_component_test.dart +++ b/packages/flame/test/components/isometric_tile_map_component_test.dart @@ -6,11 +6,7 @@ import 'package:flame_test/flame_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; -class _MockImage extends Mock implements Image { - _MockImage(this.size); - - final Vector2 size; - +class _MockImage(final Vector2 size) extends Mock implements Image { @override int get width => size.x.toInt(); @@ -18,11 +14,9 @@ class _MockImage extends Mock implements Image { int get height => size.y.toInt(); } -class _MockSpriteSheet extends Mock implements SpriteSheet { - _MockSpriteSheet(this.tileSize); - - final Vector2 tileSize; - +class _MockSpriteSheet(final Vector2 tileSize) + extends Mock + implements SpriteSheet { @override Image get image => _MockImage(tileSize); } diff --git a/packages/flame/test/components/keyboard_listener_component_test.dart b/packages/flame/test/components/keyboard_listener_component_test.dart index 0937712c807..e8053b1861c 100644 --- a/packages/flame/test/components/keyboard_listener_component_test.dart +++ b/packages/flame/test/components/keyboard_listener_component_test.dart @@ -3,13 +3,13 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -abstract class _KeyCallStub { +abstract class _KeyCallStub() { bool onCall(Set keysPressed); } -class _KeyCallStubImpl extends Mock implements _KeyCallStub {} +class _KeyCallStubImpl() extends Mock implements _KeyCallStub; -class _MockKeyUpEvent extends Mock implements KeyUpEvent { +class _MockKeyUpEvent() extends Mock implements KeyUpEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); diff --git a/packages/flame/test/components/mixins/component_viewport_margin_test.dart b/packages/flame/test/components/mixins/component_viewport_margin_test.dart index a60399aef39..a213bf9739a 100644 --- a/packages/flame/test/components/mixins/component_viewport_margin_test.dart +++ b/packages/flame/test/components/mixins/component_viewport_margin_test.dart @@ -43,7 +43,8 @@ void main() { }); } -class _TestGame extends FlameGame {} +class _TestGame() extends FlameGame; -class _ComponentWithViewportMargin extends PositionComponent - with HasGameRef<_TestGame>, ComponentViewportMargin<_TestGame> {} +class _ComponentWithViewportMargin() + extends PositionComponent + with HasGameRef<_TestGame>, ComponentViewportMargin<_TestGame>; diff --git a/packages/flame/test/components/mixins/gesture_hitboxes_test.dart b/packages/flame/test/components/mixins/gesture_hitboxes_test.dart index 0201bd5ccfa..dca93f2205d 100644 --- a/packages/flame/test/components/mixins/gesture_hitboxes_test.dart +++ b/packages/flame/test/components/mixins/gesture_hitboxes_test.dart @@ -121,4 +121,4 @@ void main() { }); } -class _HitboxComponent extends PositionComponent with GestureHitboxes {} +class _HitboxComponent() extends PositionComponent with GestureHitboxes; diff --git a/packages/flame/test/components/mixins/has_ancestor_test.dart b/packages/flame/test/components/mixins/has_ancestor_test.dart index a312bbd99b8..58ec9551669 100644 --- a/packages/flame/test/components/mixins/has_ancestor_test.dart +++ b/packages/flame/test/components/mixins/has_ancestor_test.dart @@ -35,10 +35,10 @@ void main() { }); } -class _AncestorComponent extends Component {} +class _AncestorComponent() extends Component; -class _InBetweenComponent extends Component {} +class _InBetweenComponent() extends Component; -class _DifferentComponent extends Component {} +class _DifferentComponent() extends Component; -class _TestComponent extends Component with HasAncestor<_AncestorComponent> {} +class _TestComponent() extends Component with HasAncestor<_AncestorComponent>; diff --git a/packages/flame/test/components/mixins/has_decorator_test.dart b/packages/flame/test/components/mixins/has_decorator_test.dart index c110f7f29af..cb624770a4c 100644 --- a/packages/flame/test/components/mixins/has_decorator_test.dart +++ b/packages/flame/test/components/mixins/has_decorator_test.dart @@ -29,9 +29,9 @@ void main() { }); } -class _DecoratedComponent extends PositionComponent { - _DecoratedComponent({super.position, super.size}) - : super(anchor: Anchor.center); +class _DecoratedComponent({super.position, super.size}) + extends PositionComponent { + this : super(anchor: Anchor.center); final paint = Paint()..color = const Color(0xff30ccd2); diff --git a/packages/flame/test/components/mixins/has_game_ref_test.dart b/packages/flame/test/components/mixins/has_game_ref_test.dart index 562a5f8bdab..f7b01855c77 100644 --- a/packages/flame/test/components/mixins/has_game_ref_test.dart +++ b/packages/flame/test/components/mixins/has_game_ref_test.dart @@ -4,7 +4,7 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _GameRefGame extends FlameGame {} +class _GameRefGame() extends FlameGame; void main() { group('HasGameRef', () { @@ -105,21 +105,21 @@ void main() { }); } -class _Component extends Component with HasGameRef {} +class _Component() extends Component with HasGameRef; -class _MyGame extends FlameGame { +class _MyGame() extends FlameGame { bool calledFoo = false; void foo() { calledFoo = true; } } -class _FooComponent extends Component with HasGameRef<_MyGame> { +class _FooComponent() extends Component with HasGameRef<_MyGame> { void foo() { gameRef.foo(); } } -class _BarComponent extends Component with HasGameRef<_MyGame> {} +class _BarComponent() extends Component with HasGameRef<_MyGame>; -class _MockFlameGame extends Mock implements _MyGame {} +class _MockFlameGame() extends Mock implements _MyGame; diff --git a/packages/flame/test/components/mixins/has_paint_test.dart b/packages/flame/test/components/mixins/has_paint_test.dart index 2cfcadaea7c..540cd173b2a 100644 --- a/packages/flame/test/components/mixins/has_paint_test.dart +++ b/packages/flame/test/components/mixins/has_paint_test.dart @@ -318,12 +318,13 @@ void main() { }); } -class _MyComponent extends PositionComponent with HasPaint {} +class _MyComponent() extends PositionComponent with HasPaint; -enum _MyComponentKeys { +enum _MyComponentKeys() { background, foreground, } -class _MyComponentWithType extends PositionComponent - with HasPaint<_MyComponentKeys> {} +class _MyComponentWithType() + extends PositionComponent + with HasPaint<_MyComponentKeys>; diff --git a/packages/flame/test/components/mixins/has_time_scale_self_test.dart b/packages/flame/test/components/mixins/has_time_scale_self_test.dart index 4d50193c4d4..046a3a2012c 100644 --- a/packages/flame/test/components/mixins/has_time_scale_self_test.dart +++ b/packages/flame/test/components/mixins/has_time_scale_self_test.dart @@ -50,9 +50,7 @@ void main() { }); } -class _Recorder extends Component { - _Recorder({super.children}); - +class _Recorder({super.children}) extends Component { final List recordedDts = []; @override @@ -61,8 +59,8 @@ class _Recorder extends Component { } } -class _ScaledRecorder extends _Recorder with CustomTraversal, HasTimeScale { - _ScaledRecorder({super.children}); -} +class _ScaledRecorder({super.children}) + extends _Recorder + with CustomTraversal, HasTimeScale; -class _PausableGame extends FlameGame with HasTimeScale {} +class _PausableGame() extends FlameGame with HasTimeScale; diff --git a/packages/flame/test/components/mixins/has_time_scale_test.dart b/packages/flame/test/components/mixins/has_time_scale_test.dart index c375cc22bb5..42f0a8c31c8 100644 --- a/packages/flame/test/components/mixins/has_time_scale_test.dart +++ b/packages/flame/test/components/mixins/has_time_scale_test.dart @@ -145,12 +145,13 @@ void main() { }); } -class _GameWithTimeScale extends FlameGame with HasTimeScale {} +class _GameWithTimeScale() extends FlameGame with HasTimeScale; -class _ComponentWithTimeScale extends Component - with CustomTraversal, HasTimeScale {} +class _ComponentWithTimeScale() + extends Component + with CustomTraversal, HasTimeScale; -class _MovingComponent extends PositionComponent { +class _MovingComponent() extends PositionComponent { final speed = 1.0; @override void update(double dt) => position.setValues(position.x + speed * dt, 0); diff --git a/packages/flame/test/components/mixins/has_visibility_test.dart b/packages/flame/test/components/mixins/has_visibility_test.dart index b88873a0445..bef8ce29960 100644 --- a/packages/flame/test/components/mixins/has_visibility_test.dart +++ b/packages/flame/test/components/mixins/has_visibility_test.dart @@ -20,7 +20,7 @@ void main() { }); } -class _MySpriteComponent extends PositionComponent with HasVisibility { +class _MySpriteComponent() extends PositionComponent with HasVisibility { late final Sprite sprite; @override @@ -38,8 +38,8 @@ class _MySpriteComponent extends PositionComponent with HasVisibility { /// renders a rectangle, and then the children will render. /// In this test the visibility of [mySprite] is set to /// false, so only the rectangle is expected to be rendered. -class _MyComponent extends PositionComponent { - _MyComponent() : super(size: Vector2(300, 400)) { +class _MyComponent() extends PositionComponent { + this : super(size: Vector2(300, 400)) { mySprite = _MySpriteComponent()..position = Vector2(150, 200); add(mySprite); } diff --git a/packages/flame/test/components/mixins/has_world_ref_test.dart b/packages/flame/test/components/mixins/has_world_ref_test.dart index f99968dad9c..e9f93423f7b 100644 --- a/packages/flame/test/components/mixins/has_world_ref_test.dart +++ b/packages/flame/test/components/mixins/has_world_ref_test.dart @@ -7,7 +7,7 @@ import 'package:flame_test/flame_test.dart' show testWithGame; import 'package:flutter_test/flutter_test.dart' show group; import 'package:test/expect.dart' show expect; -class _ParentComponent extends Component { +class _ParentComponent() extends Component { bool wasRemoved = false; @override @@ -17,7 +17,7 @@ class _ParentComponent extends Component { } } -class _ChildComponent extends _ParentComponent with HasWorldRef {} +class _ChildComponent() extends _ParentComponent with HasWorldRef; void main() { group('HasWorldRef', () { diff --git a/packages/flame/test/components/mixins/parent_is_a_test.dart b/packages/flame/test/components/mixins/parent_is_a_test.dart index 664b7684afe..243a4891d78 100644 --- a/packages/flame/test/components/mixins/parent_is_a_test.dart +++ b/packages/flame/test/components/mixins/parent_is_a_test.dart @@ -31,8 +31,8 @@ void main() { }); } -class _ParentComponent extends Component {} +class _ParentComponent() extends Component; -class _DifferentComponent extends Component {} +class _DifferentComponent() extends Component; -class _TestComponent extends Component with ParentIsA<_ParentComponent> {} +class _TestComponent() extends Component with ParentIsA<_ParentComponent>; diff --git a/packages/flame/test/components/mixins/snapshot_test.dart b/packages/flame/test/components/mixins/snapshot_test.dart index 5b5adc794aa..65026c0c889 100644 --- a/packages/flame/test/components/mixins/snapshot_test.dart +++ b/packages/flame/test/components/mixins/snapshot_test.dart @@ -170,12 +170,8 @@ void main() { ); } -class _SnapshotTestGame extends FlameGame { +class _SnapshotTestGame({var bool renderSnapshot = true}) extends FlameGame { late final _MockSnapshotComponent snapshotComponent; - bool renderSnapshot; - - _SnapshotTestGame({this.renderSnapshot = true}); - @override Future onLoad() async { // Add a snapshot-enabled component that has it's own rendered content @@ -218,7 +214,7 @@ class _SnapshotTestGame extends FlameGame { } } -class _MockSnapshotComponent extends _MockComponentSuper with Snapshot { +class _MockSnapshotComponent() extends _MockComponentSuper with Snapshot { int renderCalled = 0; int renderTreeCalled = 0; int takeSnapshotCalled = 0; @@ -244,7 +240,7 @@ class _MockSnapshotComponent extends _MockComponentSuper with Snapshot { /// Mock a superclass just so we can count how many times super.renderTree has /// been called -class _MockComponentSuper extends PositionComponent { +class _MockComponentSuper() extends PositionComponent { int parentRenderTreeCalled = 0; @override diff --git a/packages/flame/test/components/parallax_test.dart b/packages/flame/test/components/parallax_test.dart index b5be02c2a42..9cdc2d21682 100644 --- a/packages/flame/test/components/parallax_test.dart +++ b/packages/flame/test/components/parallax_test.dart @@ -7,11 +7,9 @@ import 'package:flame_test/flame_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; -class _ParallaxGame extends FlameGame { +class _ParallaxGame({final Vector2? parallaxSize}) extends FlameGame { late final ParallaxComponent parallaxComponent; - late final Vector2? parallaxSize; - - _ParallaxGame({this.parallaxSize}) { + this { onGameResize(Vector2.all(500)); } @@ -27,9 +25,9 @@ class _ParallaxGame extends FlameGame { } } -class _MockImages extends Mock implements Images {} +class _MockImages() extends Mock implements Images; -class _MockImage extends Mock implements Image { +class _MockImage() extends Mock implements Image { @override int get height => 100; @@ -37,11 +35,9 @@ class _MockImage extends Mock implements Image { int get width => 100; } -class _SlowLoadParallaxGame extends FlameGame { +class _SlowLoadParallaxGame({final Vector2? parallaxSize}) extends FlameGame { late final ParallaxComponent parallaxComponent; - late final Vector2? parallaxSize; - - _SlowLoadParallaxGame({this.parallaxSize}) { + this { onGameResize(Vector2.all(500)); } diff --git a/packages/flame/test/components/position_component_test.dart b/packages/flame/test/components/position_component_test.dart index cd69b43bf88..36d8f3e8a2e 100644 --- a/packages/flame/test/components/position_component_test.dart +++ b/packages/flame/test/components/position_component_test.dart @@ -1339,13 +1339,9 @@ void main() { }); } -class _MyHitboxComponent extends PositionComponent with GestureHitboxes {} - -class _MyDebugComponent extends PositionComponent { - _MyDebugComponent({this.name}); - - final String? name; +class _MyHitboxComponent() extends PositionComponent with GestureHitboxes; +class _MyDebugComponent({final String? name}) extends PositionComponent { @override bool get debugMode => true; diff --git a/packages/flame/test/components/priority_test.dart b/packages/flame/test/components/priority_test.dart index c3db2193de7..9ab46462977 100644 --- a/packages/flame/test/components/priority_test.dart +++ b/packages/flame/test/components/priority_test.dart @@ -259,12 +259,12 @@ void main() { }); } -class _PriorityComponent extends Component { - _PriorityComponent(int priority) : super(priority: priority); +class _PriorityComponent(int priority) extends Component { + this : super(priority: priority); } -class _ParentWithReorderSpy extends Component { - _ParentWithReorderSpy(int priority) : super(priority: priority); +class _ParentWithReorderSpy(int priority) extends Component { + this : super(priority: priority); int callCount = 0; diff --git a/packages/flame/test/components/route_test.dart b/packages/flame/test/components/route_test.dart index 2098ade5b03..6de23ad98c2 100644 --- a/packages/flame/test/components/route_test.dart +++ b/packages/flame/test/components/route_test.dart @@ -515,19 +515,15 @@ void main() { }); } -class _CustomRoute extends Route { - _CustomRoute({ - Component Function()? builder, - super.transparent, - super.maintainState, - this._onPush, - this._onPop, - this._build, - }) : super(builder); - - final void Function(Route, Route?)? _onPush; - final void Function(Route, Route)? _onPop; - final Component Function(Route)? _build; +class _CustomRoute({ + Component Function()? builder, + super.transparent, + super.maintainState, + final void Function(Route, Route?)? _onPush, + final void Function(Route, Route)? _onPop, + final Component Function(Route)? _build, +}) extends Route { + this : super(builder); @override void onPush(Route? route) => _onPush?.call(this, route); @@ -539,7 +535,7 @@ class _CustomRoute extends Route { Component build() => _build?.call(this) ?? super.build(); } -class _TimerComponent extends Component { +class _TimerComponent() extends Component { double elapsedTime = 0; @override @@ -548,14 +544,12 @@ class _TimerComponent extends Component { } } -class _ColoredComponent extends PositionComponent { - _ColoredComponent({ - required Color color, - super.position, - super.size, - }) : _paint = Paint()..color = color; - - final Paint _paint; +class _ColoredComponent({ + required Color color, + super.position, + super.size, +}) extends PositionComponent { + final Paint _paint = Paint()..color = color; @override void render(Canvas canvas) { @@ -563,12 +557,12 @@ class _ColoredComponent extends PositionComponent { } } -class _HeavyComponent extends PositionComponent { +class _HeavyComponent() extends PositionComponent { Duration dummyTime = const Duration(seconds: 3); Completer completer = Completer(); @override FutureOr onLoad() async { await completer.future; - return super.onLoad(); + await super.onLoad(); } } diff --git a/packages/flame/test/components/router_component_test.dart b/packages/flame/test/components/router_component_test.dart index 88685eea857..f254fa13ffd 100644 --- a/packages/flame/test/components/router_component_test.dart +++ b/packages/flame/test/components/router_component_test.dart @@ -1,7 +1,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame_test/flame_test.dart'; -import 'package:flutter/widgets.dart' hide Route, OverlayRoute; +import 'package:flutter/widgets.dart' hide OverlayRoute, Route; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -384,8 +384,8 @@ void main() { GameWidget( game: game, overlayBuilderMap: { - 'first!': (_, __) => Container(key: key1), - 'second': (_, __) => Container(key: key2), + 'first!': (_, _) => Container(key: key1), + 'second': (_, _) => Container(key: key2), }, ), ); @@ -438,17 +438,17 @@ void main() { }); } -class _ComponentA extends Component {} +class _ComponentA() extends Component; -class _ComponentB extends Component {} +class _ComponentB() extends Component; -class _ComponentC extends Component {} +class _ComponentC() extends Component; -class _ComponentD extends Component {} +class _ComponentD() extends Component; -class _ComponentE extends Component {} +class _ComponentE() extends Component; -class _TestRoute extends Route { +class _TestRoute(super.builder) extends Route { int onPopTimes = 0; int onPushTimes = 0; int didPopTimes = 0; @@ -458,8 +458,6 @@ class _TestRoute extends Route { String? lastDidPopNextRoute; String? lastDidPushPreviousRoute; - _TestRoute(super.builder); - @override void onPop(Route nextRoute) { super.onPop(nextRoute); diff --git a/packages/flame/test/components/scroll_text_box_component_test.dart b/packages/flame/test/components/scroll_text_box_component_test.dart index d56d60d47f3..5278e2d1e9b 100644 --- a/packages/flame/test/components/scroll_text_box_component_test.dart +++ b/packages/flame/test/components/scroll_text_box_component_test.dart @@ -101,6 +101,6 @@ lines.''', }); } -class _MockOnCompleteCallback extends Mock { +class _MockOnCompleteCallback() extends Mock { void call(); } diff --git a/packages/flame/test/components/spawn_component_test.dart b/packages/flame/test/components/spawn_component_test.dart index 79c12c88722..26914ec80df 100644 --- a/packages/flame/test/components/spawn_component_test.dart +++ b/packages/flame/test/components/spawn_component_test.dart @@ -546,4 +546,4 @@ void main() { }); } -class _CountComponent extends PositionComponent {} +class _CountComponent() extends PositionComponent; diff --git a/packages/flame/test/components/sprite_animation_group_component_test.dart b/packages/flame/test/components/sprite_animation_group_component_test.dart index f94f5985e9b..cde1ff87e2c 100644 --- a/packages/flame/test/components/sprite_animation_group_component_test.dart +++ b/packages/flame/test/components/sprite_animation_group_component_test.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -enum _AnimationState { +enum _AnimationState() { idle, running, } diff --git a/packages/flame/test/components/sprite_group_component_test.dart b/packages/flame/test/components/sprite_group_component_test.dart index 7a9ce07152c..dd1b61bfab2 100644 --- a/packages/flame/test/components/sprite_group_component_test.dart +++ b/packages/flame/test/components/sprite_group_component_test.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -enum _SpriteState { +enum _SpriteState() { idle, running, flying, diff --git a/packages/flame/test/components/text_box_component_test.dart b/packages/flame/test/components/text_box_component_test.dart index b4de6881e2b..490b08eb160 100644 --- a/packages/flame/test/components/text_box_component_test.dart +++ b/packages/flame/test/components/text_box_component_test.dart @@ -50,8 +50,7 @@ void main() { test('Chinese text wraps correctly without spaces', () { const maxWidth = 100.0; final c = TextBoxComponent( - text: - '''编写这些测试的人明显是一个天才(而且非常谦虚)。他们值得终生免费咖啡。这些测试需要奥妙的智慧、无穷的耐心和可能太多的咖啡因。''', + text: '''编写这些测试的人明显是一个天才(而且非常谦虚)。他们值得终生免费咖啡。这些测试需要奥妙的智慧、无穷的耐心和可能太多的咖啡因。''', textRenderer: TextPaint( style: const TextStyle(fontSize: 16), ), @@ -78,8 +77,7 @@ void main() { test('Japanese text wraps correctly without spaces', () { const maxWidth = 100.0; final c = TextBoxComponent( - text: - '''これらのテストを書いた人は明らかに天才です(そしてとても謙虚です)。彼らは生涉無料コーヒーを受けるに値します。これらのテストは絶妙な知恵、無限の忍耐、そしておそらくカフェインの取りすぎが必要でした。''', + text: '''これらのテストを書いた人は明らかに天才です(そしてとても謙虚です)。彼らは生涉無料コーヒーを受けるに値します。これらのテストは絶妙な知恵、無限の忍耐、そしておそらくカフェインの取りすぎが必要でした。''', textRenderer: TextPaint( style: const TextStyle(fontSize: 16), ), @@ -105,8 +103,7 @@ void main() { test('Korean text wraps correctly without spaces', () { const maxWidth = 100.0; final c = TextBoxComponent( - text: - '''이테스트를작성한사람은분명천재입니다(그리고매우겸손합니다)。그들은평생무료커피를받을자격이있습니다。이테스트들은놀라운지혜와무한한인내심그리고아마도너무많은카페인이필요했습니다。''', + text: '''이테스트를작성한사람은분명천재입니다(그리고매우겸손합니다)。그들은평생무료커피를받을자격이있습니다。이테스트들은놀라운지혜와무한한인내심그리고아마도너무많은카페인이필요했습니다。''', textRenderer: TextPaint( style: const TextStyle(fontSize: 16), ), @@ -426,16 +423,17 @@ lines.''', ); } -class _FramedTextBox extends TextBoxComponent { - _FramedTextBox({ - required String super.text, - super.align, - super.position, - super.size, - super.anchor, - }) : super( - textRenderer: DebugTextRenderer(fontSize: 22), - ); +class _FramedTextBox({ + required String super.text, + super.align, + super.position, + super.size, + super.anchor, +}) extends TextBoxComponent { + this + : super( + textRenderer: DebugTextRenderer(fontSize: 22), + ); final Paint _borderPaint = Paint() ..style = PaintingStyle.stroke diff --git a/packages/flame/test/components/text_component_test.dart b/packages/flame/test/components/text_component_test.dart index 222ddccdefb..018d0558972 100644 --- a/packages/flame/test/components/text_component_test.dart +++ b/packages/flame/test/components/text_component_test.dart @@ -28,11 +28,8 @@ void main() { const _ascent = 10.0; -class _RecordingTextRenderer extends TextRenderer { - _RecordingTextRenderer(this.elements); - - final List<_RecordingTextElement> elements; - +class _RecordingTextRenderer(final List<_RecordingTextElement> elements) + extends TextRenderer { @override InlineTextElement format(String text) { final element = _RecordingTextElement(); @@ -44,7 +41,7 @@ class _RecordingTextRenderer extends TextRenderer { TextRenderer copyWithPaint(Paint paint) => _RecordingTextRenderer(elements); } -class _RecordingTextElement extends InlineTextElement { +class _RecordingTextElement() extends InlineTextElement { final translations = []; @override diff --git a/packages/flame/test/components/timer_component_test.dart b/packages/flame/test/components/timer_component_test.dart index 81cf5c24b24..1dae1b9add1 100644 --- a/packages/flame/test/components/timer_component_test.dart +++ b/packages/flame/test/components/timer_component_test.dart @@ -4,10 +4,10 @@ import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _MyTimerComponent extends TimerComponent { +class _MyTimerComponent() extends TimerComponent { int count = 0; - _MyTimerComponent() + this : super( period: 1, repeat: true, @@ -21,10 +21,10 @@ class _MyTimerComponent extends TimerComponent { } } -class _MyTickOnLoadTimerComponent extends TimerComponent { +class _MyTickOnLoadTimerComponent() extends TimerComponent { int count = 0; - _MyTickOnLoadTimerComponent() + this : super( period: 1, repeat: true, @@ -39,8 +39,8 @@ class _MyTickOnLoadTimerComponent extends TimerComponent { } } -class _NonRepeatingTimerComponent extends TimerComponent { - _NonRepeatingTimerComponent() +class _NonRepeatingTimerComponent() extends TimerComponent { + this : super( period: 1, repeat: false, diff --git a/packages/flame/test/components/toogle_button_component_test.dart b/packages/flame/test/components/toogle_button_component_test.dart index 10c774d0536..c0d30f4d55d 100644 --- a/packages/flame/test/components/toogle_button_component_test.dart +++ b/packages/flame/test/components/toogle_button_component_test.dart @@ -244,13 +244,9 @@ void main() { }); } -class _SimpleStatelessWidget extends StatelessWidget { - const _SimpleStatelessWidget({ - required this._build, - }); - - final Widget Function(BuildContext) _build; - +class const _SimpleStatelessWidget({ + required final Widget Function(BuildContext) _build, +}) extends StatelessWidget { @override Widget build(BuildContext context) => _build(context); } diff --git a/packages/flame/test/components/value_route_test.dart b/packages/flame/test/components/value_route_test.dart index dacfb47c637..89c2cf99fa3 100644 --- a/packages/flame/test/components/value_route_test.dart +++ b/packages/flame/test/components/value_route_test.dart @@ -107,23 +107,18 @@ void main() { }); } -class _CustomValueRoute extends ValueRoute { - _CustomValueRoute({ - required T defaultValue, - required this.builder, - }) : super(value: defaultValue); - - final Component Function(_CustomValueRoute) builder; +class _CustomValueRoute({ + required T defaultValue, + required final Component Function(_CustomValueRoute) builder, +}) extends ValueRoute { + this : super(value: defaultValue); @override Component build() => builder(this); } -class _CustomComponent extends Component { - _CustomComponent({this.onUpdate}); - - final void Function(double dt)? onUpdate; - +class _CustomComponent({final void Function(double dt)? onUpdate}) + extends Component { @override void update(double dt) => onUpdate?.call(dt); } diff --git a/packages/flame/test/components/widget_component_test.dart b/packages/flame/test/components/widget_component_test.dart index 2507e16d7b1..8787f499e47 100644 --- a/packages/flame/test/components/widget_component_test.dart +++ b/packages/flame/test/components/widget_component_test.dart @@ -10,7 +10,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; -class _TappableComponent extends PositionComponent with TapCallbacks { +class _TappableComponent() extends PositionComponent with TapCallbacks { int tapUpCount = 0; @override @@ -19,9 +19,9 @@ class _TappableComponent extends PositionComponent with TapCallbacks { } } -class _SnapshotComponent extends PositionComponent with Snapshot {} +class _SnapshotComponent() extends PositionComponent with Snapshot; -class _CameraGame extends FlameGame { +class _CameraGame() extends FlameGame { @override Future onLoad() async { camera.viewfinder.zoom = 2; @@ -30,8 +30,8 @@ class _CameraGame extends FlameGame { } } -class _ClippedCameraGame extends FlameGame { - _ClippedCameraGame() +class _ClippedCameraGame() extends FlameGame { + this : super( camera: CameraComponent.withFixedResolution(width: 400, height: 400), ); @@ -59,12 +59,8 @@ Future _pumpGame(WidgetTester tester, FlameGame game) async { await tester.pump(); } -class _Button extends StatelessWidget { - const _Button(this.label, this.onPressed); - - final String label; - final VoidCallback onPressed; - +class const _Button(final String label, final VoidCallback onPressed) + extends StatelessWidget { @override Widget build(BuildContext context) { return Material( @@ -73,7 +69,7 @@ class _Button extends StatelessWidget { } } -class _ResizeCountingGame extends FlameGame { +class _ResizeCountingGame() extends FlameGame { int resizeCount = 0; @override @@ -83,7 +79,7 @@ class _ResizeCountingGame extends FlameGame { } } -class _SplitScreenGame extends FlameGame { +class _SplitScreenGame() extends FlameGame { @override Future onLoad() async { camera.viewport = FixedSizeViewport(400, 600); @@ -96,7 +92,7 @@ class _SplitScreenGame extends FlameGame { } } -class _HidableComponent extends PositionComponent with HasVisibility {} +class _HidableComponent() extends PositionComponent with HasVisibility; void main() { group('WidgetComponent', () { diff --git a/packages/flame/test/components/world_route_test.dart b/packages/flame/test/components/world_route_test.dart index 73655cc6d3a..a7a5a6b2b57 100644 --- a/packages/flame/test/components/world_route_test.dart +++ b/packages/flame/test/components/world_route_test.dart @@ -2,11 +2,11 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flutter_test/flutter_test.dart'; -class _TestWorld1 extends World { +class _TestWorld1() extends World { int value = 0; } -class _TestWorld2 extends World {} +class _TestWorld2() extends World; void main() { group('WorldRoute', () { diff --git a/packages/flame/test/custom_component.dart b/packages/flame/test/custom_component.dart index e0e788aaba0..a935e3d404f 100644 --- a/packages/flame/test/custom_component.dart +++ b/packages/flame/test/custom_component.dart @@ -5,25 +5,16 @@ import 'package:flame/components.dart'; /// A component where all event handlers can be provided as parameters in the /// constructor. -class CustomComponent extends Component { - CustomComponent({ - this._onGameResize, - this._onLoad, - this._onMount, - this._onRemove, - this._onUpdate, - this._onRender, - super.priority, - super.children, - }); - - final void Function(CustomComponent, Vector2)? _onGameResize; - final FutureOr Function(CustomComponent)? _onLoad; - final void Function(CustomComponent)? _onMount; - final void Function(CustomComponent)? _onRemove; - final void Function(CustomComponent, double)? _onUpdate; - final void Function(CustomComponent, Canvas)? _onRender; - +class CustomComponent({ + final void Function(CustomComponent, Vector2)? _onGameResize, + final FutureOr Function(CustomComponent)? _onLoad, + final void Function(CustomComponent)? _onMount, + final void Function(CustomComponent)? _onRemove, + final void Function(CustomComponent, double)? _onUpdate, + final void Function(CustomComponent, Canvas)? _onRender, + super.priority, + super.children, +}) extends Component { @override void onGameResize(Vector2 size) { super.onGameResize(size); diff --git a/packages/flame/test/devtools/input_connector_test.dart b/packages/flame/test/devtools/input_connector_test.dart index b8c791f6111..0efec001185 100644 --- a/packages/flame/test/devtools/input_connector_test.dart +++ b/packages/flame/test/devtools/input_connector_test.dart @@ -6,8 +6,8 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -class _Tapper extends PositionComponent with TapCallbacks { - _Tapper() : super(position: Vector2(10, 10), size: Vector2(20, 20)); +class _Tapper() extends PositionComponent with TapCallbacks { + this : super(position: Vector2(10, 10), size: Vector2(20, 20)); final taps = []; @@ -15,8 +15,8 @@ class _Tapper extends PositionComponent with TapCallbacks { void onTapUp(TapUpEvent event) => taps.add(event.localPosition); } -class _Dragger extends PositionComponent with DragCallbacks { - _Dragger() : super(size: Vector2(100, 100)); +class _Dragger() extends PositionComponent with DragCallbacks { + this : super(size: Vector2(100, 100)); int starts = 0; int updates = 0; @@ -38,9 +38,9 @@ class _Dragger extends PositionComponent with DragCallbacks { } } -class _KeyGame extends FlameGame with HasKeyboardHandlerComponents {} +class _KeyGame() extends FlameGame with HasKeyboardHandlerComponents; -class _Listener extends Component with KeyboardHandler { +class _Listener() extends Component with KeyboardHandler { final events = []; final pressed = >[]; diff --git a/packages/flame/test/devtools/snapshot_connectors_test.dart b/packages/flame/test/devtools/snapshot_connectors_test.dart index 1d3240dbc43..1b81cb0a69b 100644 --- a/packages/flame/test/devtools/snapshot_connectors_test.dart +++ b/packages/flame/test/devtools/snapshot_connectors_test.dart @@ -20,7 +20,7 @@ Future _pixelAt(Image image, int x, int y) async { ); } -class _BackgroundGame extends FlameGame { +class _BackgroundGame() extends FlameGame { @override Color backgroundColor() => const Color(0xFF0000FF); } diff --git a/packages/flame/test/effects/color_effect_test.dart b/packages/flame/test/effects/color_effect_test.dart index 2c7492582f3..951144f4ef7 100644 --- a/packages/flame/test/effects/color_effect_test.dart +++ b/packages/flame/test/effects/color_effect_test.dart @@ -4,7 +4,7 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _PaintComponent extends Component with HasPaint {} +class _PaintComponent() extends Component with HasPaint; void main() { group('ColorEffect', () { diff --git a/packages/flame/test/effects/controllers/effect_controller_test.dart b/packages/flame/test/effects/controllers/effect_controller_test.dart index 8a33a24bf82..bd02eb02d7b 100644 --- a/packages/flame/test/effects/controllers/effect_controller_test.dart +++ b/packages/flame/test/effects/controllers/effect_controller_test.dart @@ -7,11 +7,11 @@ import 'package:flutter/animation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -abstract class _Callback { +abstract class _Callback() { void call(); } -class _CallbackMock extends Mock implements _Callback {} +class _CallbackMock() extends Mock implements _Callback; void main() { group('EffectController', () { diff --git a/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart b/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart index 8218e3e1e5a..a3601d98985 100644 --- a/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart +++ b/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart @@ -38,16 +38,13 @@ void main() { }); } -class _TestEffectController extends _MockEffectController +class _TestEffectController(final _MockEffectController _child) + extends _MockEffectController with HasSingleChildEffectController<_MockEffectController> { - _TestEffectController(_MockEffectController child) : _child = child; - - final _MockEffectController _child; - @override _MockEffectController get child => _child; } -class _MockEffectController extends Mock implements EffectController {} +class _MockEffectController() extends Mock implements EffectController; -class _MockEffect extends Mock implements Effect {} +class _MockEffect() extends Mock implements Effect; diff --git a/packages/flame/test/effects/controllers/random_effect_controller_test.dart b/packages/flame/test/effects/controllers/random_effect_controller_test.dart index 11ea2bc290f..b969f389559 100644 --- a/packages/flame/test/effects/controllers/random_effect_controller_test.dart +++ b/packages/flame/test/effects/controllers/random_effect_controller_test.dart @@ -3,7 +3,7 @@ import 'dart:math'; import 'package:flame/effects.dart'; import 'package:test/test.dart'; -class _MyRandom implements Random { +class _MyRandom() implements Random { double value = 0.5; @override @@ -16,8 +16,8 @@ class _MyRandom implements Random { int nextInt(int max) => 1; } -class _MyRandomVariable extends RandomVariable { - _MyRandomVariable() : super(null); +class _MyRandomVariable() extends RandomVariable { + this : super(null); double value = 1.23; @override diff --git a/packages/flame/test/effects/effect_test.dart b/packages/flame/test/effects/effect_test.dart index 68a7f53600a..33710dcf673 100644 --- a/packages/flame/test/effects/effect_test.dart +++ b/packages/flame/test/effects/effect_test.dart @@ -4,8 +4,8 @@ import 'package:flame/src/effects/effect.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _MyEffect extends Effect { - _MyEffect(super.controller) { +class _MyEffect(super.controller) extends Effect { + this { completed.whenComplete(() => ++completedCounter); } diff --git a/packages/flame/test/effects/glow_effect.dart b/packages/flame/test/effects/glow_effect.dart index d2c471ad08c..abd8c0326b1 100644 --- a/packages/flame/test/effects/glow_effect.dart +++ b/packages/flame/test/effects/glow_effect.dart @@ -32,4 +32,4 @@ void main() { }); } -class _PaintComponent extends Component with HasPaint {} +class _PaintComponent() extends Component with HasPaint; diff --git a/packages/flame/test/effects/hue_effect_test.dart b/packages/flame/test/effects/hue_effect_test.dart index 8c769d19f67..cbb7186008d 100644 --- a/packages/flame/test/effects/hue_effect_test.dart +++ b/packages/flame/test/effects/hue_effect_test.dart @@ -101,4 +101,4 @@ void main() { }); } -class _PaintComponent extends Component with HasPaint {} +class _PaintComponent() extends Component with HasPaint; diff --git a/packages/flame/test/effects/move_by_effect_test.dart b/packages/flame/test/effects/move_by_effect_test.dart index 34070fb51ea..0bac331a3d5 100644 --- a/packages/flame/test/effects/move_by_effect_test.dart +++ b/packages/flame/test/effects/move_by_effect_test.dart @@ -61,14 +61,11 @@ void main() { }); } -class _RectComponent extends Component { +class _RectComponent() extends Component { Rect rect = Rect.zero; } -class _TopLeftCorner implements PositionProvider { - _TopLeftCorner(this.target); - _RectComponent target; - +class _TopLeftCorner(var _RectComponent target) implements PositionProvider { @override Vector2 get position => Vector2(target.rect.left, target.rect.top); diff --git a/packages/flame/test/effects/opacity_effect_test.dart b/packages/flame/test/effects/opacity_effect_test.dart index f880709a893..39d94f5ab7a 100644 --- a/packages/flame/test/effects/opacity_effect_test.dart +++ b/packages/flame/test/effects/opacity_effect_test.dart @@ -7,18 +7,23 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; -class _PaintComponent extends Component with HasPaint {} +class _PaintComponent() extends Component with HasPaint; -class _CustomPaintComponent extends Component +class _CustomPaintComponent(Map paints) + extends Component with HasPaint { - _CustomPaintComponent(Map paints) { + this { for (final p in paints.entries) { setPaint(p.key, p.value); } } } -enum _PaintTypes { paint1, paint2, paint3 } +enum _PaintTypes() { + paint1, + paint2, + paint3, +} void main() { const epsilon = 0.004; // 1/255, since alpha only holds 8 bits diff --git a/packages/flame/test/effects/size_effect_test.dart b/packages/flame/test/effects/size_effect_test.dart index 1ff567ef793..0900da6d044 100644 --- a/packages/flame/test/effects/size_effect_test.dart +++ b/packages/flame/test/effects/size_effect_test.dart @@ -155,4 +155,4 @@ void main() { }); } -class _ResizableComponent extends PositionComponent implements SizeProvider {} +class _ResizableComponent() extends PositionComponent implements SizeProvider; diff --git a/packages/flame/test/effects/transform2d_effect_test.dart b/packages/flame/test/effects/transform2d_effect_test.dart index 578dd8fad3b..4a6496daa03 100644 --- a/packages/flame/test/effects/transform2d_effect_test.dart +++ b/packages/flame/test/effects/transform2d_effect_test.dart @@ -4,9 +4,7 @@ import 'package:flame/src/effects/transform2d_effect.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _MyEffect extends Transform2DEffect { - _MyEffect(super.controller); - +class _MyEffect(super.controller) extends Transform2DEffect { @override void apply(double progress) {} } diff --git a/packages/flame/test/events/component_mixins/double_tap_callbacks_test.dart b/packages/flame/test/events/component_mixins/double_tap_callbacks_test.dart index a84da823e97..aa33d6f55aa 100644 --- a/packages/flame/test/events/component_mixins/double_tap_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/double_tap_callbacks_test.dart @@ -161,9 +161,10 @@ void main() { }); } -class _DoubleTapCallbacksComponent extends PositionComponent +class _DoubleTapCallbacksComponent() + extends PositionComponent with DoubleTapCallbacks { - _DoubleTapCallbacksComponent() { + this { anchor = Anchor.center; size = Vector2.all(10); } diff --git a/packages/flame/test/events/component_mixins/drag_callbacks_test.dart b/packages/flame/test/events/component_mixins/drag_callbacks_test.dart index bf015c0ac6c..5ae1ad0d8e7 100644 --- a/packages/flame/test/events/component_mixins/drag_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/drag_callbacks_test.dart @@ -935,21 +935,23 @@ void main() { ); } -class _SingleDragComponent extends PositionComponent +class _SingleDragComponent() + extends PositionComponent with DragCallbacks, DragCounter { @override bool get allowsMultiPointerDrag => false; } -class _SingleDragScaleComponent extends PositionComponent +class _SingleDragScaleComponent() + extends PositionComponent with DragCallbacks, DragCounter, ScaleCallbacks, ScaleCounter { @override bool get allowsMultiPointerDrag => false; } -class _TapCounterComponent extends PositionComponent with TapCallbacks { - _TapCounterComponent({super.position, super.size}); - +class _TapCounterComponent({super.position, super.size}) + extends PositionComponent + with TapCallbacks { int nTapDown = 0; int nTapUp = 0; int nTapCancel = 0; diff --git a/packages/flame/test/events/component_mixins/hover_callbacks_test.dart b/packages/flame/test/events/component_mixins/hover_callbacks_test.dart index e9060346c8c..b3e41468200 100644 --- a/packages/flame/test/events/component_mixins/hover_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/hover_callbacks_test.dart @@ -160,10 +160,7 @@ mixin _HoverInspector on HoverCallbacks { } } -class _HoverCallbacksComponent extends PositionComponent - with HoverCallbacks, _HoverInspector { - _HoverCallbacksComponent({ - super.position, - super.size, - }); -} +class _HoverCallbacksComponent({ + super.position, + super.size, +}) extends PositionComponent with HoverCallbacks, _HoverInspector; diff --git a/packages/flame/test/events/component_mixins/ignore_events_test.dart b/packages/flame/test/events/component_mixins/ignore_events_test.dart index 6f15f64a4fc..6f659687205 100644 --- a/packages/flame/test/events/component_mixins/ignore_events_test.dart +++ b/packages/flame/test/events/component_mixins/ignore_events_test.dart @@ -138,8 +138,8 @@ mixin _TapCounter on TapCallbacks { } } -class _IgnoreTapCallbacksComponent extends PositionComponent +class _IgnoreTapCallbacksComponent({super.position, super.children}) + extends PositionComponent with TapCallbacks, _TapCounter, IgnoreEvents { - _IgnoreTapCallbacksComponent({super.position, super.children}) - : super(size: Vector2.all(10)); + this : super(size: Vector2.all(10)); } diff --git a/packages/flame/test/events/component_mixins/input_test_helper.dart b/packages/flame/test/events/component_mixins/input_test_helper.dart index f8ed4e5e9f9..5e1fb4ef828 100644 --- a/packages/flame/test/events/component_mixins/input_test_helper.dart +++ b/packages/flame/test/events/component_mixins/input_test_helper.dart @@ -91,21 +91,14 @@ mixin ScaleCounter on ScaleCallbacks { } } -class DragWithCallbacksComponent extends PositionComponent with DragCallbacks { - DragWithCallbacksComponent({ - this._onDragStart, - this._onDragUpdate, - this._onDragEnd, - this._onDragCancel, - super.position, - super.size, - }); - - final void Function(DragStartEvent)? _onDragStart; - final void Function(DragUpdateEvent)? _onDragUpdate; - final void Function(DragEndEvent)? _onDragEnd; - final void Function(DragCancelEvent)? _onDragCancel; - +class DragWithCallbacksComponent({ + final void Function(DragStartEvent)? _onDragStart, + final void Function(DragUpdateEvent)? _onDragUpdate, + final void Function(DragEndEvent)? _onDragEnd, + final void Function(DragCancelEvent)? _onDragCancel, + super.position, + super.size, +}) extends PositionComponent with DragCallbacks { @override void onDragStart(DragStartEvent event) { super.onDragStart(event); @@ -130,20 +123,13 @@ class DragWithCallbacksComponent extends PositionComponent with DragCallbacks { } } -class ScaleWithCallbacksComponent extends PositionComponent - with ScaleCallbacks { - ScaleWithCallbacksComponent({ - this._onScaleStart, - this._onScaleUpdate, - this._onScaleEnd, - super.position, - super.size, - }); - - final void Function(ScaleStartEvent)? _onScaleStart; - final void Function(ScaleUpdateEvent)? _onScaleUpdate; - final void Function(ScaleEndEvent)? _onScaleEnd; - +class ScaleWithCallbacksComponent({ + final void Function(ScaleStartEvent)? _onScaleStart, + final void Function(ScaleUpdateEvent)? _onScaleUpdate, + final void Function(ScaleEndEvent)? _onScaleEnd, + super.position, + super.size, +}) extends PositionComponent with ScaleCallbacks { @override void onScaleStart(ScaleStartEvent event) { super.onScaleStart(event); @@ -162,37 +148,29 @@ class ScaleWithCallbacksComponent extends PositionComponent } } -class ScaleDragCallbacksComponent extends PositionComponent - with ScaleCallbacks, DragCallbacks, ScaleCounter, DragCounter {} - -class ScaleDragCallbacksGame extends FlameGame - with ScaleCallbacks, DragCallbacks, ScaleCounter, DragCounter {} - -class SimpleScaleDragCallbacksComponent extends PositionComponent - with ScaleCallbacks, DragCallbacks { - SimpleScaleDragCallbacksComponent({super.size}); -} - -class ScaleDragWithCallbacksComponent extends PositionComponent +class ScaleDragCallbacksComponent() + extends PositionComponent + with ScaleCallbacks, DragCallbacks, ScaleCounter, DragCounter; + +class ScaleDragCallbacksGame() + extends FlameGame + with ScaleCallbacks, DragCallbacks, ScaleCounter, DragCounter; + +class SimpleScaleDragCallbacksComponent({super.size}) + extends PositionComponent + with ScaleCallbacks, DragCallbacks; + +class ScaleDragWithCallbacksComponent({ + final void Function(ScaleStartEvent)? _onScaleStart, + final void Function(ScaleUpdateEvent)? _onScaleUpdate, + final void Function(ScaleEndEvent)? _onScaleEnd, + final void Function(DragStartEvent)? _onDragStart, + final void Function(DragUpdateEvent)? _onDragUpdate, + final void Function(DragEndEvent)? _onDragEnd, + super.position, + super.size, +}) extends PositionComponent with ScaleCallbacks, DragCallbacks, ScaleCounter, DragCounter { - ScaleDragWithCallbacksComponent({ - this._onScaleStart, - this._onScaleUpdate, - this._onScaleEnd, - this._onDragStart, - this._onDragUpdate, - this._onDragEnd, - super.position, - super.size, - }); - - final void Function(ScaleStartEvent)? _onScaleStart; - final void Function(ScaleUpdateEvent)? _onScaleUpdate; - final void Function(ScaleEndEvent)? _onScaleEnd; - final void Function(DragStartEvent)? _onDragStart; - final void Function(DragUpdateEvent)? _onDragUpdate; - final void Function(DragEndEvent)? _onDragEnd; - @override void onScaleStart(ScaleStartEvent event) { super.onScaleStart(event); @@ -403,30 +381,32 @@ extension ZoomTesting on WidgetTester { } } -class ScaleCallbacksComponent extends PositionComponent - with ScaleCallbacks, ScaleCounter {} +class ScaleCallbacksComponent() + extends PositionComponent + with ScaleCallbacks, ScaleCounter; -class ScaleCallbacksGame extends FlameGame with ScaleCallbacks, ScaleCounter {} +class ScaleCallbacksGame() extends FlameGame with ScaleCallbacks, ScaleCounter; -class SimpleScaleCallbacksComponent extends PositionComponent - with ScaleCallbacks { - SimpleScaleCallbacksComponent({super.size}); -} +class SimpleScaleCallbacksComponent({super.size}) + extends PositionComponent + with ScaleCallbacks; -class SimpleDragCallbacksComponent extends PositionComponent - with DragCallbacks { - SimpleDragCallbacksComponent({super.size}); -} +class SimpleDragCallbacksComponent({super.size}) + extends PositionComponent + with DragCallbacks; -class DragCallbacksComponent extends PositionComponent - with DragCallbacks, DragCounter {} +class DragCallbacksComponent() + extends PositionComponent + with DragCallbacks, DragCounter; -class DragCallbacksGame extends FlameGame with DragCallbacks, DragCounter {} +class DragCallbacksGame() extends FlameGame with DragCallbacks, DragCounter; /// An ancestor that starts out passing events through, but can be made to /// swallow them partway through a gesture by setting [ignoreEvents]. -class EventGate extends PositionComponent with IgnoreEvents { - EventGate({super.position, super.size, super.children}) { +class EventGate({super.position, super.size, super.children}) + extends PositionComponent + with IgnoreEvents { + this { ignoreEvents = false; } } diff --git a/packages/flame/test/events/component_mixins/long_press_callbacks_test.dart b/packages/flame/test/events/component_mixins/long_press_callbacks_test.dart index 526ee77f803..5766471d4a5 100644 --- a/packages/flame/test/events/component_mixins/long_press_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/long_press_callbacks_test.dart @@ -231,9 +231,9 @@ void _hasDispatcher(FlameGame game) { ); } -class _LongPressComponent extends PositionComponent with LongPressCallbacks { - _LongPressComponent({super.position, super.size}); - +class _LongPressComponent({super.position, super.size}) + extends PositionComponent + with LongPressCallbacks { int startCount = 0; int moveUpdateCount = 0; int endCount = 0; @@ -263,7 +263,7 @@ class _LongPressComponent extends PositionComponent with LongPressCallbacks { } } -class _LongPressGame extends FlameGame with LongPressCallbacks { +class _LongPressGame() extends FlameGame with LongPressCallbacks { int startCount = 0; @override diff --git a/packages/flame/test/events/component_mixins/mouse_move_callbacks_test.dart b/packages/flame/test/events/component_mixins/mouse_move_callbacks_test.dart index 025618fcad5..1505e451df8 100644 --- a/packages/flame/test/events/component_mixins/mouse_move_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/mouse_move_callbacks_test.dart @@ -102,13 +102,11 @@ mixin _MouseMoveInspector on MouseMoveCallbacks { } } -class _MouseMoveCallbacksComponent extends PositionComponent - with MouseMoveCallbacks, _MouseMoveInspector { - _MouseMoveCallbacksComponent({ - super.position, - super.size, - }); -} - -class _MouseMoveCallbacksGame extends FlameGame - with MouseMoveCallbacks, _MouseMoveInspector {} +class _MouseMoveCallbacksComponent({ + super.position, + super.size, +}) extends PositionComponent with MouseMoveCallbacks, _MouseMoveInspector; + +class _MouseMoveCallbacksGame() + extends FlameGame + with MouseMoveCallbacks, _MouseMoveInspector; diff --git a/packages/flame/test/events/component_mixins/scroll_callbacks_test.dart b/packages/flame/test/events/component_mixins/scroll_callbacks_test.dart index 23f3b3d7411..1250dd1cc4b 100644 --- a/packages/flame/test/events/component_mixins/scroll_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/scroll_callbacks_test.dart @@ -166,21 +166,18 @@ mixin _ScrollInspector on ScrollCallbacks { } } -class _ScrollCallbacksComponent extends PositionComponent - with ScrollCallbacks, _ScrollInspector { - _ScrollCallbacksComponent({ - super.position, - super.size, - }); -} +class _ScrollCallbacksComponent({ + super.position, + super.size, +}) extends PositionComponent with ScrollCallbacks, _ScrollInspector; -class _ScrollCallbacksGame extends FlameGame - with ScrollCallbacks, _ScrollInspector {} +class _ScrollCallbacksGame() + extends FlameGame + with ScrollCallbacks, _ScrollInspector; -class _RawScrollCallbacksComponent extends PositionComponent +class _RawScrollCallbacksComponent({super.position, super.size}) + extends PositionComponent with ScrollCallbacks { - _RawScrollCallbacksComponent({super.position, super.size}); - bool rawEventReceived = false; @override diff --git a/packages/flame/test/events/component_mixins/secondary_tap_callbacks_test.dart b/packages/flame/test/events/component_mixins/secondary_tap_callbacks_test.dart index b753324dfe2..51315953b70 100644 --- a/packages/flame/test/events/component_mixins/secondary_tap_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/secondary_tap_callbacks_test.dart @@ -198,9 +198,10 @@ void main() { }); } -class _SecondaryTapCallbacksComponent extends PositionComponent +class _SecondaryTapCallbacksComponent() + extends PositionComponent with SecondaryTapCallbacks { - _SecondaryTapCallbacksComponent() { + this { anchor = Anchor.center; size = Vector2.all(10); } @@ -225,9 +226,10 @@ class _SecondaryTapCallbacksComponent extends PositionComponent } } -class _BothTapCallbacksComponent extends PositionComponent +class _BothTapCallbacksComponent() + extends PositionComponent with TapCallbacks, SecondaryTapCallbacks { - _BothTapCallbacksComponent() { + this { anchor = Anchor.center; size = Vector2.all(10); } diff --git a/packages/flame/test/events/component_mixins/tap_callbacks_test.dart b/packages/flame/test/events/component_mixins/tap_callbacks_test.dart index 04648b013f8..db2d24178f6 100644 --- a/packages/flame/test/events/component_mixins/tap_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/tap_callbacks_test.dart @@ -565,7 +565,7 @@ void main() { /// Holds the values that are only readable while an event is being delivered, /// so that they can be asserted on after the gesture has finished. -class _CapturedTapEvent { +class _CapturedTapEvent() { late final Vector2 localPosition; late final Vector2? parentContext; late final List trace; @@ -577,45 +577,31 @@ class _CapturedTapEvent { } } -class _TapWithCallbacksGame extends FlameGame with TapCallbacks { - _TapWithCallbacksGame({required this.onTapDownCallback}); - - final void Function(TapDownEvent) onTapDownCallback; - +class _TapWithCallbacksGame({ + required final void Function(TapDownEvent) onTapDownCallback, +}) extends FlameGame with TapCallbacks { @override void onTapDown(TapDownEvent event) => onTapDownCallback(event); } -class _DragWithParentContextComponent extends PositionComponent - with DragCallbacks { - _DragWithParentContextComponent({ - required Vector2 super.position, - required Vector2 super.size, - required this.onDragUpdateCallback, - }); - - final void Function(DragUpdateEvent) onDragUpdateCallback; - +class _DragWithParentContextComponent({ + required Vector2 super.position, + required Vector2 super.size, + required final void Function(DragUpdateEvent) onDragUpdateCallback, +}) extends PositionComponent with DragCallbacks { @override void onDragUpdate(DragUpdateEvent event) => onDragUpdateCallback(event); } -class _TapWithCallbacksComponent extends PositionComponent with TapCallbacks { - _TapWithCallbacksComponent({ - required Vector2 super.position, - required Vector2 super.size, - super.children, - this._onTapDown, - this._onLongTapDown, - this._onTapUp, - this._onTapCancel, - }); - - final void Function(TapDownEvent)? _onTapDown; - final void Function(TapDownEvent)? _onLongTapDown; - final void Function(TapUpEvent)? _onTapUp; - final void Function(TapCancelEvent)? _onTapCancel; - +class _TapWithCallbacksComponent({ + required Vector2 super.position, + required Vector2 super.size, + super.children, + final void Function(TapDownEvent)? _onTapDown, + final void Function(TapDownEvent)? _onLongTapDown, + final void Function(TapUpEvent)? _onTapUp, + final void Function(TapCancelEvent)? _onTapCancel, +}) extends PositionComponent with TapCallbacks { @override void onTapDown(TapDownEvent event) => _onTapDown?.call(event); @@ -629,9 +615,9 @@ class _TapWithCallbacksComponent extends PositionComponent with TapCallbacks { void onTapCancel(TapCancelEvent event) => _onTapCancel?.call(event); } -class _SimpleTapCallbacksComponent extends PositionComponent with TapCallbacks { - _SimpleTapCallbacksComponent({super.size}); -} +class _SimpleTapCallbacksComponent({super.size}) + extends PositionComponent + with TapCallbacks; mixin _TapCounter on TapCallbacks { int tapDownEvent = 0; @@ -663,7 +649,8 @@ mixin _TapCounter on TapCallbacks { } } -class _TapCallbacksComponent extends PositionComponent - with TapCallbacks, _TapCounter {} +class _TapCallbacksComponent() + extends PositionComponent + with TapCallbacks, _TapCounter; -class _TapCallbacksGame extends FlameGame with TapCallbacks, _TapCounter {} +class _TapCallbacksGame() extends FlameGame with TapCallbacks, _TapCounter; diff --git a/packages/flame/test/events/component_mixins/tertiary_tap_callbacks_test.dart b/packages/flame/test/events/component_mixins/tertiary_tap_callbacks_test.dart index db96bff9158..0f3048b2bef 100644 --- a/packages/flame/test/events/component_mixins/tertiary_tap_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/tertiary_tap_callbacks_test.dart @@ -208,9 +208,10 @@ void main() { }); } -class _TertiaryTapCallbacksComponent extends PositionComponent +class _TertiaryTapCallbacksComponent() + extends PositionComponent with TertiaryTapCallbacks { - _TertiaryTapCallbacksComponent() { + this { anchor = Anchor.center; size = Vector2.all(10); } @@ -235,9 +236,10 @@ class _TertiaryTapCallbacksComponent extends PositionComponent } } -class _PrimaryAndTertiaryComponent extends PositionComponent +class _PrimaryAndTertiaryComponent() + extends PositionComponent with TapCallbacks, TertiaryTapCallbacks { - _PrimaryAndTertiaryComponent() { + this { anchor = Anchor.center; size = Vector2.all(10); } @@ -268,9 +270,10 @@ class _PrimaryAndTertiaryComponent extends PositionComponent } } -class _SecondaryAndTertiaryComponent extends PositionComponent +class _SecondaryAndTertiaryComponent() + extends PositionComponent with SecondaryTapCallbacks, TertiaryTapCallbacks { - _SecondaryAndTertiaryComponent() { + this { anchor = Anchor.center; size = Vector2.all(10); } diff --git a/packages/flame/test/events/hardware_keyboard_detector_test.dart b/packages/flame/test/events/hardware_keyboard_detector_test.dart index 7c74dd6ad39..e60a13d2116 100644 --- a/packages/flame/test/events/hardware_keyboard_detector_test.dart +++ b/packages/flame/test/events/hardware_keyboard_detector_test.dart @@ -150,7 +150,7 @@ void main() { }); } -class _MyKeyboardDetector extends HardwareKeyboardDetector { +class _MyKeyboardDetector() extends HardwareKeyboardDetector { final List events = []; void Function(KeyEvent)? keyEventHandler; diff --git a/packages/flame/test/experimental/geometry/shapes/circle_test.dart b/packages/flame/test/experimental/geometry/shapes/circle_test.dart index 1b37aa75840..4b38c748479 100644 --- a/packages/flame/test/experimental/geometry/shapes/circle_test.dart +++ b/packages/flame/test/experimental/geometry/shapes/circle_test.dart @@ -1,4 +1,5 @@ import 'dart:math'; + import 'package:flame/experimental.dart'; import 'package:flame/game.dart'; import 'package:flame_test/flame_test.dart'; diff --git a/packages/flame/test/experimental/has_world_ref_test.dart b/packages/flame/test/experimental/has_world_ref_test.dart index dcef2ab6cc7..46a56873a2e 100644 --- a/packages/flame/test/experimental/has_world_ref_test.dart +++ b/packages/flame/test/experimental/has_world_ref_test.dart @@ -81,23 +81,23 @@ void main() { }); } -class _ReferenceWorld extends World { +class _ReferenceWorld() extends World { bool calledFoo = false; void foo() => calledFoo = true; } -class _Component extends Component with HasWorldRef {} +class _Component() extends Component with HasWorldRef; -class _MyGame extends FlameGame { - _MyGame() : super(world: _ReferenceWorld()); +class _MyGame() extends FlameGame { + this : super(world: _ReferenceWorld()); } -class _FooComponent extends Component with HasWorldRef<_ReferenceWorld> { +class _FooComponent() extends Component with HasWorldRef<_ReferenceWorld> { void foo() { worldRef.foo(); } } -class _BarComponent extends Component with HasWorldRef<_ReferenceWorld> {} +class _BarComponent() extends Component with HasWorldRef<_ReferenceWorld>; -class _MockWorld extends Mock implements _ReferenceWorld {} +class _MockWorld() extends Mock implements _ReferenceWorld; diff --git a/packages/flame/test/experimental/linear_layout_component_test.dart b/packages/flame/test/experimental/linear_layout_component_test.dart index 736e865424d..8ba1c8fedaa 100644 --- a/packages/flame/test/experimental/linear_layout_component_test.dart +++ b/packages/flame/test/experimental/linear_layout_component_test.dart @@ -4,6 +4,7 @@ import 'package:flame/experimental.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/rendering.dart'; import 'package:test/test.dart'; + import 'linear_layout_component_test_helpers.dart'; void main() { diff --git a/packages/flame/test/extensions/canvas_test.dart b/packages/flame/test/extensions/canvas_test.dart index 6268ef2f95c..595fb442710 100644 --- a/packages/flame/test/extensions/canvas_test.dart +++ b/packages/flame/test/extensions/canvas_test.dart @@ -77,10 +77,10 @@ void main() { }); } -class _MocktailCanvas extends Mock implements Canvas {} +class _MocktailCanvas() extends Mock implements Canvas; -abstract class _DrawerFunction { +abstract class _DrawerFunction() { void call(Canvas _); } -class _MocktailDrawFunction extends Mock implements _DrawerFunction {} +class _MocktailDrawFunction() extends Mock implements _DrawerFunction; diff --git a/packages/flame/test/extensions/picture_extension_test.dart b/packages/flame/test/extensions/picture_extension_test.dart index 49406a46a21..bf9be5d71e5 100644 --- a/packages/flame/test/extensions/picture_extension_test.dart +++ b/packages/flame/test/extensions/picture_extension_test.dart @@ -21,4 +21,4 @@ void main() { }); } -class _MockPicture extends Mock implements Picture {} +class _MockPicture() extends Mock implements Picture; diff --git a/packages/flame/test/extensions/random_test.dart b/packages/flame/test/extensions/random_test.dart index 483cf4630ee..0e5c97ff4c6 100644 --- a/packages/flame/test/extensions/random_test.dart +++ b/packages/flame/test/extensions/random_test.dart @@ -67,4 +67,4 @@ void main() { }); } -class _MockRandom extends Mock implements Random {} +class _MockRandom() extends Mock implements Random; diff --git a/packages/flame/test/extensions/rect_test.dart b/packages/flame/test/extensions/rect_test.dart index 4c21df8ffdb..48b2f5bfb1f 100644 --- a/packages/flame/test/extensions/rect_test.dart +++ b/packages/flame/test/extensions/rect_test.dart @@ -264,4 +264,4 @@ void main() { }); } -class _MockRect extends Mock implements Rect {} +class _MockRect() extends Mock implements Rect; diff --git a/packages/flame/test/game/contains_event_handler_at_test.dart b/packages/flame/test/game/contains_event_handler_at_test.dart index fddd335b1ce..53c813179b2 100644 --- a/packages/flame/test/game/contains_event_handler_at_test.dart +++ b/packages/flame/test/game/contains_event_handler_at_test.dart @@ -155,29 +155,30 @@ void main() { }); } -mixin _CustomInputCallbacks on Component implements PointerInputCallbacks {} +mixin _CustomInputCallbacks on Component implements PointerInputCallbacks; -class _TransparentGame extends FlameGame with DeferHitTestToComponents { +class _TransparentGame() extends FlameGame with DeferHitTestToComponents { @override Color backgroundColor() => const Color(0x00000000); } -class _DeferringGame extends FlameGame with DeferHitTestToComponents {} +class _DeferringGame() extends FlameGame with DeferHitTestToComponents; -class _DeferringScrollGame extends FlameGame - with ScrollCallbacks, DeferHitTestToComponents {} +class _DeferringScrollGame() + extends FlameGame + with ScrollCallbacks, DeferHitTestToComponents; -class _Box extends PositionComponent { - _Box() : super(position: Vector2.all(10), size: Vector2.all(50)); +class _Box() extends PositionComponent { + this : super(position: Vector2.all(10), size: Vector2.all(50)); } -class _PlainComponent extends _Box {} +class _PlainComponent() extends _Box; -class _CustomInputComponent extends _Box with _CustomInputCallbacks {} +class _CustomInputComponent() extends _Box with _CustomInputCallbacks; -class _ScrollComponent extends _Box with ScrollCallbacks {} +class _ScrollComponent() extends _Box with ScrollCallbacks; -class _LongPressComponent extends _Box with LongPressCallbacks { +class _LongPressComponent() extends _Box with LongPressCallbacks { int longPressCount = 0; @override diff --git a/packages/flame/test/game/flame_game_test.dart b/packages/flame/test/game/flame_game_test.dart index 8a681ecc9fb..8c2a6477d47 100644 --- a/packages/flame/test/game/flame_game_test.dart +++ b/packages/flame/test/game/flame_game_test.dart @@ -547,19 +547,13 @@ void main() { }); } -class _IndexedComponent extends Component { - final int index; +class _IndexedComponent(final int index) extends Component; - _IndexedComponent(this.index); -} - -class _ConstructorChildrenGame extends FlameGame { - final Iterable<_IndexedComponent> onLoadChildren; - - _ConstructorChildrenGame({ - required Iterable<_IndexedComponent> constructorChildren, - required this.onLoadChildren, - }) : super(children: constructorChildren); +class _ConstructorChildrenGame({ + required Iterable<_IndexedComponent> constructorChildren, + required final Iterable<_IndexedComponent> onLoadChildren, +}) extends FlameGame { + this : super(children: constructorChildren); @override Future onLoad() async { @@ -567,7 +561,7 @@ class _ConstructorChildrenGame extends FlameGame { } } -class _MyTappableComponent extends _MyComponent with TapCallbacks { +class _MyTappableComponent() extends _MyComponent with TapCallbacks { bool tapped = false; @override @@ -577,7 +571,7 @@ class _MyTappableComponent extends _MyComponent with TapCallbacks { } } -class _MyComponent extends PositionComponent with HasGameRef { +class _MyComponent() extends PositionComponent with HasGameRef { bool isUpdateCalled = false; bool isRenderCalled = false; int onRemoveCallCounter = 0; @@ -609,30 +603,26 @@ class _MyComponent extends PositionComponent with HasGameRef { } } -class _MyAsyncComponent extends _MyComponent { +class _MyAsyncComponent() extends _MyComponent { @override Future onLoad() { return Future.value(); } } -class _ReadyingOnMountComponent extends Component { +class _ReadyingOnMountComponent() extends Component { @override void onMount() { unawaited(findGame()!.ready()); } } -class _NeverLoadingComponent extends Component { +class _NeverLoadingComponent() extends Component { @override Future onLoad() => Completer().future; } -class _OnAttachGame extends FlameGame { - final VoidCallback onAttachCallback; - - _OnAttachGame(this.onAttachCallback); - +class _OnAttachGame(final VoidCallback onAttachCallback) extends FlameGame { @override void onAttach() { onAttachCallback(); @@ -644,12 +634,12 @@ class _OnAttachGame extends FlameGame { } } -class _CompleterGame extends FlameGame { +class _CompleterGame() extends FlameGame { int loadedCompleterCount = 0; int mountedCompleterCount = 0; int removedCompleterCount = 0; - _CompleterGame() { + this { loaded.whenComplete(() => loadedCompleterCount++); mounted.whenComplete(() => mountedCompleterCount++); removed.whenComplete(() => removedCompleterCount++); diff --git a/packages/flame/test/game/game_render_box_test.dart b/packages/flame/test/game/game_render_box_test.dart index 0ce6b3fc4a5..537f00ac8cb 100644 --- a/packages/flame/test/game/game_render_box_test.dart +++ b/packages/flame/test/game/game_render_box_test.dart @@ -5,9 +5,9 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockFlameGame extends Mock implements FlameGame {} +class _MockFlameGame() extends Mock implements FlameGame; -class _MockBuildContext extends Mock implements BuildContext {} +class _MockBuildContext() extends Mock implements BuildContext; final _nodesNeedingCompositingBitsUpdate = []; diff --git a/packages/flame/test/game/game_widget/game_widget_hot_reload_test.dart b/packages/flame/test/game/game_widget/game_widget_hot_reload_test.dart index f1afde93d64..e2cb1625b78 100644 --- a/packages/flame/test/game/game_widget/game_widget_hot_reload_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_hot_reload_test.dart @@ -5,7 +5,7 @@ import 'package:flame/game.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _HotReloadGame extends FlameGame { +class _HotReloadGame() extends FlameGame { int hotReloadCount = 0; @override @@ -15,7 +15,7 @@ class _HotReloadGame extends FlameGame { } } -class _HotReloadComponent extends Component { +class _HotReloadComponent() extends Component { int hotReloadCount = 0; @override @@ -25,7 +25,7 @@ class _HotReloadComponent extends Component { } } -class _AsyncLoadComponent extends Component { +class _AsyncLoadComponent() extends Component { final Completer loadCompleter = Completer(); int hotReloadCount = 0; diff --git a/packages/flame/test/game/game_widget/game_widget_keyboard_test.dart b/packages/flame/test/game/game_widget/game_widget_keyboard_test.dart index 31c479b1979..a703ae06d45 100644 --- a/packages/flame/test/game/game_widget/game_widget_keyboard_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_keyboard_test.dart @@ -5,11 +5,9 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _KeyboardEventsGame extends FlameGame with KeyboardEvents { +class _KeyboardEventsGame() extends FlameGame with KeyboardEvents { final List keysPressed = []; - _KeyboardEventsGame(); - @override KeyEventResult onKeyEvent( KeyEvent event, @@ -21,7 +19,7 @@ class _KeyboardEventsGame extends FlameGame with KeyboardEvents { } } -class _KeyboardHandlerComponent extends Component with KeyboardHandler { +class _KeyboardHandlerComponent() extends Component with KeyboardHandler { final List keysPressed = []; @override @@ -31,10 +29,9 @@ class _KeyboardHandlerComponent extends Component with KeyboardHandler { } } -class _HasKeyboardHandlerComponentsGame extends FlameGame +class _HasKeyboardHandlerComponentsGame() + extends FlameGame with HasKeyboardHandlerComponents { - _HasKeyboardHandlerComponentsGame(); - late _KeyboardHandlerComponent keyboardHandler; @override @@ -44,11 +41,7 @@ class _HasKeyboardHandlerComponentsGame extends FlameGame } } -class _GamePage extends StatelessWidget { - final Widget child; - - const _GamePage({required this.child}); - +class const _GamePage({required final Widget child}) extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( diff --git a/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart b/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart index fc969b0ae57..b889a33aab6 100644 --- a/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart @@ -3,11 +3,7 @@ import 'package:flame/game.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _MyGame extends FlameGame { - final List events; - - _MyGame(this.events); - +class _MyGame(final List events) extends FlameGame { @override void onGameResize(Vector2 size) { super.onGameResize(size); @@ -50,7 +46,7 @@ class _MyGame extends FlameGame { } } -class _TitlePage extends StatelessWidget { +class const _TitlePage() extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( @@ -64,18 +60,14 @@ class _TitlePage extends StatelessWidget { } } -class _GamePage extends StatefulWidget { - final _MyGame game; - - const _GamePage(this.game); - +class const _GamePage(final _MyGame game) extends StatefulWidget { @override State createState() { return _GamePageState(); } } -class _GamePageState extends State<_GamePage> { +class _GamePageState() extends State<_GamePage> { late _MyGame _game; @override @@ -110,11 +102,10 @@ class _GamePageState extends State<_GamePage> { } } -class _MyApp extends StatelessWidget { - final List events; +class _MyApp(final List events) extends StatelessWidget { late final _MyGame game; - _MyApp(this.events) { + this { game = _MyGame(events); } @@ -122,23 +113,19 @@ class _MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( routes: { - '/': (_) => _TitlePage(), + '/': (_) => const _TitlePage(), '/game': (_) => _GamePage(game), }, ); } } -class _MyContainer extends StatefulWidget { - final List events; - - const _MyContainer(this.events); - +class const _MyContainer(final List events) extends StatefulWidget { @override State<_MyContainer> createState() => _MyContainerState(); } -class _MyContainerState extends State<_MyContainer> { +class _MyContainerState() extends State<_MyContainer> { double size = 300; late final game = _MyGame(widget.events); diff --git a/packages/flame/test/game/game_widget/game_widget_managed_lifecycle_test.dart b/packages/flame/test/game/game_widget/game_widget_managed_lifecycle_test.dart index f0cb15fa1d3..e012fdf6c4d 100644 --- a/packages/flame/test/game/game_widget/game_widget_managed_lifecycle_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_managed_lifecycle_test.dart @@ -3,11 +3,7 @@ import 'package:flame/game.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _MyGame extends FlameGame { - final List events; - - _MyGame(this.events); - +class _MyGame(final List events) extends FlameGame { @override void onGameResize(Vector2 size) { super.onGameResize(size); @@ -32,7 +28,7 @@ class _MyGame extends FlameGame { } } -class _TitlePage extends StatelessWidget { +class const _TitlePage() extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( @@ -46,11 +42,7 @@ class _TitlePage extends StatelessWidget { } } -class _GamePage extends StatelessWidget { - const _GamePage(this.events); - - final List events; - +class const _GamePage(final List events) extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( @@ -77,32 +69,24 @@ class _GamePage extends StatelessWidget { } } -class _MyApp extends StatelessWidget { - final List events; - - const _MyApp(this.events); - +class const _MyApp(final List events) extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( routes: { - '/': (_) => _TitlePage(), + '/': (_) => const _TitlePage(), '/game': (_) => _GamePage(events), }, ); } } -class _MyContainer extends StatefulWidget { - final List events; - - const _MyContainer(this.events); - +class const _MyContainer(final List events) extends StatefulWidget { @override State<_MyContainer> createState() => _MyContainerState(); } -class _MyContainerState extends State<_MyContainer> { +class _MyContainerState() extends State<_MyContainer> { double size = 300; late final game = _MyGame(widget.events); diff --git a/packages/flame/test/game/game_widget/game_widget_mouse_cursor_test.dart b/packages/flame/test/game/game_widget/game_widget_mouse_cursor_test.dart index 4bcb0132e75..a607b379a35 100644 --- a/packages/flame/test/game/game_widget/game_widget_mouse_cursor_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_mouse_cursor_test.dart @@ -69,7 +69,7 @@ void main() { }); } -class _GameWithMouseCursorSetDuringOnLoad extends FlameGame { +class _GameWithMouseCursorSetDuringOnLoad() extends FlameGame { @override Future? onLoad() { mouseCursor = SystemMouseCursors.alias; diff --git a/packages/flame/test/game/game_widget/game_widget_pause_test.dart b/packages/flame/test/game/game_widget/game_widget_pause_test.dart index 586108c60d3..c8ebbfb2b73 100644 --- a/packages/flame/test/game/game_widget/game_widget_pause_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_pause_test.dart @@ -3,21 +3,16 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _Wrapper extends StatefulWidget { - const _Wrapper({ - required this.child, - // ignore: unused_element, unused_element_parameter - this.small = false, - }); - - final Widget child; - final bool small; - +class const _Wrapper({ + required final Widget child, + // ignore: unused_element_parameter + final bool small = false, +}) extends StatefulWidget { @override State<_Wrapper> createState() => _WrapperState(); } -class _WrapperState extends State<_Wrapper> { +class _WrapperState() extends State<_Wrapper> { late bool _small; @override @@ -51,7 +46,7 @@ class _WrapperState extends State<_Wrapper> { } } -class _MyGame extends FlameGame { +class _MyGame() extends FlameGame { int updateCount = 0; int renderCount = 0; double timePassed = 0; diff --git a/packages/flame/test/game/game_widget/game_widget_tap_passthrough_test.dart b/packages/flame/test/game/game_widget/game_widget_tap_passthrough_test.dart index f629b08b255..21df1276bc0 100644 --- a/packages/flame/test/game/game_widget/game_widget_tap_passthrough_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_tap_passthrough_test.dart @@ -4,12 +4,12 @@ import 'package:flame/game.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _TransparentGame extends FlameGame with DeferHitTestToComponents { +class _TransparentGame() extends FlameGame with DeferHitTestToComponents { @override Color backgroundColor() => const Color(0x00000000); } -class _TrackingGame extends FlameGame with DeferHitTestToComponents { +class _TrackingGame() extends FlameGame with DeferHitTestToComponents { int componentsAtPointCallCount = 0; @override @@ -25,7 +25,7 @@ class _TrackingGame extends FlameGame with DeferHitTestToComponents { } } -class _TappableComponent extends PositionComponent with TapCallbacks { +class _TappableComponent() extends PositionComponent with TapCallbacks { int tapDownCount = 0; int tapUpCount = 0; diff --git a/packages/flame/test/game/game_widget/game_widget_test.dart b/packages/flame/test/game/game_widget/game_widget_test.dart index cea037e5851..ecf761fe986 100644 --- a/packages/flame/test/game/game_widget/game_widget_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_test.dart @@ -8,24 +8,17 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _Wrapper extends StatefulWidget { - const _Wrapper({ - required this.child, - this.open = false, - }); - - final Widget child; - final bool open; - +class const _Wrapper({ + required final Widget child, + final bool open = false, +}) extends StatefulWidget { @override State<_Wrapper> createState() => _WrapperState(); } -class _GameWithKeyboardEvents extends FlameGame with KeyboardEvents { +class _GameWithKeyboardEvents() extends FlameGame with KeyboardEvents { final List keyEvents = []; - _GameWithKeyboardEvents(); - @override KeyEventResult onKeyEvent( KeyEvent event, @@ -36,7 +29,7 @@ class _GameWithKeyboardEvents extends FlameGame with KeyboardEvents { } } -class _WrapperState extends State<_Wrapper> { +class _WrapperState() extends State<_Wrapper> { late bool _open; @override @@ -66,7 +59,7 @@ class _WrapperState extends State<_Wrapper> { } } -class _MyGame extends FlameGame { +class _MyGame() extends FlameGame { bool onAttachCalled = false; bool onDetachCalled = false; @@ -607,16 +600,12 @@ void main() { }); } -class _SlowComponent extends Component { - _SlowComponent(this.loadCompleter); - - final Completer loadCompleter; - +class _SlowComponent(final Completer loadCompleter) extends Component { @override Future onLoad() => loadCompleter.future; } -class _SlowLoadingGame extends FlameGame { +class _SlowLoadingGame() extends FlameGame { final childLoadCompleter = Completer(); final grandChildLoadCompleter = Completer(); late final _SlowComponent slowChild; @@ -629,10 +618,7 @@ class _SlowLoadingGame extends FlameGame { } } -class _GatedLoadGame extends FlameGame { - _GatedLoadGame(this.loadGate); - - final Completer loadGate; +class _GatedLoadGame(final Completer loadGate) extends FlameGame { int onMountCount = 0; @override @@ -644,7 +630,7 @@ class _GatedLoadGame extends FlameGame { } } -class _GameWithBuildContextCheck extends FlameGame { +class _GameWithBuildContextCheck() extends FlameGame { BuildContext? buildContextDuringOnLoad; @override @@ -653,7 +639,7 @@ class _GameWithBuildContextCheck extends FlameGame { } } -class _ComponentWithBuildContextCheck extends Component { +class _ComponentWithBuildContextCheck() extends Component { BuildContext? buildContextDuringOnLoad; @override @@ -662,7 +648,7 @@ class _ComponentWithBuildContextCheck extends Component { } } -class _GameWithComponentBuildContextCheck extends FlameGame { +class _GameWithComponentBuildContextCheck() extends FlameGame { final component = _ComponentWithBuildContextCheck(); @override diff --git a/packages/flame/test/game/mixins/has_performance_tracker_test.dart b/packages/flame/test/game/mixins/has_performance_tracker_test.dart index 8c89e6fc7fa..12667b4ef2b 100644 --- a/packages/flame/test/game/mixins/has_performance_tracker_test.dart +++ b/packages/flame/test/game/mixins/has_performance_tracker_test.dart @@ -33,11 +33,11 @@ void main() { ); } -class _GameWithPerformanceTracker extends FlameGame with HasPerformanceTracker { - _GameWithPerformanceTracker({super.children}); -} +class _GameWithPerformanceTracker({super.children}) + extends FlameGame + with HasPerformanceTracker; -class _SlowComponent extends Component { +class _SlowComponent() extends Component { static const duration = Duration(milliseconds: 8); @override void update(double dt) => sleep(duration); diff --git a/packages/flame/test/game/mixins/keyboard_test.dart b/packages/flame/test/game/mixins/keyboard_test.dart index 5724ba2295e..69dc8354ba5 100644 --- a/packages/flame/test/game/mixins/keyboard_test.dart +++ b/packages/flame/test/game/mixins/keyboard_test.dart @@ -4,10 +4,11 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _ValidGame extends FlameGame with KeyboardEvents {} +class _ValidGame() extends FlameGame with KeyboardEvents; -class _InvalidGame extends FlameGame - with HasKeyboardHandlerComponents, KeyboardEvents {} +class _InvalidGame() + extends FlameGame + with HasKeyboardHandlerComponents, KeyboardEvents; void main() { group('Keyboard events', () { diff --git a/packages/flame/test/game/mixins/single_game_instance_test.dart b/packages/flame/test/game/mixins/single_game_instance_test.dart index aeec45d78eb..74bd4b9f810 100644 --- a/packages/flame/test/game/mixins/single_game_instance_test.dart +++ b/packages/flame/test/game/mixins/single_game_instance_test.dart @@ -52,11 +52,11 @@ void main() { }); } -class _DelayedComponent extends Component { +class _DelayedComponent() extends Component { @override Future onLoad() async { await Future.delayed(const Duration(milliseconds: 20)); } } -class _SingletonGame extends FlameGame with SingleGameInstance {} +class _SingletonGame() extends FlameGame with SingleGameInstance; diff --git a/packages/flame/test/game/overlays_manager_test.dart b/packages/flame/test/game/overlays_manager_test.dart index 5b78c55a6b2..3da28ed9653 100644 --- a/packages/flame/test/game/overlays_manager_test.dart +++ b/packages/flame/test/game/overlays_manager_test.dart @@ -16,8 +16,8 @@ void main() { GameWidget( game: FlameGame(), overlayBuilderMap: { - 'first!': (_, __) => Container(key: key1), - 'second': (_, __) => Container(key: key2), + 'first!': (_, _) => Container(key: key1), + 'second': (_, _) => Container(key: key2), }, initialActiveOverlays: const ['first!'], ), @@ -42,8 +42,8 @@ void main() { }, ), overlayBuilderMap: { - 'first!': (_, __) => Container(key: key1), - 'second': (_, __) => Container(key: key2), + 'first!': (_, _) => Container(key: key1), + 'second': (_, _) => Container(key: key2), }, ), ); @@ -64,8 +64,8 @@ void main() { GameWidget( game: game, overlayBuilderMap: { - 'first!': (_, __) => Container(key: key1), - 'second': (_, __) => Container(key: key2), + 'first!': (_, _) => Container(key: key1), + 'second': (_, _) => Container(key: key2), }, ), ); diff --git a/packages/flame/test/game/transform2d_test.dart b/packages/flame/test/game/transform2d_test.dart index 80349dcc905..013c96b7af2 100644 --- a/packages/flame/test/game/transform2d_test.dart +++ b/packages/flame/test/game/transform2d_test.dart @@ -1,13 +1,9 @@ import 'dart:math' as math; -// TODO(spydon): Remove this import once Flutter 3.35.0 is the minimum version. -// ignore: unnecessary_import -import 'package:flame/extensions.dart'; import 'package:flame/geometry.dart'; import 'package:flame/src/game/transform2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:test/test.dart'; -// ignore: unnecessary_import import 'package:vector_math/vector_math.dart'; void main() { diff --git a/packages/flame/test/geometry/polygon_ray_intersection_test.dart b/packages/flame/test/geometry/polygon_ray_intersection_test.dart index 8ae2ae6522c..1e8e3fe79cd 100644 --- a/packages/flame/test/geometry/polygon_ray_intersection_test.dart +++ b/packages/flame/test/geometry/polygon_ray_intersection_test.dart @@ -25,12 +25,7 @@ List _pathVertices(Path path) { return contours.first.vertices; } -class _RayCase { - _RayCase(this.ray, {required this.expectsHit}); - - final Ray2 ray; - final bool expectsHit; -} +class _RayCase(final Ray2 ray, {required final bool expectsHit}); List<_RayCase> _randomRayCases( PolygonHitbox polygon, diff --git a/packages/flame/test/image_composition_test.dart b/packages/flame/test/image_composition_test.dart index 7cff119914b..6c7c5d1c0b4 100644 --- a/packages/flame/test/image_composition_test.dart +++ b/packages/flame/test/image_composition_test.dart @@ -3,7 +3,7 @@ import 'package:flame_test/flame_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; -class _MockImage extends Mock implements Image {} +class _MockImage() extends Mock implements Image; void main() { group('ImageComposition', () { diff --git a/packages/flame/test/math/recycled_queue_test.dart b/packages/flame/test/math/recycled_queue_test.dart index 14ae7b15a92..b53c9c13da2 100644 --- a/packages/flame/test/math/recycled_queue_test.dart +++ b/packages/flame/test/math/recycled_queue_test.dart @@ -426,11 +426,7 @@ void main() { }); } -class _Int implements Disposable { - _Int([this.value]); - - int? value; - +class _Int([var int? value]) implements Disposable { @override void dispose() => value = null; diff --git a/packages/flame/test/nine_tile_box_test.dart b/packages/flame/test/nine_tile_box_test.dart index 95b558c2f44..43d53d51665 100644 --- a/packages/flame/test/nine_tile_box_test.dart +++ b/packages/flame/test/nine_tile_box_test.dart @@ -61,8 +61,8 @@ void main() { }); } -class _MyComponent1 extends PositionComponent { - _MyComponent1() : super(size: Vector2(300, 200)); +class _MyComponent1() extends PositionComponent { + this : super(size: Vector2(300, 200)); late final Sprite sprite; late final NineTileBox nineTileBox; final bgPaint = Paint()..color = const Color.fromARGB(255, 57, 113, 158); @@ -83,8 +83,8 @@ class _MyComponent1 extends PositionComponent { } } -class _MyComponent2 extends PositionComponent { - _MyComponent2() : super(size: Vector2(300, 200)); +class _MyComponent2() extends PositionComponent { + this : super(size: Vector2(300, 200)); late final Sprite sprite; late final NineTileBox nineTileBox; final bgPaint = Paint()..color = const Color.fromARGB(255, 57, 113, 158); diff --git a/packages/flame/test/post_process/post_process_test.dart b/packages/flame/test/post_process/post_process_test.dart index 8ff6d443a9f..9af96ed6264 100644 --- a/packages/flame/test/post_process/post_process_test.dart +++ b/packages/flame/test/post_process/post_process_test.dart @@ -5,11 +5,7 @@ import 'package:flame/post_process.dart'; import 'package:test/test.dart'; import 'package:vector_math/vector_math.dart'; -class _CallbackPostProcess extends PostProcess { - _CallbackPostProcess(this.callback); - - final void Function() callback; - +class _CallbackPostProcess(final void Function() callback) extends PostProcess { @override void postProcess(Vector2 size, Canvas canvas) { renderSubtree(canvas); diff --git a/packages/flame/test/raster_sprite_test.dart b/packages/flame/test/raster_sprite_test.dart index ec38b87063f..85e0f21ec00 100644 --- a/packages/flame/test/raster_sprite_test.dart +++ b/packages/flame/test/raster_sprite_test.dart @@ -70,8 +70,8 @@ void main() { }); } -class _MyRasterComponent extends PositionComponent { - _MyRasterComponent() : super(size: Vector2(200, 400)); +class _MyRasterComponent() extends PositionComponent { + this : super(size: Vector2(200, 400)); late final Sprite sprite; @override diff --git a/packages/flame/test/rendering/hue_decorator_test.dart b/packages/flame/test/rendering/hue_decorator_test.dart index ff9cd9d668b..e2f80fadf26 100644 --- a/packages/flame/test/rendering/hue_decorator_test.dart +++ b/packages/flame/test/rendering/hue_decorator_test.dart @@ -1,5 +1,6 @@ import 'dart:math' as math; import 'dart:ui'; + import 'package:flame/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -40,7 +41,7 @@ void main() { }); } -class _MockCanvas extends Fake implements Canvas { +class _MockCanvas() extends Fake implements Canvas { bool saveLayerCalled = false; bool restoreCalled = false; diff --git a/packages/flame/test/rendering/paint_decorator_test.dart b/packages/flame/test/rendering/paint_decorator_test.dart index e4af115d3fb..d961aa8c61a 100644 --- a/packages/flame/test/rendering/paint_decorator_test.dart +++ b/packages/flame/test/rendering/paint_decorator_test.dart @@ -105,12 +105,12 @@ void main() { }); } -class _DecoratedSprite extends SpriteComponent { - _DecoratedSprite({ - required Decorator decorator, - super.sprite, - super.position, - }) { +class _DecoratedSprite({ + required Decorator decorator, + super.sprite, + super.position, +}) extends SpriteComponent { + this { this.decorator.addLast(decorator); } } diff --git a/packages/flame/test/rendering/rotate3d_decorator_test.dart b/packages/flame/test/rendering/rotate3d_decorator_test.dart index fd46ad33a4f..0e06beb8f4a 100644 --- a/packages/flame/test/rendering/rotate3d_decorator_test.dart +++ b/packages/flame/test/rendering/rotate3d_decorator_test.dart @@ -92,13 +92,13 @@ void main() { }); } -class _DecoratedRectangle extends RectangleComponent { - _DecoratedRectangle({ - super.position, - super.size, - super.paint, - Decorator? decorator, - }) { +class _DecoratedRectangle({ + super.position, + super.size, + super.paint, + Decorator? decorator, +}) extends RectangleComponent { + this { this.decorator.addLast(decorator); } } diff --git a/packages/flame/test/rendering/shadow3d_decorator_test.dart b/packages/flame/test/rendering/shadow3d_decorator_test.dart index 98624b696d8..604c55c2b01 100644 --- a/packages/flame/test/rendering/shadow3d_decorator_test.dart +++ b/packages/flame/test/rendering/shadow3d_decorator_test.dart @@ -92,21 +92,18 @@ void main() { }); } -class _DecoratedRectangle extends RectangleComponent { - _DecoratedRectangle({ - super.position, - super.size, - super.paint, - Decorator? decorator, - }) { +class _DecoratedRectangle({ + super.position, + super.size, + super.paint, + Decorator? decorator, +}) extends RectangleComponent { + this { this.decorator.addLast(decorator); } } -class _Background extends Component { - _Background(this.color); - final Color color; - +class _Background(final Color color) extends Component { @override void render(Canvas canvas) { canvas.drawColor(color, BlendMode.src); diff --git a/packages/flame/test/sprite_animation_test.dart b/packages/flame/test/sprite_animation_test.dart index 6196336de85..642002a9360 100644 --- a/packages/flame/test/sprite_animation_test.dart +++ b/packages/flame/test/sprite_animation_test.dart @@ -88,4 +88,4 @@ void main() { }); } -class _MockSprite extends Mock implements Sprite {} +class _MockSprite() extends Mock implements Sprite; diff --git a/packages/flame/test/sprite_animation_ticker_test.dart b/packages/flame/test/sprite_animation_ticker_test.dart index b9eb9eff236..228e0e49bd3 100644 --- a/packages/flame/test/sprite_animation_ticker_test.dart +++ b/packages/flame/test/sprite_animation_ticker_test.dart @@ -195,4 +195,4 @@ void main() { }); } -class _MockSprite extends Mock implements Sprite {} +class _MockSprite() extends Mock implements Sprite; diff --git a/packages/flame/test/sprite_batch_test.dart b/packages/flame/test/sprite_batch_test.dart index 5ba63cef2c0..156d9e185b9 100644 --- a/packages/flame/test/sprite_batch_test.dart +++ b/packages/flame/test/sprite_batch_test.dart @@ -9,7 +9,7 @@ import 'package:mocktail/mocktail.dart'; import '_resources/load_image.dart'; -class _MockImage extends Mock implements Image {} +class _MockImage() extends Mock implements Image; void main() { group('SpriteBatch', () { diff --git a/packages/flame/test/sprite_test.dart b/packages/flame/test/sprite_test.dart index 4704b0a7ad9..69ba7faa79a 100644 --- a/packages/flame/test/sprite_test.dart +++ b/packages/flame/test/sprite_test.dart @@ -19,8 +19,8 @@ void main() { }); } -class _MyComponent extends PositionComponent { - _MyComponent() : super(size: Vector2(200, 400)); +class _MyComponent() extends PositionComponent { + this : super(size: Vector2(200, 400)); late final Sprite sprite; @override diff --git a/packages/flame/test/spritesheet_test.dart b/packages/flame/test/spritesheet_test.dart index 9760243c78e..0ab367488d4 100644 --- a/packages/flame/test/spritesheet_test.dart +++ b/packages/flame/test/spritesheet_test.dart @@ -5,7 +5,7 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockImage extends Mock implements Image {} +class _MockImage() extends Mock implements Image; void main() { group('SpriteSheet', () { diff --git a/packages/flame/test/text/text_renderer_test.dart b/packages/flame/test/text/text_renderer_test.dart index 5d35b23e386..295b00e2b1c 100644 --- a/packages/flame/test/text/text_renderer_test.dart +++ b/packages/flame/test/text/text_renderer_test.dart @@ -32,7 +32,7 @@ void main() { }); } -class _CustomTextRenderer extends TextRenderer { +class _CustomTextRenderer() extends TextRenderer { @override InlineTextElement format(String text) { return _CustomTextElement(); @@ -44,7 +44,7 @@ class _CustomTextRenderer extends TextRenderer { } } -class _CustomTextElement extends InlineTextElement { +class _CustomTextElement() extends InlineTextElement { @override LineMetrics get metrics => LineMetrics(); diff --git a/packages/flame/test/widgets/components_notifier_builder_test.dart b/packages/flame/test/widgets/components_notifier_builder_test.dart index ec3e0927f49..64ea0710818 100644 --- a/packages/flame/test/widgets/components_notifier_builder_test.dart +++ b/packages/flame/test/widgets/components_notifier_builder_test.dart @@ -3,7 +3,7 @@ import 'package:flame/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _Enemy extends PositionComponent with Notifier {} +class _Enemy() extends PositionComponent with Notifier; void main() { group('ComponentsNotifierBuilder', () { diff --git a/packages/flame/test/widgets/loading_widget.dart b/packages/flame/test/widgets/loading_widget.dart index 1ec2868d4cb..a23e688808b 100644 --- a/packages/flame/test/widgets/loading_widget.dart +++ b/packages/flame/test/widgets/loading_widget.dart @@ -1,8 +1,6 @@ import 'package:flutter/widgets.dart'; -class LoadingWidget extends StatelessWidget { - const LoadingWidget({super.key}); - +class const LoadingWidget({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return const SizedBox(); diff --git a/packages/flame/test/widgets/sprite_button_test.dart b/packages/flame/test/widgets/sprite_button_test.dart index 304a9ceb335..aca67edced4 100644 --- a/packages/flame/test/widgets/sprite_button_test.dart +++ b/packages/flame/test/widgets/sprite_button_test.dart @@ -8,7 +8,7 @@ import 'package:mocktail/mocktail.dart'; import 'loading_widget.dart'; -class _MockImages extends Mock implements Images {} +class _MockImages() extends Mock implements Images; Future main() async { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame_3d/bin/_build_wgslbundle.dart b/packages/flame_3d/bin/_build_wgslbundle.dart index 70586e18dab..8979e035c10 100644 --- a/packages/flame_3d/bin/_build_wgslbundle.dart +++ b/packages/flame_3d/bin/_build_wgslbundle.dart @@ -238,8 +238,7 @@ Map _reflect(String stage) { slots[name] = { 'group': group, 'binding': binding, - if (samplers['${name}Sampler'] case final sampler?) - 'samplerBinding': sampler, + 'samplerBinding': ?samplers['${name}Sampler'], }; } return slots; @@ -275,7 +274,7 @@ Map> _parseStructs(String wgsl) { var align = 0; final offsets = {}; for (final (name, type) in fields) { - final (size: size, align: fieldAlign) = _sizeAlign(type, structs); + final (:size, align: fieldAlign) = _sizeAlign(type, structs); offset = _roundUp(offset, fieldAlign); offsets[name] = offset; offset += size; @@ -303,7 +302,7 @@ Map> _parseStructs(String wgsl) { // matCxR: C columns, each a `vecR` padded to its own alignment. if (RegExp(r'^mat(\d)x(\d)$').firstMatch(type) case final m?) { final columns = int.parse(m.group(1)!); - final (size: columnSize, align: align) = _sizeAlign( + final (size: columnSize, :align) = _sizeAlign( 'vec${m.group(2)}', structs, ); @@ -312,7 +311,7 @@ Map> _parseStructs(String wgsl) { // array: N elements on a stride of `roundUp(sizeof E, alignof E)`. if (RegExp(r'^array<(.+),\s*(\d+)>$').firstMatch(type) case final m?) { - final (size: elementSize, align: align) = _sizeAlign( + final (size: elementSize, :align) = _sizeAlign( m.group(1)!.trim(), structs, ); diff --git a/packages/flame_3d/example/lib/commands/destroy_command.dart b/packages/flame_3d/example/lib/commands/destroy_command.dart index 861e1688756..b931b4bcc30 100644 --- a/packages/flame_3d/example/lib/commands/destroy_command.dart +++ b/packages/flame_3d/example/lib/commands/destroy_command.dart @@ -8,7 +8,7 @@ import 'package:flame_3d_example/components/room_bounds.dart'; import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_console/flame_console.dart'; -class DestroyCommand extends FlameConsoleCommand { +class DestroyCommand() extends FlameConsoleCommand { @override String get name => 'destroy'; diff --git a/packages/flame_3d/example/lib/commands/reset_command.dart b/packages/flame_3d/example/lib/commands/reset_command.dart index f6a190a151b..0f0a26d5a1b 100644 --- a/packages/flame_3d/example/lib/commands/reset_command.dart +++ b/packages/flame_3d/example/lib/commands/reset_command.dart @@ -1,7 +1,7 @@ import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_console/flame_console.dart'; -class ResetCommand extends FlameConsoleCommand { +class ResetCommand() extends FlameConsoleCommand { @override String get name => 'reset'; diff --git a/packages/flame_3d/example/lib/commands/setup_command.dart b/packages/flame_3d/example/lib/commands/setup_command.dart index c7994da623b..741f8a0e0d3 100644 --- a/packages/flame_3d/example/lib/commands/setup_command.dart +++ b/packages/flame_3d/example/lib/commands/setup_command.dart @@ -3,7 +3,7 @@ import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_3d_example/scenarios/game_scenario.dart'; import 'package:flame_console/flame_console.dart'; -class SetupCommand extends FlameConsoleCommand { +class SetupCommand() extends FlameConsoleCommand { @override String get name => 'setup'; diff --git a/packages/flame_3d/example/lib/components/crate.dart b/packages/flame_3d/example/lib/components/crate.dart index 4e8e44f38e9..f956fc91722 100644 --- a/packages/flame_3d/example/lib/components/crate.dart +++ b/packages/flame_3d/example/lib/components/crate.dart @@ -5,11 +5,11 @@ import 'package:flame_3d/components.dart'; import 'package:flame_3d/game.dart'; import 'package:flame_3d/resources.dart'; -class Crate extends MeshComponent { - Crate({ - required Vector3 size, - super.position, - }) : super(mesh: CuboidMesh(size: size)); +class Crate({ + required Vector3 size, + super.position, +}) extends MeshComponent { + this : super(mesh: CuboidMesh(size: size)); @override FutureOr onLoad() async { diff --git a/packages/flame_3d/example/lib/components/player.dart b/packages/flame_3d/example/lib/components/player.dart index 85f313ffbad..f74043a0fe8 100644 --- a/packages/flame_3d/example/lib/components/player.dart +++ b/packages/flame_3d/example/lib/components/player.dart @@ -11,7 +11,8 @@ import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_3d_example/keyboard_utils.dart'; import 'package:flutter/services.dart'; -class Player extends MeshComponent +class Player({required Vector3 position}) + extends MeshComponent with HasGameRef, KeyboardHandler { final Vector2 _input = Vector2.zero(); @@ -27,7 +28,7 @@ class Player extends MeshComponent Vector3 get lookAt => Vector3(sin(_lookAngle), 0.0, cos(_lookAngle)); - Player({required Vector3 position}) + this : super( position: position, mesh: CuboidMesh( diff --git a/packages/flame_3d/example/lib/components/rendered_point_light.dart b/packages/flame_3d/example/lib/components/rendered_point_light.dart index 1b71a3b795a..23320499961 100644 --- a/packages/flame_3d/example/lib/components/rendered_point_light.dart +++ b/packages/flame_3d/example/lib/components/rendered_point_light.dart @@ -4,14 +4,10 @@ import 'dart:ui'; import 'package:flame_3d/components.dart'; import 'package:flame_3d/resources.dart'; -class RenderedPointLight extends Component3D { - final Color color; - - RenderedPointLight({ - required super.position, - required this.color, - }); - +class RenderedPointLight({ + required super.position, + required final Color color, +}) extends Component3D { @override FutureOr onLoad() async { addAll([ diff --git a/packages/flame_3d/example/lib/components/room_bounds.dart b/packages/flame_3d/example/lib/components/room_bounds.dart index 0ee17ea2253..42f6fed3ede 100644 --- a/packages/flame_3d/example/lib/components/room_bounds.dart +++ b/packages/flame_3d/example/lib/components/room_bounds.dart @@ -5,7 +5,7 @@ import 'package:flame/palette.dart'; import 'package:flame_3d/components.dart'; import 'package:flame_3d/resources.dart'; -class RoomBounds extends Component { +class RoomBounds() extends Component { @override FutureOr onLoad() { addAll([ diff --git a/packages/flame_3d/example/lib/components/rotating_light.dart b/packages/flame_3d/example/lib/components/rotating_light.dart index f1eb7609f2c..d3d61ebcf8c 100644 --- a/packages/flame_3d/example/lib/components/rotating_light.dart +++ b/packages/flame_3d/example/lib/components/rotating_light.dart @@ -4,8 +4,8 @@ import 'dart:ui'; import 'package:flame_3d/components.dart'; import 'package:flame_3d/game.dart'; -class RotatingLight extends LightComponent { - RotatingLight() +class RotatingLight() extends LightComponent { + this : super.point( position: Vector3.zero(), color: const Color(0xFF00FF00), diff --git a/packages/flame_3d/example/lib/components/simple_hud.dart b/packages/flame_3d/example/lib/components/simple_hud.dart index 96d842b512c..5725ac0e414 100644 --- a/packages/flame_3d/example/lib/components/simple_hud.dart +++ b/packages/flame_3d/example/lib/components/simple_hud.dart @@ -21,8 +21,8 @@ final _style = TextStyle( ], ); -class SimpleHud extends Component with HasGameRef { - SimpleHud() : super(children: [FpsComponent()]); +class SimpleHud() extends Component with HasGameRef { + this : super(children: [FpsComponent()]); String get fps => children.query().firstOrNull?.fps.toStringAsFixed(2) ?? '0'; diff --git a/packages/flame_3d/example/lib/example_camera_3d.dart b/packages/flame_3d/example/lib/example_camera_3d.dart index 84aba9290b0..af05519feb9 100644 --- a/packages/flame_3d/example/lib/example_camera_3d.dart +++ b/packages/flame_3d/example/lib/example_camera_3d.dart @@ -5,12 +5,14 @@ import 'package:flame_3d_example/components/player.dart'; import 'package:flame_3d_example/components/simple_hud.dart'; import 'package:flame_3d_example/example_game_3d.dart'; -class ExampleCamera3D extends CameraComponent3D with HasGameRef { +class ExampleCamera3D() + extends CameraComponent3D + with HasGameRef { CameraMode _mode = CameraMode.player; double distance = 5.0; Vector2 delta = Vector2.zero(); - ExampleCamera3D() + this : super( position: Vector3(0, 2, 4), projection: CameraProjection.perspective, @@ -73,7 +75,7 @@ class ExampleCamera3D extends CameraComponent3D with HasGameRef { static const double _cameraLinearSpeed = 12.0; } -enum CameraMode { +enum CameraMode() { drag, player, } diff --git a/packages/flame_3d/example/lib/example_game_3d.dart b/packages/flame_3d/example/lib/example_game_3d.dart index 7765628371a..6cbdfa74282 100644 --- a/packages/flame_3d/example/lib/example_game_3d.dart +++ b/packages/flame_3d/example/lib/example_game_3d.dart @@ -11,11 +11,12 @@ import 'package:flame_3d_example/scenarios/game_scenario.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; -class ExampleGame3D extends FlameGame3D +class ExampleGame3D() + extends FlameGame3D with DragCallbacks, ScrollCallbacks, HasKeyboardHandlerComponents { late final Player player; - ExampleGame3D() + this : super( world: World3D(), camera: ExampleCamera3D(), diff --git a/packages/flame_3d/example/lib/scenarios/boxes_scenario.dart b/packages/flame_3d/example/lib/scenarios/boxes_scenario.dart index 03a202b0a29..a21b11965e8 100644 --- a/packages/flame_3d/example/lib/scenarios/boxes_scenario.dart +++ b/packages/flame_3d/example/lib/scenarios/boxes_scenario.dart @@ -10,7 +10,7 @@ import 'package:flame_3d_example/components/rotating_light.dart'; import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_3d_example/scenarios/game_scenario.dart'; -class BoxesScenario implements GameScenario { +class BoxesScenario() implements GameScenario { @override Future onLoad() async {} diff --git a/packages/flame_3d/example/lib/scenarios/colors_scenario.dart b/packages/flame_3d/example/lib/scenarios/colors_scenario.dart index 35090c44686..77be3169940 100644 --- a/packages/flame_3d/example/lib/scenarios/colors_scenario.dart +++ b/packages/flame_3d/example/lib/scenarios/colors_scenario.dart @@ -6,7 +6,7 @@ import 'package:flame_3d_example/components/rendered_point_light.dart'; import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_3d_example/scenarios/game_scenario.dart'; -class ColorsScenario implements GameScenario { +class ColorsScenario() implements GameScenario { @override Future onLoad() async {} diff --git a/packages/flame_3d/example/lib/scenarios/culling_scenario.dart b/packages/flame_3d/example/lib/scenarios/culling_scenario.dart index b5a2823ee47..61070c5e12d 100644 --- a/packages/flame_3d/example/lib/scenarios/culling_scenario.dart +++ b/packages/flame_3d/example/lib/scenarios/culling_scenario.dart @@ -8,7 +8,7 @@ import 'package:flame_3d_example/components/rendered_point_light.dart'; import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_3d_example/scenarios/game_scenario.dart'; -class CullingScenario implements GameScenario { +class CullingScenario() implements GameScenario { @override Future onLoad() async {} @@ -73,11 +73,11 @@ class CullingScenario implements GameScenario { } } -class _ObjectGroup extends Object3D { - _ObjectGroup({ - required List children, - super.position, - }) : super(children: children); +class _ObjectGroup({ + required List children, + super.position, +}) extends Object3D { + this : super(children: children); @override void draw(RenderContext context) {} diff --git a/packages/flame_3d/example/lib/scenarios/game_scenario.dart b/packages/flame_3d/example/lib/scenarios/game_scenario.dart index 0334f5bd7e2..f1de13a05dc 100644 --- a/packages/flame_3d/example/lib/scenarios/game_scenario.dart +++ b/packages/flame_3d/example/lib/scenarios/game_scenario.dart @@ -4,7 +4,7 @@ import 'package:flame_3d_example/scenarios/colors_scenario.dart'; import 'package:flame_3d_example/scenarios/culling_scenario.dart'; import 'package:flame_3d_example/scenarios/models_scenario.dart'; -abstract class GameScenario { +abstract class GameScenario() { Future onLoad(); void setup(ExampleGame3D game); diff --git a/packages/flame_3d/example/lib/scenarios/models_scenario.dart b/packages/flame_3d/example/lib/scenarios/models_scenario.dart index f85a86e14a0..acc4bfb42a2 100644 --- a/packages/flame_3d/example/lib/scenarios/models_scenario.dart +++ b/packages/flame_3d/example/lib/scenarios/models_scenario.dart @@ -4,7 +4,7 @@ import 'package:flame_3d/parser.dart'; import 'package:flame_3d_example/example_game_3d.dart'; import 'package:flame_3d_example/scenarios/game_scenario.dart'; -class ModelsScenario implements GameScenario { +class ModelsScenario() implements GameScenario { late final Model model; @override diff --git a/packages/flame_3d/example/pubspec.yaml b/packages/flame_3d/example/pubspec.yaml index 7add630fcfa..6a66cb71829 100644 --- a/packages/flame_3d/example/pubspec.yaml +++ b/packages/flame_3d/example/pubspec.yaml @@ -5,7 +5,7 @@ version: 0.0.1+1 publish_to: none environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_3d/lib/core.dart b/packages/flame_3d/lib/core.dart index 97d9212061c..7198e23cd26 100644 --- a/packages/flame_3d/lib/core.dart +++ b/packages/flame_3d/lib/core.dart @@ -1,12 +1,12 @@ export 'package:vector_math/vector_math.dart' show - Vector2, - Vector3, - Vector4, + Aabb3, Matrix2, Matrix3, Matrix4, Quaternion, - Aabb3; + Vector2, + Vector3, + Vector4; export 'extensions.dart'; diff --git a/packages/flame_3d/lib/src/camera/camera_component_3d.dart b/packages/flame_3d/lib/src/camera/camera_component_3d.dart index fbcd7d3dace..fa67c7838ec 100644 --- a/packages/flame_3d/lib/src/camera/camera_component_3d.dart +++ b/packages/flame_3d/lib/src/camera/camera_component_3d.dart @@ -1,48 +1,45 @@ import 'package:flame_3d/camera.dart'; import 'package:flame_3d/game.dart'; -enum CameraProjection { perspective, orthographic } +enum CameraProjection() { + perspective, + orthographic, +} /// {@template camera_component_3d} /// [CameraComponent3D] is a component through which a [World3D] is observed. /// {@endtemplate} -class CameraComponent3D extends CameraComponent { - /// {@macro camera_component_3d} - CameraComponent3D({ - this.fovY = 60, - Vector3? position, - Quaternion? rotation, - Vector3? target, - Vector3? up, - this.projection = CameraProjection.perspective, - World3D? super.world, - super.viewport, - super.viewfinder, - super.backdrop, - super.hudComponents, - }) : position = position?.clone() ?? Vector3.zero(), - rotation = rotation ?? Quaternion.identity(), - target = target?.clone() ?? Vector3(0, 0, -1), - _up = up?.clone() ?? Vector3(0, 1, 0); +class CameraComponent3D({ + /// The [fovY] is the field of view in Y (degrees) when the [projection] is + /// [CameraProjection.perspective] otherwise it is used as the near plane when + /// the [projection] is [CameraProjection.orthographic]. + var double fovY = 60, + Vector3? position, + Quaternion? rotation, + Vector3? target, + Vector3? up, + /// The current camera projection. + var CameraProjection projection = CameraProjection.perspective, + World3D? super.world, + super.viewport, + super.viewfinder, + super.backdrop, + super.hudComponents, +}) extends CameraComponent { @override World3D? get world => super.world as World3D?; @override set world(covariant World3D? world) => super.world = world; - /// The [fovY] is the field of view in Y (degrees) when the [projection] is - /// [CameraProjection.perspective] otherwise it is used as the near plane when - /// the [projection] is [CameraProjection.orthographic]. - double fovY; - /// The position of the camera in 3D space. /// /// Often also referred to as the "eye". - Vector3 position; + Vector3 position = position?.clone() ?? Vector3.zero(); /// The target in 3D space that the camera is looking at. - Vector3 target; + Vector3 target = target?.clone() ?? Vector3(0, 0, -1); /// The forward direction relative to the camera. Vector3 get forward => target - position; @@ -53,13 +50,10 @@ class CameraComponent3D extends CameraComponent { /// The up direction relative to the camera. Vector3 get up => _up.normalized(); set up(Vector3 up) => _up.setFrom(up); - final Vector3 _up; + final Vector3 _up = up?.clone() ?? Vector3(0, 1, 0); /// The rotation of the camera. - Quaternion rotation; - - /// The current camera projection. - CameraProjection projection; + Quaternion rotation = rotation ?? Quaternion.identity(); /// The view matrix of the camera, this is without any projection applied on /// it. diff --git a/packages/flame_3d/lib/src/camera/first_person_camera.dart b/packages/flame_3d/lib/src/camera/first_person_camera.dart index 34aa06552aa..10e1c479e4f 100644 --- a/packages/flame_3d/lib/src/camera/first_person_camera.dart +++ b/packages/flame_3d/lib/src/camera/first_person_camera.dart @@ -2,24 +2,20 @@ import 'package:flame_3d/camera.dart'; import 'package:flame_3d/core.dart'; import 'package:meta/meta.dart'; -class FirstPersonCamera extends CameraComponent3D { - FirstPersonCamera({ - required this.following, - super.fovY, - super.position, - super.rotation, - super.up, - super.projection, - super.world, - super.viewport, - super.viewfinder, - super.backdrop, - super.hudComponents, - }); - +class FirstPersonCamera({ /// The point the camera should follow. - Vector3 following; - + required var Vector3 following, + super.fovY, + super.position, + super.rotation, + super.up, + super.projection, + super.world, + super.viewport, + super.viewfinder, + super.backdrop, + super.hudComponents, +}) extends CameraComponent3D { @override @mustCallSuper void update(double dt) { diff --git a/packages/flame_3d/lib/src/camera/third_person_camera.dart b/packages/flame_3d/lib/src/camera/third_person_camera.dart index 77ab461ecc6..e36c1195a99 100644 --- a/packages/flame_3d/lib/src/camera/third_person_camera.dart +++ b/packages/flame_3d/lib/src/camera/third_person_camera.dart @@ -2,36 +2,29 @@ import 'package:flame_3d/camera.dart'; import 'package:flame_3d/core.dart'; import 'package:meta/meta.dart'; -class ThirdPersonCamera extends CameraComponent3D { - ThirdPersonCamera({ - required this.following, - this._distance = 5.0, - this.followDamping = 1.0, - super.fovY, - super.position, - super.rotation, - super.up, - super.projection, - super.world, - super.viewport, - super.viewfinder, - super.backdrop, - super.hudComponents, - }); - +class ThirdPersonCamera({ /// The point the camera should follow. - Vector3 following; - - /// The distance the camera should maintain from the `following` point. - double get distance => _distance; - set distance(double value) => _distance = value.clamp(0.1, double.infinity); - double _distance; + required var Vector3 following, + var double _distance = 5.0, /// Damping factor for smoothing out rotation and position changes. /// /// If the value is `1`, no damping is applied. - double followDamping; - + var double followDamping = 1.0, + super.fovY, + super.position, + super.rotation, + super.up, + super.projection, + super.world, + super.viewport, + super.viewfinder, + super.backdrop, + super.hudComponents, +}) extends CameraComponent3D { + /// The distance the camera should maintain from the `following` point. + double get distance => _distance; + set distance(double value) => _distance = value.clamp(0.1, double.infinity); @override @mustCallSuper void update(double dt) { diff --git a/packages/flame_3d/lib/src/camera/world_3d.dart b/packages/flame_3d/lib/src/camera/world_3d.dart index 997c9813f1e..d15c093daea 100644 --- a/packages/flame_3d/lib/src/camera/world_3d.dart +++ b/packages/flame_3d/lib/src/camera/world_3d.dart @@ -15,13 +15,10 @@ import 'package:meta/meta.dart'; /// The primary feature of this component is that it allows [Component3D]s to /// render directly to a [GraphicsDevice] instead of the regular rendering. /// {@endtemplate} -class World3D extends flame.World with flame.HasGameRef { - /// {@macro world_3d} - World3D({ - super.children, - super.priority, - }); - +class World3D({ + super.children, + super.priority, +}) extends flame.World with flame.HasGameRef { final List _lights = []; RenderContext3D get context => gameRef.context; diff --git a/packages/flame_3d/lib/src/components/component_3d.dart b/packages/flame_3d/lib/src/components/component_3d.dart index 67644271834..f08ad8b29ee 100644 --- a/packages/flame_3d/lib/src/components/component_3d.dart +++ b/packages/flame_3d/lib/src/components/component_3d.dart @@ -30,20 +30,19 @@ import 'package:meta/meta.dart'; /// rotating or scaling the [Component3D] will affect the whole /// group as if it was a single entity. /// {@endtemplate} -abstract class Component3D extends Component with HasWorldRef { - final Transform3D transform; +abstract class Component3D({ + Vector3? position, + Vector3? scale, + Quaternion? rotation, + List children = const [], +}) extends Component with HasWorldRef { + final Transform3D transform = Transform3D() + ..position = position ?? Vector3.zero() + ..rotation = rotation ?? Quaternion.euler(0, 0, 0) + ..scale = scale ?? Vector3.all(1); /// {@macro component_3d} - Component3D({ - Vector3? position, - Vector3? scale, - Quaternion? rotation, - List children = const [], - }) : transform = Transform3D() - ..position = position ?? Vector3.zero() - ..rotation = rotation ?? Quaternion.euler(0, 0, 0) - ..scale = scale ?? Vector3.all(1), - super(children: children) { + this : super(children: children) { this.children.register(); _childComponents = this.children.query(); transform.addListener(_onTransformChanged); diff --git a/packages/flame_3d/lib/src/components/light_component.dart b/packages/flame_3d/lib/src/components/light_component.dart index 8e73f0d92d8..1922c7c8d82 100644 --- a/packages/flame_3d/lib/src/components/light_component.dart +++ b/packages/flame_3d/lib/src/components/light_component.dart @@ -6,12 +6,10 @@ import 'package:flame_3d/game.dart'; import 'package:flame_3d/resources.dart'; /// A [Component3D] that represents a light source in 3D space. -class LightComponent extends Component3D { - LightComponent({ - required this.source, - super.position, - }); - +class LightComponent({ + required final LightSource source, + super.position, +}) extends Component3D { LightComponent.point({ Vector3? position, Color color = const Color(0xFFFFFFFF), @@ -34,8 +32,6 @@ class LightComponent extends Component3D { ), ); - final LightSource source; - late final Light _light = Light( position: Vector3.fromBuffer( worldTransformMatrix.storage.buffer, diff --git a/packages/flame_3d/lib/src/components/line_3d.dart b/packages/flame_3d/lib/src/components/line_3d.dart index 386c9759a23..528e0fbb388 100644 --- a/packages/flame_3d/lib/src/components/line_3d.dart +++ b/packages/flame_3d/lib/src/components/line_3d.dart @@ -4,18 +4,19 @@ import 'package:flame_3d/components.dart'; import 'package:flame_3d/game.dart'; import 'package:flame_3d/resources.dart'; -class Line3D extends MeshComponent { - Line3D._({ - required double radius, - required double height, - required Material material, - }) : super( - mesh: CylinderMesh( - radius: radius, - height: height, - material: material, - ), - ); +class Line3D._({ + required double radius, + required double height, + required Material material, +}) extends MeshComponent { + this + : super( + mesh: CylinderMesh( + radius: radius, + height: height, + material: material, + ), + ); factory Line3D.generate({ required Vector3 start, diff --git a/packages/flame_3d/lib/src/components/mesh_component.dart b/packages/flame_3d/lib/src/components/mesh_component.dart index fa5cdd5eb5e..2cbc1c4308a 100644 --- a/packages/flame_3d/lib/src/components/mesh_component.dart +++ b/packages/flame_3d/lib/src/components/mesh_component.dart @@ -10,20 +10,15 @@ import 'package:flame_3d/src/camera/camera_component_3d.dart'; /// /// This is a commonly used subclass of [Object3D]. /// {@endtemplate} -class MeshComponent extends Object3D { - /// {@macro mesh_component} - MeshComponent({ - required this._mesh, - super.position, - super.scale, - super.rotation, - super.children, - }); - +class MeshComponent({ + required final Mesh _mesh, + super.position, + super.scale, + super.rotation, + super.children, +}) extends Object3D { /// The mesh resource. Mesh get mesh => _mesh; - final Mesh _mesh; - @override Aabb3? computeLocalAabb() => mesh.aabb; diff --git a/packages/flame_3d/lib/src/components/object_3d.dart b/packages/flame_3d/lib/src/components/object_3d.dart index d287d7927bb..d5295376a62 100644 --- a/packages/flame_3d/lib/src/components/object_3d.dart +++ b/packages/flame_3d/lib/src/components/object_3d.dart @@ -20,15 +20,12 @@ import 'package:flame_3d/resources.dart'; /// See the [MeshComponent] for an [Object3D] that has a visual representation /// using a [Mesh]. /// {@endtemplate} -abstract class Object3D extends Component3D { - /// {@macro object_3d} - Object3D({ - super.position, - super.scale, - super.rotation, - super.children, - }); - +abstract class Object3D({ + super.position, + super.scale, + super.rotation, + super.children, +}) extends Component3D { /// Whether an ancestor's AABB was fully inside the frustum, meaning /// children can skip their own frustum tests. static bool _ancestorFullyInside = false; diff --git a/packages/flame_3d/lib/src/extensions/aabb3.dart b/packages/flame_3d/lib/src/extensions/aabb3.dart index f0a3effc498..4230f6bbb18 100644 --- a/packages/flame_3d/lib/src/extensions/aabb3.dart +++ b/packages/flame_3d/lib/src/extensions/aabb3.dart @@ -2,7 +2,7 @@ import 'package:flame_3d/game.dart'; import 'package:vector_math/vector_math.dart' show Frustum; /// Result of a frustum-AABB intersection test. -enum CullResult { +enum CullResult() { /// The AABB is fully outside the frustum cull the entire subtree. outside, diff --git a/packages/flame_3d/lib/src/extensions/matrix4.dart b/packages/flame_3d/lib/src/extensions/matrix4.dart index 7060adfe66a..3b397648b9c 100644 --- a/packages/flame_3d/lib/src/extensions/matrix4.dart +++ b/packages/flame_3d/lib/src/extensions/matrix4.dart @@ -3,9 +3,9 @@ import 'package:flame_3d/game.dart'; export 'package:vector_math/vector_math.dart' show degrees2Radians, - setViewMatrix, + setOrthographicMatrix, setPerspectiveMatrix, - setOrthographicMatrix; + setViewMatrix; extension Matrix4Extension on Matrix4 { /// Set the matrix to be a view matrix. diff --git a/packages/flame_3d/lib/src/extensions/quaternion.dart b/packages/flame_3d/lib/src/extensions/quaternion.dart index 14936c12368..785cd1cf926 100644 --- a/packages/flame_3d/lib/src/extensions/quaternion.dart +++ b/packages/flame_3d/lib/src/extensions/quaternion.dart @@ -22,9 +22,7 @@ extension QuaternionExtension on Quaternion { } } -final class QuaternionUtils { - QuaternionUtils._(); - +final class QuaternionUtils._() { static Quaternion slerp( Quaternion q0, Quaternion q1, diff --git a/packages/flame_3d/lib/src/extensions/vector2.dart b/packages/flame_3d/lib/src/extensions/vector2.dart index 1b607209c27..92450b223ee 100644 --- a/packages/flame_3d/lib/src/extensions/vector2.dart +++ b/packages/flame_3d/lib/src/extensions/vector2.dart @@ -12,9 +12,7 @@ extension Vector2Extension on Vector2 { } } -final class Vector2Utils { - Vector2Utils._(); - +final class Vector2Utils._() { static Vector2 lerp(Vector2 a, Vector2 b, double t) { return a + (b - a).scaled(t); } diff --git a/packages/flame_3d/lib/src/extensions/vector3.dart b/packages/flame_3d/lib/src/extensions/vector3.dart index e3a01f73336..1b6db0ad512 100644 --- a/packages/flame_3d/lib/src/extensions/vector3.dart +++ b/packages/flame_3d/lib/src/extensions/vector3.dart @@ -12,9 +12,7 @@ extension Vector3Extension on Vector3 { } } -class Vector3Utils { - Vector3Utils._(); - +class Vector3Utils._() { static Vector3 lerp(Vector3 a, Vector3 b, double t) { return a + (b - a).scaled(t); } diff --git a/packages/flame_3d/lib/src/extensions/vector4.dart b/packages/flame_3d/lib/src/extensions/vector4.dart index 92aeb46d6ed..93f076ce5f0 100644 --- a/packages/flame_3d/lib/src/extensions/vector4.dart +++ b/packages/flame_3d/lib/src/extensions/vector4.dart @@ -14,9 +14,7 @@ extension Vector4Extension on Vector4 { } } -class Vector4Utils { - Vector4Utils._(); - +class Vector4Utils._() { static Vector4 lerp(Vector4 a, Vector4 b, double t) { return a + (b - a).scaled(t); } diff --git a/packages/flame_3d/lib/src/game/flame_game_3d.dart b/packages/flame_3d/lib/src/game/flame_game_3d.dart index 724364f7e17..a47eefd1750 100644 --- a/packages/flame_3d/lib/src/game/flame_game_3d.dart +++ b/packages/flame_3d/lib/src/game/flame_game_3d.dart @@ -2,17 +2,16 @@ import 'package:flame/game.dart'; import 'package:flame_3d/camera.dart'; import 'package:flame_3d/game.dart'; -class FlameGame3D - extends FlameGame - with Game3D { - FlameGame3D({ - super.children, - W? world, - C? camera, - }) : super( - world: world ?? World3D() as W, - camera: camera ?? CameraComponent3D() as C, - ); +class FlameGame3D({ + super.children, + W? world, + C? camera, +}) extends FlameGame with Game3D { + this + : super( + world: world ?? World3D() as W, + camera: camera ?? CameraComponent3D() as C, + ); @override C get camera => super.camera as C; diff --git a/packages/flame_3d/lib/src/game/notifying_quaternion.dart b/packages/flame_3d/lib/src/game/notifying_quaternion.dart index e1cbf37dbd2..9a18f523f2b 100644 --- a/packages/flame_3d/lib/src/game/notifying_quaternion.dart +++ b/packages/flame_3d/lib/src/game/notifying_quaternion.dart @@ -14,13 +14,13 @@ import 'package:flutter/foundation.dart'; /// /// Direct modification of this quaternion's [storage] is not allowed. /// {@endtemplate} -class NotifyingQuaternion extends Quaternion with ChangeNotifier { +class NotifyingQuaternion._() extends Quaternion with ChangeNotifier { /// {@macro notifying_quaternion} /// /// Constructs a quaternion using the raw values [x], [y], [z], and [w]. factory NotifyingQuaternion(double x, double y, double z, double w) => NotifyingQuaternion._()..setValues(x, y, z, w); - NotifyingQuaternion._() : super.fromFloat32List(Float32List(4)); + this : super.fromFloat32List(Float32List(4)); /// {@macro notifying_quaternion} /// diff --git a/packages/flame_3d/lib/src/game/notifying_vector3.dart b/packages/flame_3d/lib/src/game/notifying_vector3.dart index 369500dbd00..50e812176bc 100644 --- a/packages/flame_3d/lib/src/game/notifying_vector3.dart +++ b/packages/flame_3d/lib/src/game/notifying_vector3.dart @@ -12,7 +12,7 @@ import 'package:flutter/foundation.dart'; /// /// Direct modification of this vector's [storage] is not allowed. /// {@endtemplate} -class NotifyingVector3 extends Vector3 with ChangeNotifier { +class NotifyingVector3.zero() extends Vector3 with ChangeNotifier { /// {@macro notifying_vector_3} /// /// Constructs a vector using the raw values [x], [y], and [z]. @@ -22,7 +22,7 @@ class NotifyingVector3 extends Vector3 with ChangeNotifier { /// {@macro notifying_vector_3} /// /// Create an empty vector. - NotifyingVector3.zero() : super.zero(); + this : super.zero(); /// {@macro notifying_vector_3} /// diff --git a/packages/flame_3d/lib/src/game/transform_3d.dart b/packages/flame_3d/lib/src/game/transform_3d.dart index ebc559efce0..a43f8f706e3 100644 --- a/packages/flame_3d/lib/src/game/transform_3d.dart +++ b/packages/flame_3d/lib/src/game/transform_3d.dart @@ -26,9 +26,9 @@ import 'package:flutter/foundation.dart' show ChangeNotifier; /// can subscribe to get notified when individual components of the transform /// change: [position], [scale], and [rotation]. /// {@endtemplate} -class Transform3D extends ChangeNotifier { +class Transform3D() extends ChangeNotifier { /// {@macro transform_3d} - Transform3D() + this : _recalculate = true, _position = NotifyingVector3.zero(), _rotation = NotifyingQuaternion(0, 0, 0, 0), diff --git a/packages/flame_3d/lib/src/game/unmodifiable_vector3.dart b/packages/flame_3d/lib/src/game/unmodifiable_vector3.dart index b5088e7d44f..52a29ca65dc 100644 --- a/packages/flame_3d/lib/src/game/unmodifiable_vector3.dart +++ b/packages/flame_3d/lib/src/game/unmodifiable_vector3.dart @@ -9,7 +9,7 @@ import 'package:flutter/foundation.dart'; /// /// Direct modification of this vector's [storage] is not allowed. /// {@endtemplate} -class UnmodifiableVector3 extends Vector3 { +class UnmodifiableVector3.zero() extends Vector3 { /// {@macro unmodifiable_vector_3} /// /// Constructs a vector using the raw values [x], [y], and [z]. @@ -19,7 +19,7 @@ class UnmodifiableVector3 extends Vector3 { /// {@macro unmodifiable_vector_3} /// /// Create an empty vector. - UnmodifiableVector3.zero() : super.zero(); + this : super.zero(); /// {@macro unmodifiable_vector_3} /// diff --git a/packages/flame_3d/lib/src/graphics/backend/flutter_gpu/gpu_backend.dart b/packages/flame_3d/lib/src/graphics/backend/flutter_gpu/gpu_backend.dart index b6cac6baddb..a635ea58d52 100644 --- a/packages/flame_3d/lib/src/graphics/backend/flutter_gpu/gpu_backend.dart +++ b/packages/flame_3d/lib/src/graphics/backend/flutter_gpu/gpu_backend.dart @@ -10,19 +10,17 @@ import 'package:flutter/services.dart'; import 'package:flutter_gpu/gpu.dart' as gpu; /// A [base.GpuBackend] implemented on top of `flutter_gpu`. -base class GpuBackend extends base.GpuBackend { +/// +/// Creates a backend wrapping `gpuContext`, defaulting to the global +/// `flutter_gpu` context. +base class GpuBackend({gpu.GpuContext? gpuContext}) extends base.GpuBackend { static Future initialize() async { await create()?._preloadShaderLibraries(); } static GpuBackend? create() => GpuBackend(); - /// Creates a backend wrapping [gpuContext], defaulting to the global - /// `flutter_gpu` context. - GpuBackend({gpu.GpuContext? gpuContext}) - : _context = gpuContext ?? gpu.gpuContext; - - final gpu.GpuContext _context; + final gpu.GpuContext _context = gpuContext ?? gpu.gpuContext; late final gpu.HostBuffer _hostBuffer = _context.createHostBuffer(); late final _FlutterGpuFrame _frame = _FlutterGpuFrame(this); @@ -156,11 +154,7 @@ base class GpuBackend extends base.GpuBackend { } } -class _FlutterGpuTexture implements GpuTexture { - const _FlutterGpuTexture(this.raw); - - final gpu.Texture raw; - +class const _FlutterGpuTexture(final gpu.Texture raw) implements GpuTexture { @override void write(ByteData data) => raw.overwrite(data); @@ -168,24 +162,17 @@ class _FlutterGpuTexture implements GpuTexture { Image asImage() => raw.asImage(); } -class _FlutterGpuBuffer implements GpuBuffer { - const _FlutterGpuBuffer(this.raw); - - final gpu.DeviceBuffer raw; - +class const _FlutterGpuBuffer(final gpu.DeviceBuffer raw) implements GpuBuffer { @override void write(ByteData data, {int destinationOffsetInBytes = 0}) { raw.overwrite(data, destinationOffsetInBytes: destinationOffsetInBytes); } } -class _FlutterGpuShaderLibrary implements GpuShaderLibrary { - const _FlutterGpuShaderLibrary(this.raw, this._assetName); - - final gpu.ShaderLibrary raw; - - final String _assetName; - +class const _FlutterGpuShaderLibrary( + final gpu.ShaderLibrary raw, + final String _assetName, +) implements GpuShaderLibrary { @override GpuShader operator [](String entryPoint) { final shader = raw[entryPoint]; @@ -198,22 +185,15 @@ class _FlutterGpuShaderLibrary implements GpuShaderLibrary { } } -class _FlutterGpuShader implements GpuShader { - const _FlutterGpuShader(this.raw); - - final gpu.Shader raw; - +class const _FlutterGpuShader(final gpu.Shader raw) implements GpuShader { @override GpuUniformSlot getUniformSlot(String slot) { return _FlutterGpuUniformSlot(raw.getUniformSlot(slot)); } } -class _FlutterGpuUniformSlot implements GpuUniformSlot { - const _FlutterGpuUniformSlot(this.raw); - - final gpu.UniformSlot raw; - +class const _FlutterGpuUniformSlot(final gpu.UniformSlot raw) + implements GpuUniformSlot { @override int? get sizeInBytes => raw.sizeInBytes; @@ -223,28 +203,19 @@ class _FlutterGpuUniformSlot implements GpuUniformSlot { } } -class _FlutterGpuPipeline implements GpuPipeline { - const _FlutterGpuPipeline(this.raw); - - final gpu.RenderPipeline raw; -} - -class _FlutterGpuRenderTarget implements GpuRenderTarget { - const _FlutterGpuRenderTarget(this._colorTexture, this.raw); - - final _FlutterGpuTexture _colorTexture; - - final gpu.RenderTarget raw; +class const _FlutterGpuPipeline(final gpu.RenderPipeline raw) + implements GpuPipeline; +class const _FlutterGpuRenderTarget( + final _FlutterGpuTexture _colorTexture, + final gpu.RenderTarget raw, +) implements GpuRenderTarget { @override GpuTexture get colorTexture => _colorTexture; } -class _FlutterGpuFrame implements base.GpuFrame { - const _FlutterGpuFrame(this._backend); - - final GpuBackend _backend; - +class const _FlutterGpuFrame(final GpuBackend _backend) + implements base.GpuFrame { @override base.GpuRenderPass beginRenderPass( GpuRenderTarget target, { @@ -297,19 +268,11 @@ class _FlutterGpuFrame implements base.GpuFrame { } } -class _FlutterGpuRenderPass implements base.GpuRenderPass { - _FlutterGpuRenderPass( - this._backend, - this._commandBuffer, - this._renderPass, - ); - - final GpuBackend _backend; - - final gpu.CommandBuffer _commandBuffer; - - final gpu.RenderPass _renderPass; - +class _FlutterGpuRenderPass( + final GpuBackend _backend, + final gpu.CommandBuffer _commandBuffer, + final gpu.RenderPass _renderPass, +) implements base.GpuRenderPass { // `flutter_gpu` takes the counts in `draw`/`drawIndexed` rather than at // bind time, so they are recorded here until [draw] is called. int _vertexCount = 0; diff --git a/packages/flame_3d/lib/src/graphics/backend/gpu_backend.dart b/packages/flame_3d/lib/src/graphics/backend/gpu_backend.dart index 9dae6de71c2..1f86f368d3d 100644 --- a/packages/flame_3d/lib/src/graphics/backend/gpu_backend.dart +++ b/packages/flame_3d/lib/src/graphics/backend/gpu_backend.dart @@ -17,8 +17,8 @@ import 'package:flame_3d/src/graphics/backend/gpu_handles.dart'; /// [GpuBackend] implementation sets the [instance] at construction time through /// it's super constructor. /// {@endtemplate} -abstract base class GpuBackend { - GpuBackend() { +abstract base class GpuBackend() { + this { _instance = this; } @@ -81,7 +81,7 @@ abstract base class GpuBackend { /// /// Owns the transient uniform storage shared across the frame's render passes. /// Obtain one via [GpuBackend.beginFrame] and finalize it with [end]. -abstract interface class GpuFrame { +abstract interface class GpuFrame() { /// Begins a render pass that draws into [target] using [blend] and /// [depthStencil] state. GpuRenderPass beginRenderPass( @@ -97,7 +97,7 @@ abstract interface class GpuFrame { /// Records the bind and draw commands of a single render pass. /// /// Obtain one via [GpuFrame.beginRenderPass] and submit it with [submit]. -abstract interface class GpuRenderPass { +abstract interface class GpuRenderPass() { /// Binds the render [pipeline] and applies [cullMode]. void bindPipeline(GpuPipeline pipeline, CullMode cullMode); diff --git a/packages/flame_3d/lib/src/graphics/backend/gpu_enums.dart b/packages/flame_3d/lib/src/graphics/backend/gpu_enums.dart index 711b3244c5c..ab37636f0e5 100644 --- a/packages/flame_3d/lib/src/graphics/backend/gpu_enums.dart +++ b/packages/flame_3d/lib/src/graphics/backend/gpu_enums.dart @@ -1,5 +1,5 @@ /// How a GPU resource's memory is allocated and accessed. -enum GpuStorageMode { +enum GpuStorageMode() { /// Memory visible to the host (CPU): used for resources written from Dart. hostVisible, @@ -11,7 +11,7 @@ enum GpuStorageMode { } /// Pixel layout of a GPU texture. -enum GpuPixelFormat { +enum GpuPixelFormat() { /// 8 bits per channel, RGBA order. rgba8888, @@ -26,7 +26,7 @@ enum GpuPixelFormat { } /// Width of the integers stored in an index buffer. -enum GpuIndexType { +enum GpuIndexType() { /// 16-bit unsigned indices. uint16, @@ -35,7 +35,7 @@ enum GpuIndexType { } /// Color blending mode for a render pass output. -enum BlendState { +enum BlendState() { /// No blending, source overwrites destination. opaque, @@ -48,7 +48,7 @@ enum BlendState { } /// Depth buffer behavior for a render pass. -enum DepthStencilState { +enum DepthStencilState() { /// Depth test and write enabled (normal opaque 3D rendering). /// Fragments closer than the stored depth pass and update the buffer. standard, @@ -63,7 +63,7 @@ enum DepthStencilState { /// Face culling mode. Controls which triangle faces are discarded before /// rasterization. -enum CullMode { +enum CullMode() { /// No culling, both front and back faces are rendered. none, diff --git a/packages/flame_3d/lib/src/graphics/backend/gpu_handles.dart b/packages/flame_3d/lib/src/graphics/backend/gpu_handles.dart index 4581f9307a7..6b961c90b4b 100644 --- a/packages/flame_3d/lib/src/graphics/backend/gpu_handles.dart +++ b/packages/flame_3d/lib/src/graphics/backend/gpu_handles.dart @@ -2,7 +2,7 @@ import 'dart:typed_data'; import 'dart:ui'; /// Handle to a GPU texture. -abstract interface class GpuTexture { +abstract interface class GpuTexture() { /// Uploads [data] to the texture. void write(ByteData data); @@ -11,35 +11,30 @@ abstract interface class GpuTexture { } /// Handle to a GPU buffer holding vertex/index data. -abstract interface class GpuBuffer { +abstract interface class GpuBuffer() { /// Uploads [data] into the buffer starting at [destinationOffsetInBytes]. void write(ByteData data, {int destinationOffsetInBytes = 0}); } /// A windowed view over a region of a [GpuBuffer]. -class GpuBufferView { - /// Creates a view over [buffer] spanning [lengthInBytes] bytes starting at - /// [offsetInBytes]. - const GpuBufferView( - this.buffer, { - required this.offsetInBytes, - required this.lengthInBytes, - }); - +/// +/// Creates a view over [buffer] spanning [lengthInBytes] bytes starting at +/// [offsetInBytes]. +class const GpuBufferView( /// The buffer this view refers into. - final GpuBuffer buffer; + final GpuBuffer buffer, { /// Byte offset of the view within [buffer]. - final int offsetInBytes; + required final int offsetInBytes, /// Length of the view in bytes. - final int lengthInBytes; -} + required final int lengthInBytes, +}); /// A uniform or sampler slot within a [GpuShader]. /// /// Uniform blocks report a non-null [sizeInBytes] while samplers report `null`. -abstract interface class GpuUniformSlot { +abstract interface class GpuUniformSlot() { /// Size of the uniform block in bytes, or `null` when this slot is a /// sampler. int? get sizeInBytes; @@ -50,22 +45,22 @@ abstract interface class GpuUniformSlot { } /// Handle to a compiled shader stage. -abstract interface class GpuShader { +abstract interface class GpuShader() { /// Looks up the uniform or sampler slot named [slot]. GpuUniformSlot getUniformSlot(String slot); } /// A collection of compiled shaders loaded from a single asset bundle. -abstract interface class GpuShaderLibrary { +abstract interface class GpuShaderLibrary() { /// Retrieves the shader registered under [entryPoint]. GpuShader operator [](String entryPoint); } /// Handle to a compiled render pipeline. -abstract interface class GpuPipeline {} +abstract interface class GpuPipeline(); /// Handle to a render target. -abstract interface class GpuRenderTarget { +abstract interface class GpuRenderTarget() { /// The color attachment's texture, holding the rendered output. GpuTexture get colorTexture; } diff --git a/packages/flame_3d/lib/src/graphics/backend/web_gpu/gpu_backend.dart b/packages/flame_3d/lib/src/graphics/backend/web_gpu/gpu_backend.dart index b64b1b9b9e3..ade866af105 100644 --- a/packages/flame_3d/lib/src/graphics/backend/web_gpu/gpu_backend.dart +++ b/packages/flame_3d/lib/src/graphics/backend/web_gpu/gpu_backend.dart @@ -12,10 +12,12 @@ import 'package:flutter/services.dart'; /// {@template web_gpu_backend} /// A [base.GpuBackend] implemented on browser WebGPU (`navigator.gpu`). /// {@endtemplate} -base class GpuBackend extends base.GpuBackend { - GpuBackend._(this._device, this._bundles) - : _queue = _device.queue, - _defaultSampler = _device.createSampler( +base class GpuBackend._( + final GPUDevice _device, + final Map _bundles, +) extends base.GpuBackend { + this + : _defaultSampler = _device.createSampler( GPUSamplerDescriptor( magFilter: 'nearest', minFilter: 'nearest', @@ -87,11 +89,7 @@ base class GpuBackend extends base.GpuBackend { return bundles; } - final GPUDevice _device; - - final GPUQueue _queue; - - final Map _bundles; + final GPUQueue _queue = _device.queue; late final GPUSampler _defaultSampler; @@ -332,13 +330,10 @@ typedef _PipelineKey = ( CullMode, ); -class _WebGpuShaderLibrary implements GpuShaderLibrary { - const _WebGpuShaderLibrary(this._device, this._bundle); - - final GPUDevice _device; - - final WebShaderBundle _bundle; - +class const _WebGpuShaderLibrary( + final GPUDevice _device, + final WebShaderBundle _bundle, +) implements GpuShaderLibrary { @override GpuShader operator [](String entryPoint) => switch (entryPoint) { 'TextureVertex' => _WebGpuShader(_device, _bundle.vertex, _bundle.slots), @@ -351,15 +346,11 @@ class _WebGpuShaderLibrary implements GpuShaderLibrary { }; } -class _WebGpuShader implements GpuShader { - _WebGpuShader(this._device, this._wgsl, this.slots); - - final GPUDevice _device; - - final String _wgsl; - - final Map slots; - +class _WebGpuShader( + final GPUDevice _device, + final String _wgsl, + final Map slots, +) implements GpuShader { GPUShaderModule? _module; GPUShaderModule get module => _module ??= _device.createShaderModule( @@ -376,11 +367,8 @@ class _WebGpuShader implements GpuShader { } } -class _WebGpuUniformSlot implements GpuUniformSlot { - const _WebGpuUniformSlot(this.slot); - - final WebShaderSlot slot; - +class const _WebGpuUniformSlot(final WebShaderSlot slot) + implements GpuUniformSlot { @override int? get sizeInBytes => slot.sizeInBytes; @@ -388,13 +376,10 @@ class _WebGpuUniformSlot implements GpuUniformSlot { int? getMemberOffsetInBytes(String member) => slot.memberOffsets[member]; } -class _WebGpuPipeline implements GpuPipeline { - const _WebGpuPipeline(this._vertex, this._fragment); - - final _WebGpuShader _vertex; - - final _WebGpuShader _fragment; - +class const _WebGpuPipeline( + final _WebGpuShader _vertex, + final _WebGpuShader _fragment, +) implements GpuPipeline { GPUShaderModule get vertexModule => _vertex.module; GPUShaderModule get fragmentModule => _fragment.module; @@ -402,30 +387,20 @@ class _WebGpuPipeline implements GpuPipeline { Map get slots => _vertex.slots; } -class _WebGpuBuffer implements GpuBuffer { - const _WebGpuBuffer(this._queue, this.raw); - - final GPUQueue _queue; - - final GPUBuffer raw; - +class const _WebGpuBuffer(final GPUQueue _queue, final GPUBuffer raw) + implements GpuBuffer { @override void write(ByteData data, {int destinationOffsetInBytes = 0}) { _queue.writeBuffer(raw, destinationOffsetInBytes, _padded(data)); } } -class _WebGpuSampledTexture implements GpuTexture { - const _WebGpuSampledTexture(this._queue, this.raw, this._width, this._height); - - final GPUQueue _queue; - - final GPUTexture raw; - - final int _width; - - final int _height; - +class const _WebGpuSampledTexture( + final GPUQueue _queue, + final GPUTexture raw, + final int _width, + final int _height, +) implements GpuTexture { @override void write(ByteData data) { _queue.writeTexture( @@ -445,45 +420,32 @@ class _WebGpuSampledTexture implements GpuTexture { throw UnsupportedError('A sampled texture cannot be read as an Image.'); } -class _WebGpuRenderTarget implements GpuRenderTarget { - _WebGpuRenderTarget( - this.canvas, - this.context, - this.depthTexture, - Color clearValue, - ) : clearColor = GPUColor( - r: clearValue.r, - g: clearValue.g, - b: clearValue.b, - a: clearValue.a, - ), - _colorTexture = _WebGpuColorTexture( - canvas, - canvas.width, - canvas.height, - ); - - final OffscreenCanvas canvas; - - final GPUCanvasContext context; - - final GPUTexture depthTexture; - - final GPUColor clearColor; +class _WebGpuRenderTarget( + final OffscreenCanvas canvas, + final GPUCanvasContext context, + final GPUTexture depthTexture, + Color clearValue, +) implements GpuRenderTarget { + final GPUColor clearColor = GPUColor( + r: clearValue.r, + g: clearValue.g, + b: clearValue.b, + a: clearValue.a, + ); - final _WebGpuColorTexture _colorTexture; + final _WebGpuColorTexture _colorTexture = _WebGpuColorTexture( + canvas, + canvas.width, + canvas.height, + ); @override GpuTexture get colorTexture => _colorTexture; } -class _WebGpuColorTexture implements GpuTexture { - _WebGpuColorTexture(this._canvas, int width, int height) - : _blitCanvas = OffscreenCanvas(width, height); - - final OffscreenCanvas _canvas; - - final OffscreenCanvas _blitCanvas; +class _WebGpuColorTexture(final OffscreenCanvas _canvas, int width, int height) + implements GpuTexture { + final OffscreenCanvas _blitCanvas = OffscreenCanvas(width, height); late final CanvasContext2D _blit = _blitCanvas.context2D(); @@ -523,11 +485,7 @@ class _WebGpuColorTexture implements GpuTexture { } } -class _WebGpuFrame implements base.GpuFrame { - _WebGpuFrame(this._backend); - - final GpuBackend _backend; - +class _WebGpuFrame(final GpuBackend _backend) implements base.GpuFrame { final List> _uniformPools = [[], [], []]; int _frameIndex = 0; @@ -614,28 +572,14 @@ class _WebGpuFrame implements base.GpuFrame { } } -class _WebGpuRenderPass implements base.GpuRenderPass { - _WebGpuRenderPass( - this._backend, - this._frame, - this._blend, - this._depthStencil, - this._encoder, - this._pass, - ); - - final GpuBackend _backend; - - final _WebGpuFrame _frame; - - final BlendState _blend; - - final DepthStencilState _depthStencil; - - final GPUCommandEncoder _encoder; - - final GPURenderPassEncoder _pass; - +class _WebGpuRenderPass( + final GpuBackend _backend, + final _WebGpuFrame _frame, + final BlendState _blend, + final DepthStencilState _depthStencil, + final GPUCommandEncoder _encoder, + final GPURenderPassEncoder _pass, +) implements base.GpuRenderPass { late _WebGpuPipeline _pipeline; late GPURenderPipeline _renderPipeline; diff --git a/packages/flame_3d/lib/src/graphics/backend/web_gpu/shader_bundle.dart b/packages/flame_3d/lib/src/graphics/backend/web_gpu/shader_bundle.dart index 41167ffe0ad..662120d5627 100644 --- a/packages/flame_3d/lib/src/graphics/backend/web_gpu/shader_bundle.dart +++ b/packages/flame_3d/lib/src/graphics/backend/web_gpu/shader_bundle.dart @@ -1,12 +1,14 @@ /// A compiled vertex + fragment WGSL pair with its binding reflection. -class WebShaderBundle { - /// Creates a bundle from its [vertex]/[fragment] WGSL and [slots]. - const WebShaderBundle({ - required this.vertex, - required this.fragment, - required this.slots, - }); +class const WebShaderBundle({ + /// The vertex stage WGSL source. + required final String vertex, + + /// The fragment stage WGSL source. + required final String fragment, + /// Binding reflection, keyed by uniform block or texture slot name. + required final Map slots, +}) { /// Decodes a bundle from its `.wgslbundle` JSON representation. factory WebShaderBundle.fromJson(Map json) { return WebShaderBundle( @@ -20,28 +22,25 @@ class WebShaderBundle { }, ); } +} - /// The vertex stage WGSL source. - final String vertex; +/// Reflection for one uniform block or texture slot of a [WebShaderBundle]. +class const WebShaderSlot({ + /// The `@group` the slot is bound to. + required final int group, - /// The fragment stage WGSL source. - final String fragment; + /// The `@binding` the slot is bound to. + required final int binding, - /// Binding reflection, keyed by uniform block or texture slot name. - final Map slots; -} + /// Size of the uniform block in bytes, or `null` for a texture slot. + final int? sizeInBytes, -/// Reflection for one uniform block or texture slot of a [WebShaderBundle]. -class WebShaderSlot { - /// Creates a slot binding at the given [group]/[binding]. - const WebShaderSlot({ - required this.group, - required this.binding, - this.sizeInBytes, - this.samplerBinding, - this.memberOffsets = const {}, - }); + /// The companion sampler's `@binding` for a texture slot, else `null`. + final int? samplerBinding, + /// Byte offset of each member within a uniform block. + final Map memberOffsets = const {}, +}) { /// Decodes a slot from its `.wgslbundle` JSON representation. factory WebShaderSlot.fromJson(Map json) { return WebShaderSlot( @@ -56,19 +55,4 @@ class WebShaderSlot { }, ); } - - /// The `@group` the slot is bound to. - final int group; - - /// The `@binding` the slot is bound to. - final int binding; - - /// Size of the uniform block in bytes, or `null` for a texture slot. - final int? sizeInBytes; - - /// The companion sampler's `@binding` for a texture slot, else `null`. - final int? samplerBinding; - - /// Byte offset of each member within a uniform block. - final Map memberOffsets; } diff --git a/packages/flame_3d/lib/src/graphics/backend/web_gpu/web_gpu_interop.dart b/packages/flame_3d/lib/src/graphics/backend/web_gpu/web_gpu_interop.dart index 84021c03d2e..ea8454bcdfa 100644 --- a/packages/flame_3d/lib/src/graphics/backend/web_gpu/web_gpu_interop.dart +++ b/packages/flame_3d/lib/src/graphics/backend/web_gpu/web_gpu_interop.dart @@ -112,21 +112,21 @@ extension type GPUTexture._(JSObject _) implements JSObject { external void destroy(); } -extension type GPUTextureView._(JSObject _) implements JSObject {} +extension type GPUTextureView._(JSObject _) implements JSObject; -extension type GPUSampler._(JSObject _) implements JSObject {} +extension type GPUSampler._(JSObject _) implements JSObject; -extension type GPUShaderModule._(JSObject _) implements JSObject {} +extension type GPUShaderModule._(JSObject _) implements JSObject; -extension type GPUBindGroupLayout._(JSObject _) implements JSObject {} +extension type GPUBindGroupLayout._(JSObject _) implements JSObject; -extension type GPUBindGroup._(JSObject _) implements JSObject {} +extension type GPUBindGroup._(JSObject _) implements JSObject; extension type GPURenderPipeline._(JSObject _) implements JSObject { external GPUBindGroupLayout getBindGroupLayout(int index); } -extension type GPUCommandBuffer._(JSObject _) implements JSObject {} +extension type GPUCommandBuffer._(JSObject _) implements JSObject; extension type GPUCommandEncoder._(JSObject _) implements JSObject { external GPURenderPassEncoder beginRenderPass( @@ -428,14 +428,14 @@ extension type CanvasContext2D._(JSObject _) implements JSObject { external void drawImage(JSObject image, num dx, num dy); } -abstract final class GPUBufferUsage { +abstract final class GPUBufferUsage() { static const int copyDst = 0x0008; static const int index = 0x0010; static const int vertex = 0x0020; static const int uniform = 0x0040; } -abstract final class GPUTextureUsage { +abstract final class GPUTextureUsage() { static const int copyDst = 0x02; static const int textureBinding = 0x04; static const int renderAttachment = 0x10; diff --git a/packages/flame_3d/lib/src/graphics/graphics_device.dart b/packages/flame_3d/lib/src/graphics/graphics_device.dart index 7f0866e583c..079f62f86f2 100644 --- a/packages/flame_3d/lib/src/graphics/graphics_device.dart +++ b/packages/flame_3d/lib/src/graphics/graphics_device.dart @@ -14,18 +14,13 @@ import 'package:flame_3d/src/graphics/backend/gpu_handles.dart'; /// render passes can be created with [beginPass]/[endPass], each producing an /// [Image]. /// {@endtemplate} -class GraphicsDevice { - /// {@macro graphics_device} - GraphicsDevice({ - this.clearValue = const Color(0x00000000), - GpuBackend? backend, - }) : backend = backend ?? GpuBackend.instance; - - /// The GPU backend this device records its rendering commands through. - final GpuBackend backend; - +class GraphicsDevice({ /// The clear value, used to clear out the screen. - final Color clearValue; + final Color clearValue = const Color(0x00000000), + GpuBackend? backend, +}) { + /// The GPU backend this device records its rendering commands through. + final GpuBackend backend = backend ?? GpuBackend.instance; /// Blend state applied to each render pass. BlendState blendState = BlendState.alphaBlend; @@ -48,7 +43,7 @@ class GraphicsDevice { /// passes. Call [end] when the frame is complete. void begin() { // Reset the pool indices, each existing target becomes available again. - _poolIndex.updateAll((_, __) => 0); + _poolIndex.updateAll((_, _) => 0); _frame = backend.beginFrame(); } diff --git a/packages/flame_3d/lib/src/graphics/joints_info.dart b/packages/flame_3d/lib/src/graphics/joints_info.dart index 346ca98ef94..c339948942e 100644 --- a/packages/flame_3d/lib/src/graphics/joints_info.dart +++ b/packages/flame_3d/lib/src/graphics/joints_info.dart @@ -1,6 +1,6 @@ import 'package:flame_3d/core.dart'; -class JointsInfo { +class JointsInfo() { /// Joints per surface index Map> jointTransformsPerSurface = {}; diff --git a/packages/flame_3d/lib/src/graphics/render_context.dart b/packages/flame_3d/lib/src/graphics/render_context.dart index 96e93bc52a3..bd759013e30 100644 --- a/packages/flame_3d/lib/src/graphics/render_context.dart +++ b/packages/flame_3d/lib/src/graphics/render_context.dart @@ -1,7 +1,3 @@ import 'package:flame_3d/graphics.dart'; -abstract class RenderContext { - const RenderContext(this.device); - - final GraphicsDevice device; -} +abstract class const RenderContext(final GraphicsDevice device); diff --git a/packages/flame_3d/lib/src/graphics/render_context_3d.dart b/packages/flame_3d/lib/src/graphics/render_context_3d.dart index e36c759a1c2..0db5e81862e 100644 --- a/packages/flame_3d/lib/src/graphics/render_context_3d.dart +++ b/packages/flame_3d/lib/src/graphics/render_context_3d.dart @@ -4,9 +4,7 @@ import 'package:flame_3d/graphics.dart'; import 'package:flame_3d/resources.dart'; import 'package:flame_3d/src/graphics/joints_info.dart'; -class RenderContext3D extends RenderContext { - RenderContext3D(super.device); - +class RenderContext3D(super.device) extends RenderContext { Matrix4 get model => _modelMatrix; final Matrix4 _modelMatrix = Matrix4.zero(); @@ -99,7 +97,7 @@ class RenderContext3D extends RenderContext { } } -class _DrawEntry { +class _DrawEntry() { double distance = 0; Object3D? object; } diff --git a/packages/flame_3d/lib/src/model/animation_state.dart b/packages/flame_3d/lib/src/model/animation_state.dart index 731e868f260..14623e70bca 100644 --- a/packages/flame_3d/lib/src/model/animation_state.dart +++ b/packages/flame_3d/lib/src/model/animation_state.dart @@ -3,7 +3,7 @@ import 'package:flame_3d/src/model/model_animation.dart'; /// Couples an immutable [ModelAnimation] (animation data) with a clock, which /// allows it to be ticked by the game loop and sampled for rendering. -class AnimationState { +class AnimationState() { ModelAnimation? animationRef; double clock = 0.0; diff --git a/packages/flame_3d/lib/src/model/model_animation.dart b/packages/flame_3d/lib/src/model/model_animation.dart index 3294b058b1c..da413c112c0 100644 --- a/packages/flame_3d/lib/src/model/model_animation.dart +++ b/packages/flame_3d/lib/src/model/model_animation.dart @@ -1,9 +1,5 @@ import 'dart:math'; -// TODO(spydon): Remove this import once Flutter 3.35.0 is the minimum version. -// ignore: unnecessary_import -import 'package:flame/extensions.dart'; -// ignore: unnecessary_import import 'package:flame_3d/core.dart'; import 'package:flame_3d/model.dart'; import 'package:flame_3d/src/parser/gltf/animation_interpolation.dart'; @@ -39,12 +35,12 @@ abstract class AnimationSpline { } /// An animation spline over the position of a transformation (translation). -class TranslationAnimationSpline extends AnimationSpline { - TranslationAnimationSpline.from({ - required super.interpolation, - required super.times, - required super.values, - }) : super.from(); +class TranslationAnimationSpline.from({ + required super.interpolation, + required super.times, + required super.values, +}) extends AnimationSpline { + this : super.from(); @override Vector3 lerp(Vector3 a, Vector3 b, double t) { @@ -58,12 +54,12 @@ class TranslationAnimationSpline extends AnimationSpline { } /// An animation spline over the angle of a transformation (rotation). -class RotationAnimationSpline extends AnimationSpline { - RotationAnimationSpline.from({ - required super.interpolation, - required super.times, - required super.values, - }) : super.from(); +class RotationAnimationSpline.from({ + required super.interpolation, + required super.times, + required super.values, +}) extends AnimationSpline { + this : super.from(); @override Quaternion lerp(Quaternion a, Quaternion b, double t) { @@ -77,12 +73,12 @@ class RotationAnimationSpline extends AnimationSpline { } /// An animation spline over the scale of a transformation (scaling). -class ScaleAnimationSpline extends AnimationSpline { - ScaleAnimationSpline.from({ - required super.interpolation, - required super.times, - required super.values, - }) : super.from(); +class ScaleAnimationSpline.from({ + required super.interpolation, + required super.times, + required super.values, +}) extends AnimationSpline { + this : super.from(); @override Vector3 lerp(Vector3 a, Vector3 b, double t) { @@ -96,13 +92,10 @@ class ScaleAnimationSpline extends AnimationSpline { } /// Allows sampling of an animation by interpolating keyframes. -class AnimationController { - final AnimationSpline animation; - final double lastTime; - - AnimationController({ - required this.animation, - }) : lastTime = animation.values.last.time; +class AnimationController({ + required final AnimationSpline animation, +}) { + final double lastTime = animation.values.last.time; T sample(double time) { final values = animation.values; @@ -138,13 +131,10 @@ class AnimationController { /// Groups the animations of a single node in a [Model], which can be /// controlled by multiple animation channels. -class NodeAnimation { - final List channels; - final double lastTime; - - NodeAnimation({ - required this.channels, - }) : lastTime = channels.map((e) => e.lastTime).reduce(max); +class NodeAnimation({ + required final List channels, +}) { + final double lastTime = channels.map((e) => e.lastTime).reduce(max); void sampleInto(double time, Matrix4 matrix) { for (final channel in channels) { @@ -154,13 +144,9 @@ class NodeAnimation { } /// Groups the animations for all nodes of a [Model]. -class ModelAnimation { - final String? name; - final Map nodes; - final double lastTime; - - ModelAnimation({ - required this.name, - required this.nodes, - }) : lastTime = nodes.values.map((e) => e.lastTime).reduce(max); +class ModelAnimation({ + required final String? name, + required final Map nodes, +}) { + final double lastTime = nodes.values.map((e) => e.lastTime).reduce(max); } diff --git a/packages/flame_3d/lib/src/model/model_component.dart b/packages/flame_3d/lib/src/model/model_component.dart index 3acd15e2c45..9ebeb709161 100644 --- a/packages/flame_3d/lib/src/model/model_component.dart +++ b/packages/flame_3d/lib/src/model/model_component.dart @@ -7,20 +7,16 @@ import 'package:flame_3d/src/model/model.dart'; /// A component wrapper over a 3D [Model], using the [AnimationState] to keep /// track and manage its animations. -class ModelComponent extends Object3D { - final Model model; - +class ModelComponent({ + required final Model model, + super.position, + super.rotation, + super.scale, + super.children, +}) extends Object3D { final Set _hiddenNodes = {}; final AnimationState _animation = AnimationState(); - ModelComponent({ - required this.model, - super.position, - super.rotation, - super.scale, - super.children, - }); - @override Aabb3? computeLocalAabb() => model.aabb; diff --git a/packages/flame_3d/lib/src/model/model_node.dart b/packages/flame_3d/lib/src/model/model_node.dart index 69c8dcd9188..157e8997a1a 100644 --- a/packages/flame_3d/lib/src/model/model_node.dart +++ b/packages/flame_3d/lib/src/model/model_node.dart @@ -99,28 +99,18 @@ class ModelNode { } /// A single join inside a [ModelNode]. -class ModelJoint { - final int nodeIndex; - final Matrix4 inverseBindMatrix; - - ModelJoint({ - required this.nodeIndex, - required this.inverseBindMatrix, - }); -} +class ModelJoint({ + required final int nodeIndex, + required final Matrix4 inverseBindMatrix, +}); /// A post-processed node including the final transforms after animations are /// applied. -class ProcessedNode { - final ModelNode node; - final Matrix4 combinedTransform; +class ProcessedNode({ + required final ModelNode node, + required final Matrix4 combinedTransform, + required final Map> jointTransforms, +}) { // for each surface within the node's mesh, a list of up to 4 joint transforms // with localized indexes according to the surface's localJoints - final Map> jointTransforms; - - ProcessedNode({ - required this.node, - required this.combinedTransform, - required this.jointTransforms, - }); } diff --git a/packages/flame_3d/lib/src/parser/glb_parser.dart b/packages/flame_3d/lib/src/parser/glb_parser.dart index cb397cb081b..23809d46bd7 100644 --- a/packages/flame_3d/lib/src/parser/glb_parser.dart +++ b/packages/flame_3d/lib/src/parser/glb_parser.dart @@ -10,7 +10,7 @@ import 'package:flame_3d/src/parser/model_parser.dart'; /// Parses GLB and GLTF file formats as per specified by: /// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.pdf -class GlbParser extends ModelParser { +class GlbParser() extends ModelParser { @override Future parseModel(String filePath) async { final root = await parseRoot(filePath); @@ -19,7 +19,7 @@ class GlbParser extends ModelParser { Future parseRoot(String filePath) async { final glb = await parseGlb(filePath); - return glb.parse(); + return await glb.parse(); } Future parseGlb(String filePath) async { @@ -67,19 +67,12 @@ class GlbParser extends ModelParser { } } -class Glb { - final String prefix; - final int version; - final int length; - final List chunks; - - Glb({ - required this.prefix, - required this.version, - required this.length, - required this.chunks, - }); - +class Glb({ + required final String prefix, + required final int version, + required final int length, + required final List chunks, +}) { Map jsonChunk() { final chunk = chunks.firstWhere((GlbChunk chunk) => chunk.type == 'JSON'); return jsonDecode(_parseString(chunk.data)) as Map; @@ -92,7 +85,7 @@ class Glb { Future parse() async { final json = jsonChunk(); final chunks = binaryChunks().toList(); - return GltfRoot.from( + return await GltfRoot.from( prefix: prefix, json: json, chunks: chunks, diff --git a/packages/flame_3d/lib/src/parser/gltf/accessor.dart b/packages/flame_3d/lib/src/parser/gltf/accessor.dart index 0d04718b131..6eb27cac372 100644 --- a/packages/flame_3d/lib/src/parser/gltf/accessor.dart +++ b/packages/flame_3d/lib/src/parser/gltf/accessor.dart @@ -9,22 +9,24 @@ import 'package:flame_3d/src/parser/gltf/sparse_accessor.dart'; /// A untyped GLTF accessor; it is typically wrapped into a specific accessor /// type on the data model. This provides the backing implementation. -class RawAccessor extends GltfNode { +class RawAccessor({ + required super.root, + /// The reference to the buffer view. /// When undefined, the accessor **MUST** be initialized with zeros; `sparse` /// property or extensions **MAY** override zeros with actual values. - final GltfRef bufferView; + required final GltfRef bufferView, /// The offset relative to the start of the buffer view in bytes. /// /// This **MUST** be a multiple of the size of the component datatype. /// This property **MUST NOT** be defined when `bufferView` is undefined. - final int byteOffset; + required final int byteOffset, /// The datatype of the accessor's components. /// UNSIGNED_INT type **MUST NOT** be used for any accessor that is not /// referenced by `mesh.primitive.indices`. - final ComponentType componentType; + required final ComponentType componentType, /// Specifies whether integer data values are normalized (`true`) to [0, 1] /// (for unsigned types) or to [-1, 1] (for signed types) when they are @@ -32,15 +34,15 @@ class RawAccessor extends GltfNode { /// /// This property **MUST NOT** be set to `true` for accessors with `FLOAT` or /// `UNSIGNED_INT` component type. - final bool normalized; + required final bool normalized, /// The number of elements referenced by this accessor, not to be confused /// with the number of bytes or number of components. - final int count; + required final int count, /// Specifies if the accessor's elements are scalars, vectors, or matrices. /// This should match the type used for a [TypedAccessor]. - final AccessorType type; + required final AccessorType type, /// Maximum value of each component in this accessor. /// Array elements **MUST** be treated as having the same data type as @@ -56,7 +58,7 @@ class RawAccessor extends GltfNode { /// /// When the accessor is sparse, this property **MUST** contain maximum /// values of accessor data with sparse substitution applied. - final List? max; + required final List? max, /// Minimum value of each component in this accessor. /// @@ -73,11 +75,11 @@ class RawAccessor extends GltfNode { /// /// When the accessor is sparse, this property **MUST** contain minimum /// values of accessor data with sparse substitution applied. - final List? min; + required final List? min, /// Sparse storage of elements that deviate from their initialization value. - final SparseAccessor? sparse; - + required final SparseAccessor? sparse, +}) extends GltfNode { Iterable data() sync* { final buffer = bufferView.get(); final bytes = buffer.data(); @@ -158,19 +160,6 @@ class RawAccessor extends GltfNode { ); Matrix4Accessor asMatrix4() => Matrix4Accessor(root: root, accessor: this); - RawAccessor({ - required super.root, - required this.bufferView, - required this.byteOffset, - required this.componentType, - required this.normalized, - required this.count, - required this.type, - required this.max, - required this.min, - required this.sparse, - }); - RawAccessor.parse( GltfRoot root, Map map, @@ -188,13 +177,11 @@ class RawAccessor extends GltfNode { ); } -abstract class TypedAccessor extends GltfNode { - final RawAccessor rawAccessor; - - TypedAccessor({ - required super.root, - required RawAccessor accessor, - }) : rawAccessor = accessor; +abstract class TypedAccessor({ + required super.root, + required RawAccessor accessor, +}) extends GltfNode { + final RawAccessor rawAccessor = accessor; List typedData(); @@ -206,12 +193,10 @@ abstract class TypedAccessor extends GltfNode { } } -class IntAccessor extends TypedAccessor { - IntAccessor({ - required super.root, - required super.accessor, - }); - +class IntAccessor({ + required super.root, + required super.accessor, +}) extends TypedAccessor { @override List typedData() { _checkAccessorType(AccessorType.scalar); @@ -219,12 +204,10 @@ class IntAccessor extends TypedAccessor { } } -class FloatAccessor extends TypedAccessor { - FloatAccessor({ - required super.root, - required super.accessor, - }); - +class FloatAccessor({ + required super.root, + required super.accessor, +}) extends TypedAccessor { @override List typedData() { _checkAccessorType(AccessorType.scalar); @@ -232,12 +215,10 @@ class FloatAccessor extends TypedAccessor { } } -class Vector2Accessor extends TypedAccessor { - Vector2Accessor({ - required super.root, - required super.accessor, - }); - +class Vector2Accessor({ + required super.root, + required super.accessor, +}) extends TypedAccessor { @override List typedData() { _checkAccessorType(AccessorType.vec2); @@ -248,12 +229,10 @@ class Vector2Accessor extends TypedAccessor { } } -class Vector3Accessor extends TypedAccessor { - Vector3Accessor({ - required super.root, - required super.accessor, - }); - +class Vector3Accessor({ + required super.root, + required super.accessor, +}) extends TypedAccessor { @override List typedData() { _checkAccessorType(AccessorType.vec3); @@ -264,12 +243,10 @@ class Vector3Accessor extends TypedAccessor { } } -class Vector4Accessor extends TypedAccessor { - Vector4Accessor({ - required super.root, - required super.accessor, - }); - +class Vector4Accessor({ + required super.root, + required super.accessor, +}) extends TypedAccessor { @override List typedData() { _checkAccessorType(AccessorType.vec4); @@ -280,12 +257,10 @@ class Vector4Accessor extends TypedAccessor { } } -class QuaternionAccessor extends TypedAccessor { - QuaternionAccessor({ - required super.root, - required super.accessor, - }); - +class QuaternionAccessor({ + required super.root, + required super.accessor, +}) extends TypedAccessor { @override List typedData() { _checkAccessorType(AccessorType.vec4); @@ -296,12 +271,10 @@ class QuaternionAccessor extends TypedAccessor { } } -class Matrix4Accessor extends TypedAccessor { - Matrix4Accessor({ - required super.root, - required super.accessor, - }); - +class Matrix4Accessor({ + required super.root, + required super.accessor, +}) extends TypedAccessor { @override List typedData() { _checkAccessorType(AccessorType.mat4); diff --git a/packages/flame_3d/lib/src/parser/gltf/accessor_type.dart b/packages/flame_3d/lib/src/parser/gltf/accessor_type.dart index 887fbdb6430..41e8f2c6972 100644 --- a/packages/flame_3d/lib/src/parser/gltf/accessor_type.dart +++ b/packages/flame_3d/lib/src/parser/gltf/accessor_type.dart @@ -1,7 +1,7 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Specifies if the accessor's elements are scalars, vectors, or matrices. -enum AccessorType { +enum AccessorType(final String name, final int size) { scalar('SCALAR', 1), vec2('VEC2', 2), vec3('VEC3', 3), @@ -10,11 +10,6 @@ enum AccessorType { mat3('MAT3', 9), mat4('MAT4', 16); - final String name; - final int size; - - const AccessorType(this.name, this.size); - static AccessorType valueOf(String name) { return values.firstWhere((e) => e.name == name); } diff --git a/packages/flame_3d/lib/src/parser/gltf/alpha_mode.dart b/packages/flame_3d/lib/src/parser/gltf/alpha_mode.dart index 7d82cb46755..546e20ccc72 100644 --- a/packages/flame_3d/lib/src/parser/gltf/alpha_mode.dart +++ b/packages/flame_3d/lib/src/parser/gltf/alpha_mode.dart @@ -2,7 +2,7 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// The material's alpha rendering mode enumeration specifying the /// interpretation of the alpha value of the base color. -enum AlphaMode { +enum AlphaMode(final String value) { /// The alpha value is ignored, and the rendered output is fully opaque. opaque('OPAQUE'), @@ -17,10 +17,6 @@ enum AlphaMode { /// painting operation (i.e. the Porter and Duff over operator). blend('BLEND'); - final String value; - - const AlphaMode(this.value); - static AlphaMode valueOf(String value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/animation.dart b/packages/flame_3d/lib/src/parser/gltf/animation.dart index 79a60423a4d..eb78d1d44c2 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation.dart @@ -6,28 +6,22 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// A keyframe animation. -class Animation extends GltfNode { - final String? name; +class Animation({ + required super.root, + required final String? name, /// An array of animation channels. /// An animation channel combines an animation sampler with a target property /// being animated. /// Different channels of the same animation **MUST NOT** have the same /// targets. - final List channels; + required final List channels, /// An array of animation samplers. /// An animation sampler combines timestamps with a sequence of output values /// and defines an interpolation algorithm. - final List samplers; - - Animation({ - required super.root, - required this.name, - required this.channels, - required this.samplers, - }); - + required final List samplers, +}) extends GltfNode { Animation.parse( GltfRoot root, Map map, @@ -57,26 +51,24 @@ class Animation extends GltfNode { final times = sampler.input.get().typedData(); final values = sampler.output.get(); - final spline = - switch (path) { - AnimationPath.translation => TranslationAnimationSpline.from( - interpolation: sampler.interpolation, - times: times, - values: values.asVector3().typedData(), - ), - AnimationPath.scale => ScaleAnimationSpline.from( - interpolation: sampler.interpolation, - times: times, - values: values.asVector3().typedData(), - ), - AnimationPath.rotation => RotationAnimationSpline.from( - interpolation: sampler.interpolation, - times: times, - values: values.asQuaternion().typedData(), - ), - AnimationPath.weights => throw UnimplementedError(), - } - as AnimationSpline; + final spline = switch (path) { + AnimationPath.translation => TranslationAnimationSpline.from( + interpolation: sampler.interpolation, + times: times, + values: values.asVector3().typedData(), + ), + AnimationPath.scale => ScaleAnimationSpline.from( + interpolation: sampler.interpolation, + times: times, + values: values.asVector3().typedData(), + ), + AnimationPath.rotation => RotationAnimationSpline.from( + interpolation: sampler.interpolation, + times: times, + values: values.asQuaternion().typedData(), + ), + AnimationPath.weights => throw UnimplementedError(), + } as AnimationSpline; final nodeIndex = channel.target.node.index; (controllers[nodeIndex] ??= []).add( diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart b/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart index 6443abbd337..89302ccc323 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart @@ -2,20 +2,16 @@ import 'package:flame_3d/src/parser/gltf/animation_target.dart'; import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; -class AnimationChannel extends GltfNode { +class AnimationChannel({ + required super.root, + /// The ID of a sampler in this animation used to compute the value for the /// target, e.g., a node's translation, rotation, or scale (TRS). - final int sampler; + required final int sampler, /// The descriptor of the animated property. - final AnimationTarget target; - - AnimationChannel({ - required super.root, - required this.sampler, - required this.target, - }); - + required final AnimationTarget target, +}) extends GltfNode { AnimationChannel.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_interpolation.dart b/packages/flame_3d/lib/src/parser/gltf/animation_interpolation.dart index 18bd764cdff..c389198db84 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_interpolation.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_interpolation.dart @@ -2,7 +2,7 @@ import 'package:flame_3d/core.dart'; import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Interpolation algorithm. -enum AnimationInterpolation { +enum AnimationInterpolation(final String value) { /// The animated values are linearly interpolated between keyframes. /// When targeting a rotation, spherical linear interpolation (slerp) /// **SHOULD** be used to interpolate quaternions. @@ -23,10 +23,6 @@ enum AnimationInterpolation { /// There **MUST** be at least two keyframes when using this interpolation. cubicSpline('CUBICSPLINE'); // cSpell:ignore CUBICSPLINE - final String value; - - const AnimationInterpolation(this.value); - static AnimationInterpolation valueOf(String value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_path.dart b/packages/flame_3d/lib/src/parser/gltf/animation_path.dart index 1f5f6590f3d..3acf53da6dc 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_path.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_path.dart @@ -1,16 +1,12 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// The name of the node's TRS property to modify. -enum AnimationPath { +enum AnimationPath(final String value) { translation('translation'), rotation('rotation'), scale('scale'), weights('weights'); - final String value; - - const AnimationPath(this.value); - static AnimationPath valueOf(String value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart b/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart index 170dad257db..8fa197b9240 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart @@ -6,26 +6,21 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// An animation sampler combines timestamps with a sequence of output values /// and defines an interpolation algorithm. -class AnimationSampler extends GltfNode { +class AnimationSampler({ + required super.root, + /// The index of an accessor containing keyframe timestamps. /// The accessor **MUST** be of scalar type with floating-point components. /// The values represent time in seconds with `time[0] >= 0.0`, and strictly /// increasing values, i.e., `time[n + 1] > time[n]`. - final GltfRef input; + required final GltfRef input, /// Interpolation algorithm. - final AnimationInterpolation interpolation; + required final AnimationInterpolation interpolation, /// The index of an accessor, containing keyframe output values. - final GltfRef output; - - AnimationSampler({ - required super.root, - required this.input, - required this.interpolation, - required this.output, - }); - + required final GltfRef output, +}) extends GltfNode { AnimationSampler.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_target.dart b/packages/flame_3d/lib/src/parser/gltf/animation_target.dart index feb8fb08062..9a5a1e0bc6e 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_target.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_target.dart @@ -5,10 +5,12 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; import 'package:flame_3d/src/parser/gltf/node.dart'; /// The descriptor of the animated property. -class AnimationTarget extends GltfNode { +class AnimationTarget({ + required super.root, + /// The reference to the node to animate. When undefined, the animated object /// **MAY** be defined by an extension. - final GltfRef node; + required final GltfRef node, /// The name of the node's TRS property to animate, or the `weights` of the /// Morph Targets it instantiates. @@ -18,14 +20,8 @@ class AnimationTarget extends GltfNode { /// (x, y, z, w), where w is the scalar. /// For the `scale` property, the values are the scaling factors along the /// X, Y, and Z axes. - final AnimationPath path; - - AnimationTarget({ - required super.root, - required this.node, - required this.path, - }); - + required final AnimationPath path, +}) extends GltfNode { AnimationTarget.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/buffer.dart b/packages/flame_3d/lib/src/parser/gltf/buffer.dart index 1e25ab568fb..f7aa000f5e5 100644 --- a/packages/flame_3d/lib/src/parser/gltf/buffer.dart +++ b/packages/flame_3d/lib/src/parser/gltf/buffer.dart @@ -2,19 +2,15 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// A buffer points to binary geometry, animation, or skins. -class Buffer extends GltfNode { +class Buffer({ + required super.root, + /// The length of the buffer in bytes. - final int byteLength; + required final int byteLength, /// The URI of the buffer. - final String? uri; - - Buffer({ - required super.root, - required this.byteLength, - required this.uri, - }); - + required final String? uri, +}) extends GltfNode { Buffer.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart b/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart index 2110d0f0d9c..d9fe441bc11 100644 --- a/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart +++ b/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart @@ -8,36 +8,29 @@ import 'package:flame_3d/src/parser/gltf/gltf_ref.dart'; import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// A view into a buffer generally representing a subset of the buffer. -class BufferView extends GltfNode with GltfNodeWithData { +class BufferView({ + required super.root, + /// The reference to the buffer. - final GltfRef buffer; + required final GltfRef buffer, /// The length of the bufferView in bytes. - final int byteLength; + required final int byteLength, /// The offset into the buffer in bytes. - final int byteOffset; + required final int byteOffset, /// The stride, in bytes, between vertex attributes. /// /// When this is not defined, data is tightly packed. /// When two or more accessors use the same buffer view, this field **MUST** /// be defined. - final int? byteStride; + required final int? byteStride, /// The hint representing the intended GPU buffer type to use with this /// buffer view. - final BufferViewTarget? target; - - BufferView({ - required super.root, - required this.buffer, - required this.byteLength, - required this.byteOffset, - required this.byteStride, - required this.target, - }); - + required final BufferViewTarget? target, +}) extends GltfNode with GltfNodeWithData { BufferView.parse( GltfRoot root, Map map, @@ -52,7 +45,7 @@ class BufferView extends GltfNode with GltfNodeWithData { @override Future loadData() async { - return root.readChunk(buffer); + return await root.readChunk(buffer); } Uint8List data() { diff --git a/packages/flame_3d/lib/src/parser/gltf/buffer_view_target.dart b/packages/flame_3d/lib/src/parser/gltf/buffer_view_target.dart index 6e4cf8a4f2c..d98df68f5b8 100644 --- a/packages/flame_3d/lib/src/parser/gltf/buffer_view_target.dart +++ b/packages/flame_3d/lib/src/parser/gltf/buffer_view_target.dart @@ -1,14 +1,10 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// The target that the WebGL buffer should be bound to. -enum BufferViewTarget { +enum BufferViewTarget(final int value) { arrayBuffer(34962), elementArrayBuffer(34963); - final int value; - - const BufferViewTarget(this.value); - static BufferViewTarget valueOf(int value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/camera.dart b/packages/flame_3d/lib/src/parser/gltf/camera.dart index c79b312889a..1e247a25e3c 100644 --- a/packages/flame_3d/lib/src/parser/gltf/camera.dart +++ b/packages/flame_3d/lib/src/parser/gltf/camera.dart @@ -8,29 +8,24 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// /// A node **MAY** reference a camera to apply a transform to place the camera /// in the scene. -class Camera extends GltfNode { +class Camera({ + required super.root, + /// Specifies if the camera uses a perspective or orthographic projection. /// Based on this, either the camera's `perspective` or `orthographic` /// property **MUST** be defined. - final CameraType type; + required final CameraType type, /// An orthographic camera containing properties to create an orthographic /// projection matrix. /// This property **MUST NOT** be defined when `perspective` is defined. - final CameraOrthographic? orthographic; + required final CameraOrthographic? orthographic, /// A perspective camera containing properties to create a perspective /// projection matrix. /// This property **MUST NOT** be defined when `orthographic` is defined. - final CameraPerspective? perspective; - - Camera({ - required super.root, - required this.type, - required this.orthographic, - required this.perspective, - }); - + required final CameraPerspective? perspective, +}) extends GltfNode { Camera.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart b/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart index 2da34c4f644..f0017964658 100644 --- a/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart +++ b/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart @@ -3,33 +3,27 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// An orthographic camera containing properties to create an orthographic /// projection matrix. -class CameraOrthographic extends GltfNode { +class CameraOrthographic({ + required super.root, + /// The floating-point horizontal magnification of the view. /// This value **MUST NOT** be equal to zero. /// This value **SHOULD NOT** be negative. - final double xMag; + required final double xMag, /// The floating-point vertical magnification of the view. /// This value **MUST NOT** be equal to zero. /// This value **SHOULD NOT** be negative. - final double yMag; + required final double yMag, /// The floating-point distance to the far clipping plane. /// This value **MUST NOT** be equal to zero. /// `zFar` **MUST** be greater than `zNear`. - final double xFar; + required final double xFar, /// The floating-point distance to the near clipping plane. - final double zNear; - - CameraOrthographic({ - required super.root, - required this.xMag, - required this.yMag, - required this.xFar, - required this.zNear, - }); - + required final double zNear, +}) extends GltfNode { CameraOrthographic.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart b/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart index faba0100c29..b7872b665c7 100644 --- a/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart +++ b/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart @@ -3,33 +3,27 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// A perspective camera containing properties to create a perspective /// projection matrix. -class CameraPerspective extends GltfNode { +class CameraPerspective({ + required super.root, + /// The floating-point aspect ratio of the field of view. /// When undefined, the aspect ratio of the rendering viewport **MUST** be /// used. - final double? aspectRatio; + required final double? aspectRatio, /// The floating-point vertical field of view in radians. /// This value **SHOULD** be less than π. - final double yFov; + required final double yFov, /// The floating-point distance to the far clipping plane. /// When defined, `zFar` **MUST** be greater than `zNear`. /// If `zFar` is undefined, client implementations **SHOULD** use /// infinite projection matrix. - final double? zFar; + required final double? zFar, /// The floating-point distance to the near clipping plane. - final double zNear; - - CameraPerspective({ - required super.root, - required this.aspectRatio, - required this.yFov, - required this.zFar, - required this.zNear, - }); - + required final double zNear, +}) extends GltfNode { CameraPerspective.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/camera_type.dart b/packages/flame_3d/lib/src/parser/gltf/camera_type.dart index c6c2821d264..622841479cf 100644 --- a/packages/flame_3d/lib/src/parser/gltf/camera_type.dart +++ b/packages/flame_3d/lib/src/parser/gltf/camera_type.dart @@ -1,7 +1,7 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Specifies if the camera uses a perspective or orthographic projection. -enum CameraType { +enum CameraType() { perspective, orthographic; diff --git a/packages/flame_3d/lib/src/parser/gltf/component_type.dart b/packages/flame_3d/lib/src/parser/gltf/component_type.dart index 4e0b3f985ca..da73335cff1 100644 --- a/packages/flame_3d/lib/src/parser/gltf/component_type.dart +++ b/packages/flame_3d/lib/src/parser/gltf/component_type.dart @@ -3,7 +3,10 @@ import 'dart:typed_data'; import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// The datatype of the accessor's components. -enum ComponentType { +enum ComponentType({ + required final int value, + required final int byteSize, +}) { byte(value: 5120, byteSize: 1), unsignedByte(value: 5121, byteSize: 1), short(value: 5122, byteSize: 2), @@ -11,14 +14,6 @@ enum ComponentType { unsignedInt(value: 5125, byteSize: 4), float(value: 5126, byteSize: 4); - final int value; - final int byteSize; - - const ComponentType({ - required this.value, - required this.byteSize, - }); - num parseData(ByteData byteData, {int cursor = 0}) { return switch (this) { ComponentType.byte => byteData.getInt8(cursor), diff --git a/packages/flame_3d/lib/src/parser/gltf/glb_chunk.dart b/packages/flame_3d/lib/src/parser/gltf/glb_chunk.dart index 6f1ea406e05..782f96b0496 100644 --- a/packages/flame_3d/lib/src/parser/gltf/glb_chunk.dart +++ b/packages/flame_3d/lib/src/parser/gltf/glb_chunk.dart @@ -1,14 +1,8 @@ import 'dart:typed_data'; /// Each data chunk in a GLB file. -class GlbChunk { - final int length; - final String type; - final Uint8List data; - - GlbChunk({ - required this.length, - required this.type, - required this.data, - }); -} +class GlbChunk({ + required final int length, + required final String type, + required final Uint8List data, +}); diff --git a/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart b/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart index 5d387599bf2..4634638b05b 100644 --- a/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart +++ b/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart @@ -5,19 +5,13 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// A base class for all data classes representing the GLTF schema. /// It holds a reference to the [GltfRoot] that contains it, which allows /// for [GltfRef]s to be resolved. -abstract class GltfNode { - final GltfRoot root; - - GltfNode({ - required this.root, - }); -} +abstract class GltfNode({ + required final GltfRoot root, +}); /// A helper utility class to group different methods for parsing GLTF data /// into data classes. -class Parser { - Parser._(); - +class Parser._() { static GltfRef? ref( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/gltf_ref.dart b/packages/flame_3d/lib/src/parser/gltf/gltf_ref.dart index 7fd233811a9..56473cf0421 100644 --- a/packages/flame_3d/lib/src/parser/gltf/gltf_ref.dart +++ b/packages/flame_3d/lib/src/parser/gltf/gltf_ref.dart @@ -2,14 +2,10 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// A wrapper over an index reference within the GLTF spec, allowing the data /// structure to be navigated with ease. -class GltfRef extends GltfNode { - final int index; - - GltfRef({ - required super.root, - required this.index, - }); - +class GltfRef({ + required super.root, + required final int index, +}) extends GltfNode { T get() { return root.resolve(index); } diff --git a/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart b/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart index 45bf19ffc42..05ffa12fb5a 100644 --- a/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart +++ b/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart @@ -22,10 +22,10 @@ import 'package:flame_3d/src/parser/gltf/skin.dart'; import 'package:flame_3d/src/parser/gltf/texture.dart'; /// The root schema of a GLTF file. -class GltfRoot { +class GltfRoot._({ /// Path prefix used to resolve relative paths. - final String _prefix; - + required final String _prefix, +}) { late final List buffers; late final List bufferViews; late final List accessors; @@ -45,17 +45,13 @@ class GltfRoot { late final List chunks; - GltfRoot._({ - required this._prefix, - }); - Future readChunk(GltfRef ref) async { if (chunks.isNotEmpty) { final chunk = chunks[ref.index]; return chunk.data; } final buffer = ref.get(); - return readChunkFrom(buffer.uri!); + return await readChunkFrom(buffer.uri!); } Future readChunkFrom(String uri) async { @@ -72,35 +68,34 @@ class GltfRoot { throw Exception('Unsupported data URI: $uri'); } else { final path = '$_prefix/$uri'; - return Flame.assets.readBinaryFile(path); + return await Flame.assets.readBinaryFile(path); } } T resolve(int index) { return switch (T) { - const (Scene) => scenes[index], - const (Node) => nodes[index], - const (Mesh) => meshes[index], - const (Material) => materials[index], - const (Camera) => cameras[index], - const (Skin) => skins[index], - const (BufferView) => bufferViews[index], - const (Buffer) => buffers[index], - const (Texture) => textures[index], - const (Animation) => animations[index], - const (Sampler) => samplers[index], - const (Image) => images[index], - const (IntAccessor) => accessors[index].asInt(), - const (FloatAccessor) => accessors[index].asFloat(), - const (Vector2Accessor) => accessors[index].asVector2(), - const (Vector3Accessor) => accessors[index].asVector3(), - const (Vector4Accessor) => accessors[index].asVector4(), - const (QuaternionAccessor) => accessors[index].asQuaternion(), - const (Matrix4Accessor) => accessors[index].asMatrix4(), - const (RawAccessor) => accessors[index], - _ => throw UnimplementedError('Cannot resolve type $T'), - } - as T; + const (Scene) => scenes[index], + const (Node) => nodes[index], + const (Mesh) => meshes[index], + const (Material) => materials[index], + const (Camera) => cameras[index], + const (Skin) => skins[index], + const (BufferView) => bufferViews[index], + const (Buffer) => buffers[index], + const (Texture) => textures[index], + const (Animation) => animations[index], + const (Sampler) => samplers[index], + const (Image) => images[index], + const (IntAccessor) => accessors[index].asInt(), + const (FloatAccessor) => accessors[index].asFloat(), + const (Vector2Accessor) => accessors[index].asVector2(), + const (Vector3Accessor) => accessors[index].asVector3(), + const (Vector4Accessor) => accessors[index].asVector4(), + const (QuaternionAccessor) => accessors[index].asQuaternion(), + const (Matrix4Accessor) => accessors[index].asMatrix4(), + const (RawAccessor) => accessors[index], + _ => throw UnimplementedError('Cannot resolve type $T'), + } as T; } static Future from({ diff --git a/packages/flame_3d/lib/src/parser/gltf/image.dart b/packages/flame_3d/lib/src/parser/gltf/image.dart index 662e5b8c47c..c4b0559528a 100644 --- a/packages/flame_3d/lib/src/parser/gltf/image.dart +++ b/packages/flame_3d/lib/src/parser/gltf/image.dart @@ -10,31 +10,26 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; import 'package:flame_3d/src/parser/gltf/mime_type.dart'; /// Image data used to create a texture. -class Image extends GltfNode with GltfNodeWithData { +class Image({ + required super.root, + /// The URI (or IRI) of the image. /// /// Relative paths are relative to the current glTF asset. /// Instead of referencing an external file, this field **MAY** contain a /// `data:`-URI. /// This field **MUST NOT** be defined when `bufferView` is defined. - final String? uri; + required final String? uri, /// The image's media type. /// /// This field **MUST** be defined when `bufferView` is defined. - final MimeType? mimeType; + required final MimeType? mimeType, /// The reference to the bufferView that contains the image. /// This field **MUST NOT** be defined when `uri` is defined. - final GltfRef? bufferView; - - Image({ - required super.root, - required this.uri, - required this.mimeType, - required this.bufferView, - }); - + required final GltfRef? bufferView, +}) extends GltfNode with GltfNodeWithData { Image.parse( GltfRoot root, Map map, @@ -48,7 +43,7 @@ class Image extends GltfNode with GltfNodeWithData { Future data() async { final uri = this.uri; if (uri != null) { - return root.readChunkFrom(uri); + return await root.readChunkFrom(uri); } else { final bufferView = this.bufferView?.get(); if (bufferView == null) { @@ -67,7 +62,7 @@ class Image extends GltfNode with GltfNodeWithData { @override Future loadData() async { - return flame3d.ImageTexture.create(await parseDartImage()); + return await flame3d.ImageTexture.create(await parseDartImage()); } flame3d.ImageTexture toFlameTexture() { diff --git a/packages/flame_3d/lib/src/parser/gltf/mag_filter.dart b/packages/flame_3d/lib/src/parser/gltf/mag_filter.dart index a0d4baa4825..53769870529 100644 --- a/packages/flame_3d/lib/src/parser/gltf/mag_filter.dart +++ b/packages/flame_3d/lib/src/parser/gltf/mag_filter.dart @@ -1,15 +1,10 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Magnification filter. Valid values correspond to WebGL enums. -enum MagFilter { +enum MagFilter(final String name, final int value) { nearest('NEAREST', 9728), linear('LINEAR', 9729); - final String name; - final int value; - - const MagFilter(this.name, this.value); - static MagFilter valueOf(int value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/material.dart b/packages/flame_3d/lib/src/parser/gltf/material.dart index c099ba92443..0d4e0f293d8 100644 --- a/packages/flame_3d/lib/src/parser/gltf/material.dart +++ b/packages/flame_3d/lib/src/parser/gltf/material.dart @@ -9,14 +9,15 @@ import 'package:flame_3d/src/parser/gltf/pbr_metallic_roughness.dart'; import 'package:flame_3d/src/parser/gltf/texture_info.dart'; /// The material appearance of a primitive. -class Material extends GltfNode { - final String? name; +class Material({ + required super.root, + required final String? name, /// A set of parameter values that are used to define the metallic-roughness /// material model from Physically Based Rendering (PBR) methodology. /// When undefined, all the default values of `pbrMetallicRoughness` **MUST** /// apply. - final PBRMetallicRoughness? pbrMetallicRoughness; + required final PBRMetallicRoughness? pbrMetallicRoughness, /// The tangent space normal texture. The texture encodes RGB components with /// linear transfer function. @@ -26,7 +27,7 @@ class Material extends GltfNode { /// toward the viewer. /// If a fourth component (A) is present, it **MUST** be ignored. /// When undefined, the material does not have a tangent space normal texture. - final NormalTextureInfo? normalTexture; + required final NormalTextureInfo? normalTexture, /// The occlusion texture. The occlusion values are linearly sampled from the /// R channel. @@ -35,7 +36,7 @@ class Material extends GltfNode { /// If other channels are present (GBA), they **MUST** be ignored for /// occlusion calculations. /// When undefined, the material does not have an occlusion texture. - final OcclusionTextureInfo? occlusionTexture; + required final OcclusionTextureInfo? occlusionTexture, /// The emissive texture. It controls the color and intensity of the light /// being emitted by the material. @@ -44,15 +45,15 @@ class Material extends GltfNode { /// If a fourth component (A) is present, it **MUST** be ignored. /// When undefined, the texture **MUST** be sampled as having `1.0` in RGB /// components. - final TextureInfo? emissiveTexture; + required final TextureInfo? emissiveTexture, /// The factors for the emissive color of the material. This value defines /// linear multipliers for the sampled texels of the emissive texture. - final Vector3 emissiveFactor; + required final Vector3 emissiveFactor, /// The material's alpha rendering mode enumeration specifying the /// interpretation of the alpha value of the base color. - final AlphaMode alphaMode; + required final AlphaMode alphaMode, /// Specifies whether the material is double sided. When this value is false, /// back-face culling is enabled. @@ -60,20 +61,8 @@ class Material extends GltfNode { /// lighting is enabled. /// The back-face **MUST** have its normals reversed before the lighting /// equation is evaluated. - final bool doubleSided; - - Material({ - required super.root, - required this.name, - required this.pbrMetallicRoughness, - required this.normalTexture, - required this.occlusionTexture, - required this.emissiveTexture, - required this.emissiveFactor, - required this.alphaMode, - required this.doubleSided, - }); - + required final bool doubleSided, +}) extends GltfNode { Material.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/mesh.dart b/packages/flame_3d/lib/src/parser/gltf/mesh.dart index 46548443e9b..9ca05eddd67 100644 --- a/packages/flame_3d/lib/src/parser/gltf/mesh.dart +++ b/packages/flame_3d/lib/src/parser/gltf/mesh.dart @@ -7,20 +7,16 @@ import 'package:flame_3d/src/parser/gltf/primitive.dart'; /// A set of primitives to be rendered. /// /// Its global transform is defined by a node that references it. -class Mesh extends GltfNode { +class Mesh({ + required super.root, + /// An array of primitives, each defining geometry to be rendered. - final List primitives; + required final List primitives, /// Array of weights to be applied to the morph targets. /// The number of array elements **MUST** match the number of morph targets - final List? weights; - - Mesh({ - required super.root, - required this.primitives, - required this.weights, - }); - + required final List? weights, +}) extends GltfNode { Mesh.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/mime_type.dart b/packages/flame_3d/lib/src/parser/gltf/mime_type.dart index cfb3b845a8b..a197db2e66f 100644 --- a/packages/flame_3d/lib/src/parser/gltf/mime_type.dart +++ b/packages/flame_3d/lib/src/parser/gltf/mime_type.dart @@ -1,14 +1,10 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; -enum MimeType { +enum MimeType(final String value) { jpeg('image/jpeg'), png('image/png'), string('string'); - final String value; - - const MimeType(this.value); - static MimeType valueOf(String value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/min_filter.dart b/packages/flame_3d/lib/src/parser/gltf/min_filter.dart index aa90a025457..74594362f22 100644 --- a/packages/flame_3d/lib/src/parser/gltf/min_filter.dart +++ b/packages/flame_3d/lib/src/parser/gltf/min_filter.dart @@ -1,7 +1,7 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Minification filter. Valid values correspond to WebGL enums. -enum MinFilter { +enum MinFilter(final String name, final int value) { nearest('NEAREST', 9728), linear('LINEAR', 9729), nearestMipmapNearest('NEAREST_MIPMAP_NEAREST', 9984), @@ -9,11 +9,6 @@ enum MinFilter { nearestMipmapLinear('NEAREST_MIPMAP_LINEAR', 9986), linearMipmapLinear('LINEAR_MIPMAP_LINEAR', 9987); - final String name; - final int value; - - const MinFilter(this.name, this.value); - static MinFilter valueOf(int value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/morph_target.dart b/packages/flame_3d/lib/src/parser/gltf/morph_target.dart index 3ae58f60f2a..aaeb241d6cf 100644 --- a/packages/flame_3d/lib/src/parser/gltf/morph_target.dart +++ b/packages/flame_3d/lib/src/parser/gltf/morph_target.dart @@ -9,14 +9,10 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// (`POSITION`, `NORMAL`, or `TANGENT`); and /// * each value is the index of the accessor containing the attribute /// displacements' data. -class MorphTarget extends GltfNode { - Map> attributes = {}; - - MorphTarget({ - required super.root, - required this.attributes, - }); - +class MorphTarget({ + required super.root, + required var Map> attributes, +}) extends GltfNode { MorphTarget.parse( GltfRoot root, Map map, @@ -31,15 +27,11 @@ class MorphTarget extends GltfNode { ); } -enum MorphTargetType { +enum MorphTargetType(final String value) { position('POSITION'), normal('NORMAL'), tangent('TANGENT'); - final String value; - - const MorphTargetType(this.value); - static MorphTargetType valueOf(String value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/node.dart b/packages/flame_3d/lib/src/parser/gltf/node.dart index 66757209bf4..6297b694b7d 100644 --- a/packages/flame_3d/lib/src/parser/gltf/node.dart +++ b/packages/flame_3d/lib/src/parser/gltf/node.dart @@ -21,69 +21,54 @@ import 'package:flame_3d/src/parser/gltf/skin.dart'; /// /// When a node is targeted for animation (referenced by an /// animation.channel.target), `matrix` **MUST NOT** be present. -class Node extends GltfNode { +class Node({ + required super.root, + /// The reference to the camera referenced by this node. - final GltfRef? camera; + required final GltfRef? camera, /// The references to this node's children. - final List> children; + required final List> children, /// The reference to skeleton nodes. /// /// Each node defines a subtree, which has a `jointName` of the corresponding /// element in the referenced `skin.jointNames`. - final List> skeletons; + required final List> skeletons, /// The reference to the skin referenced by this node. /// When a skin is referenced by a node within a scene, all joints used by /// the skin **MUST** belong to the same scene. /// When defined, `mesh` **MUST** also be defined. - final GltfRef? skin; + required final GltfRef? skin, /// Name used when this node is a joint in a skin. - final String? jointName; + required final String? jointName, /// A floating-point 4x4 transformation matrix stored in column-major order. - final Matrix4? matrix; + required final Matrix4? matrix, /// The reference to the mesh in this node. - final GltfRef? mesh; + required final GltfRef? mesh, /// The node's unit quaternion rotation in the order (x, y, z, w), /// where w is the scalar. - final Quaternion? rotation; + required final Quaternion? rotation, /// The node's non-uniform scale, given as the scaling factors along /// the x, y, and z axes. - final Vector3? scale; + required final Vector3? scale, /// The node's translation along the x, y, and z axes.". - final Vector3? translation; + required final Vector3? translation, /// The weights of the instantiated morph target. /// The number of array elements **MUST** match the number of morph targets /// of the referenced mesh. /// When defined, `mesh` **MUST** also be defined. - final List? weights; - - final String? name; - - Node({ - required super.root, - required this.camera, - required this.children, - required this.skeletons, - required this.skin, - required this.jointName, - required this.matrix, - required this.mesh, - required this.rotation, - required this.scale, - required this.translation, - required this.weights, - required this.name, - }); - + required final List? weights, + required final String? name, +}) extends GltfNode { Node.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart b/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart index f1470f06d6d..edc62072b47 100644 --- a/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart +++ b/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart @@ -3,25 +3,22 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; import 'package:flame_3d/src/parser/gltf/texture_info.dart'; /// Material Normal Texture Info. -class NormalTextureInfo extends TextureInfo { +class NormalTextureInfo({ + required super.root, + required super.index, + required super.texCoord, + /// The scalar parameter applied to each normal vector of the texture. /// /// This value scales the normal vector in X and Y directions using the /// formula: /// - /// ``` + /// ```text /// scaledNormal = normalize(( * 2.0 - 1.0) /// * vec3(, , 1.0)) /// ``` - final double scale; - - NormalTextureInfo({ - required super.root, - required super.index, - required super.texCoord, - required this.scale, - }); - + required final double scale, +}) extends TextureInfo { NormalTextureInfo.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart b/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart index 0bb7223b36d..1d51152e974 100644 --- a/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart +++ b/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart @@ -3,7 +3,11 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; import 'package:flame_3d/src/parser/gltf/texture_info.dart'; /// The occlusion texture. -class OcclusionTextureInfo extends TextureInfo { +class OcclusionTextureInfo({ + required super.root, + required super.index, + required super.texCoord, + /// A scalar parameter controlling the amount of occlusion applied. /// /// A value of `0.0` means no occlusion. A value of `1.0` means full @@ -13,15 +17,8 @@ class OcclusionTextureInfo extends TextureInfo { /// ```' /// 1.0 + strength * ( - 1.0) /// ``` - final double strength; - - OcclusionTextureInfo({ - required super.root, - required super.index, - required super.texCoord, - required this.strength, - }); - + required final double strength, +}) extends TextureInfo { OcclusionTextureInfo.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart b/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart index 9bb5eb428b0..5e6a7badf12 100644 --- a/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart +++ b/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart @@ -8,11 +8,13 @@ import 'package:flame_3d/src/parser/gltf/texture_info.dart'; /// A set of parameter values that are used to define the metallic-roughness /// material model from Physically-Based Rendering (PBR) methodology. -class PBRMetallicRoughness extends GltfNode { +class PBRMetallicRoughness({ + required super.root, + /// The factors for the base color of the material. /// This value defines linear multipliers for the sampled texels of the base /// color texture. - final Vector4? baseColorFactor; + required final Vector4? baseColorFactor, /// The base color texture. /// @@ -25,19 +27,19 @@ class PBRMetallicRoughness extends GltfNode { /// The `material.alphaMode` property specifies how alpha is interpreted. /// The stored texels **MUST NOT** be premultiplied. When undefined, /// the texture **MUST** be sampled as having `1.0` in all components." - final TextureInfo? baseColorTexture; + required final TextureInfo? baseColorTexture, /// The factor for the metalness of the material. /// This value defines a linear multiplier for the sampled metalness values /// of the metallic-roughness texture. /// Goes from [0, 1]. Default value is 1. - final double metallicFactor; + required final double metallicFactor, /// The factor for the roughness of the material. /// This value defines a linear multiplier for the sampled roughness values /// of the metallic-roughness texture. /// Goes from [0, 1]. Default value is 1. - final double roughnessFactor; + required final double roughnessFactor, /// The metallic-roughness texture. /// The metalness values are sampled from the B channel. @@ -47,17 +49,8 @@ class PBRMetallicRoughness extends GltfNode { /// metallic-roughness calculations. /// When undefined, the texture **MUST** be sampled as having `1.0` in /// G and B components." - final TextureInfo? metallicRoughnessTexture; - - PBRMetallicRoughness({ - required super.root, - required this.baseColorFactor, - required this.baseColorTexture, - required this.metallicFactor, - required this.roughnessFactor, - required this.metallicRoughnessTexture, - }); - + required final TextureInfo? metallicRoughnessTexture, +}) extends GltfNode { PBRMetallicRoughness.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/primitive.dart b/packages/flame_3d/lib/src/parser/gltf/primitive.dart index bf1a35e5786..eefb767a67b 100644 --- a/packages/flame_3d/lib/src/parser/gltf/primitive.dart +++ b/packages/flame_3d/lib/src/parser/gltf/primitive.dart @@ -15,38 +15,31 @@ import 'package:flame_3d/src/parser/gltf/primitive_mode.dart'; // (used in GLTF as the key for texture coordinate attributes) /// Geometry to be rendered with the given material. -class Primitive extends GltfNode { +class Primitive({ + required super.root, + /// The topology type of primitives to render. - final PrimitiveMode mode; + required final PrimitiveMode mode, /// A plain JSON object, where each key corresponds to a mesh attribute /// semantic and each value is the index of the accessor containing /// attribute's data. /// /// Typical keys include: `POSITION`, `NORMAL`, `TEXCOORD_0`, etc. - final Map attributes; + required final Map attributes, /// The reference to the accessor that contains the vertex indices. /// When this is undefined, the primitive defines non-indexed geometry. /// When defined, the accessor **MUST** have `SCALAR` type and an unsigned /// integer component type. - final GltfRef? indices; + required final GltfRef? indices, /// The reference to the material to apply to this primitive when rendering. - final GltfRef? material; + required final GltfRef? material, /// An array of morph targets. - final List targets; - - Primitive({ - required super.root, - required this.mode, - required this.attributes, - required this.indices, - required this.material, - required this.targets, - }); - + required final List targets, +}) extends GltfNode { GltfRef? get positions => _accessor('POSITION'); GltfRef? get normals => _accessor('NORMAL'); GltfRef? get texCoords => _accessor('TEXCOORD_0'); @@ -191,17 +184,11 @@ class Primitive extends GltfNode { ); } -class JointData { - final List weights; - final List localizedJoints; - final Map jointMap; - - JointData({ - required this.weights, - required this.localizedJoints, - required this.jointMap, - }); - +class JointData({ + required final List weights, + required final List localizedJoints, + required final Map jointMap, +}) { Vector4 weight(int index) { return weights.elementAtOrNull(index) ?? Vector4.zero(); } diff --git a/packages/flame_3d/lib/src/parser/gltf/primitive_mode.dart b/packages/flame_3d/lib/src/parser/gltf/primitive_mode.dart index d54e33519a1..f63283ce5ba 100644 --- a/packages/flame_3d/lib/src/parser/gltf/primitive_mode.dart +++ b/packages/flame_3d/lib/src/parser/gltf/primitive_mode.dart @@ -1,7 +1,7 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// The topology type of primitives to render. -enum PrimitiveMode { +enum PrimitiveMode(final int value) { points(0), lines(1), lineLoop(2), @@ -10,10 +10,6 @@ enum PrimitiveMode { triangleStrip(5), triangleFan(6); - final int value; - - const PrimitiveMode(this.value); - static PrimitiveMode valueOf(int value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/sampler.dart b/packages/flame_3d/lib/src/parser/gltf/sampler.dart index 45c9eba4932..3c7105d011a 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sampler.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sampler.dart @@ -5,27 +5,21 @@ import 'package:flame_3d/src/parser/gltf/min_filter.dart'; import 'package:flame_3d/src/parser/gltf/wrap_mode.dart'; /// Texture sampler properties for filtering and wrapping modes. -class Sampler extends GltfNode { +class Sampler({ + required super.root, + /// Magnification filter. - final MagFilter magFilter; + required final MagFilter magFilter, /// Minification filter. - final MinFilter minFilter; + required final MinFilter minFilter, /// The wrap mode for the s coordinate. - final WrapMode wrapS; + required final WrapMode wrapS, /// The wrap mode for the t coordinate. - final WrapMode wrapT; - - Sampler({ - required super.root, - required this.magFilter, - required this.minFilter, - required this.wrapS, - required this.wrapT, - }); - + required final WrapMode wrapT, +}) extends GltfNode { Sampler.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/scene.dart b/packages/flame_3d/lib/src/parser/gltf/scene.dart index ab0db240684..2066dc2faee 100644 --- a/packages/flame_3d/lib/src/parser/gltf/scene.dart +++ b/packages/flame_3d/lib/src/parser/gltf/scene.dart @@ -6,15 +6,12 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; import 'package:flame_3d/src/parser/gltf/node.dart'; /// The root nodes of a scene. -class Scene extends GltfNode { - /// The references to each root node. - final List> nodes; - - Scene({ - required super.root, - required this.nodes, - }); +class Scene({ + required super.root, + /// The references to each root node. + required final List> nodes, +}) extends GltfNode { Scene.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/skin.dart b/packages/flame_3d/lib/src/parser/gltf/skin.dart index 89eff12bf0f..512af24325f 100644 --- a/packages/flame_3d/lib/src/parser/gltf/skin.dart +++ b/packages/flame_3d/lib/src/parser/gltf/skin.dart @@ -5,29 +5,24 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; import 'package:flame_3d/src/parser/gltf/node.dart'; /// Joints and matrices defining a skin. -class Skin extends GltfNode { +class Skin({ + required super.root, + /// The reference to the accessor containing the floating-point 4x4 /// inverse-bind matrices. /// Its `accessor.count` property **MUST** be greater than or equal to the /// number of elements of the `joints` array. /// When undefined, each matrix is a 4x4 identity matrix. - final GltfRef? inverseBindMatrices; + required final GltfRef? inverseBindMatrices, /// The reference to the node used as a skeleton root. /// The node **MUST** be the closest common root of the joints hierarchy or a /// direct or indirect parent node of the closest common root. - final GltfRef? skeleton; + required final GltfRef? skeleton, /// Indices of skeleton nodes, used as joints in this skin. - final List> joints; - - Skin({ - required super.root, - required this.inverseBindMatrices, - required this.skeleton, - required this.joints, - }); - + required final List> joints, +}) extends GltfNode { Skin.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart index 8f062c4b9e2..c12836b9a12 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart @@ -5,27 +5,22 @@ import 'package:flame_3d/src/parser/gltf/sparse_accessor_values.dart'; /// Sparse storage of accessor values that deviate from their initialization /// value. -class SparseAccessor extends GltfNode { +class SparseAccessor({ + required super.root, + /// Number of deviating accessor values stored in the sparse array. - final int count; + required final int count, /// An object pointing to a buffer view containing the indices of deviating /// accessor values. /// The number of indices is equal to `count`. /// Indices **MUST** strictly increase. - final SparseAccessorIndices indices; + required final SparseAccessorIndices indices, /// An object pointing to a buffer view containing the deviating /// accessor values. - final SparseAccessorValues values; - - SparseAccessor({ - required super.root, - required this.count, - required this.indices, - required this.values, - }); - + required final SparseAccessorValues values, +}) extends GltfNode { SparseAccessor.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart index 3f90bb78460..1525466a2a7 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart @@ -8,27 +8,22 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// accessor values. /// The number of indices is equal to `accessor.sparse.count`. Indices **MUST** /// strictly increase. -class SparseAccessorIndices extends GltfNode { +class SparseAccessorIndices({ + required super.root, + /// The reference to the buffer view with sparse indices. /// The referenced buffer view **MUST NOT** have its `target` or `byteStride` /// properties defined. /// The buffer view and the optional `byteOffset` **MUST** be aligned to the /// `componentType` byte length." - final GltfRef bufferView; + required final GltfRef bufferView, /// The offset relative to the start of the buffer view in bytes. - final int byteOffset; + required final int byteOffset, /// The indices data type. - final ComponentType componentType; - - SparseAccessorIndices({ - required super.root, - required this.bufferView, - required this.byteOffset, - required this.componentType, - }); - + required final ComponentType componentType, +}) extends GltfNode { SparseAccessorIndices.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart index 5e8c6f96a12..3aa9cf7084f 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart @@ -10,21 +10,17 @@ import 'package:flame_3d/src/parser/gltf/gltf_root.dart'; /// The elements have the same component type as the base accessor. /// The elements are tightly packed. Data **MUST** be aligned following the /// same rules as the base accessor. -class SparseAccessorValues extends GltfNode { +class SparseAccessorValues({ + required super.root, + /// The index of the bufferView with sparse values. /// The referenced buffer view **MUST NOT** have its `target` or `byteStride` /// properties defined. - final GltfRef bufferView; + required final GltfRef bufferView, /// The offset relative to the start of the bufferView in bytes. - final int byteOffset; - - SparseAccessorValues({ - required super.root, - required this.bufferView, - required this.byteOffset, - }); - + required final int byteOffset, +}) extends GltfNode { SparseAccessorValues.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/texture.dart b/packages/flame_3d/lib/src/parser/gltf/texture.dart index ca51b88af05..ecbad969023 100644 --- a/packages/flame_3d/lib/src/parser/gltf/texture.dart +++ b/packages/flame_3d/lib/src/parser/gltf/texture.dart @@ -8,37 +8,29 @@ import 'package:flame_3d/src/parser/gltf/texture_format.dart'; import 'package:flame_3d/src/parser/gltf/texture_target.dart'; import 'package:flame_3d/src/parser/gltf/texture_type.dart'; -class Texture extends GltfNode { +class Texture({ + required super.root, + /// The texture's format. Defaults to `6408` (RGBA). - final TextureFormat format; + required final TextureFormat format, /// The texture's internal format. Defaults to `6408` (RGBA). - final TextureFormat internalFormat; + required final TextureFormat internalFormat, /// The reference to the sampler used by this texture. - final GltfRef? sampler; + required final GltfRef? sampler, /// The reference to the image used by this texture. - final GltfRef source; + required final GltfRef source, /// The target that the WebGL texture should be bound to. /// /// Valid values correspond to WebGL enums: `3553` (TEXTURE_2D). - final TextureTarget target; + required final TextureTarget target, /// Texel datatype. Defaults to `5121` (UNSIGNED_BYTE). - final TextureType type; - - Texture({ - required super.root, - required this.format, - required this.internalFormat, - required this.sampler, - required this.source, - required this.target, - required this.type, - }); - + required final TextureType type, +}) extends GltfNode { Texture.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/texture_format.dart b/packages/flame_3d/lib/src/parser/gltf/texture_format.dart index afb9b91be87..e65def8077a 100644 --- a/packages/flame_3d/lib/src/parser/gltf/texture_format.dart +++ b/packages/flame_3d/lib/src/parser/gltf/texture_format.dart @@ -1,18 +1,13 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Texture formats; values correspond to WebGL enums. -enum TextureFormat { +enum TextureFormat(final String name, final int value) { alpha('ALPHA', 6406), rgb('RGB', 6407), rgba('RGBA', 6408), luminance('LUMINANCE', 6409), luminanceAlpha('LUMINANCE_ALPHA', 6410); - final String name; - final int value; - - const TextureFormat(this.name, this.value); - static TextureFormat valueOf(String name) { return values.firstWhere((e) => e.name == name); } diff --git a/packages/flame_3d/lib/src/parser/gltf/texture_info.dart b/packages/flame_3d/lib/src/parser/gltf/texture_info.dart index 8313511294d..359a7ebbb34 100644 --- a/packages/flame_3d/lib/src/parser/gltf/texture_info.dart +++ b/packages/flame_3d/lib/src/parser/gltf/texture_info.dart @@ -8,9 +8,11 @@ import 'package:flame_3d/src/parser/gltf/texture.dart'; // (used in GLTF as the key for texture coordinate attributes) /// Reference to a texture. -class TextureInfo extends GltfNode { +class TextureInfo({ + required super.root, + /// The reference to the texture. - final GltfRef index; + required final GltfRef index, /// This integer value is used to construct a string in the format /// `TEXCOORD_`, which is a reference to a key in @@ -19,14 +21,8 @@ class TextureInfo extends GltfNode { /// /// A mesh primitive **MUST** have the corresponding texture coordinate /// attributes for the material to be applicable to it. - final int? texCoord; - - TextureInfo({ - required super.root, - required this.index, - this.texCoord, - }); - + final int? texCoord, +}) extends GltfNode { TextureInfo.parse( GltfRoot root, Map map, diff --git a/packages/flame_3d/lib/src/parser/gltf/texture_target.dart b/packages/flame_3d/lib/src/parser/gltf/texture_target.dart index 81c9afa7a6c..77af513758a 100644 --- a/packages/flame_3d/lib/src/parser/gltf/texture_target.dart +++ b/packages/flame_3d/lib/src/parser/gltf/texture_target.dart @@ -1,14 +1,9 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Texture targets; values correspond to WebGL enums. -enum TextureTarget { +enum TextureTarget(final String name, final int value) { texture2d('TEXTURE_2D', 3553); - final String name; - final int value; - - const TextureTarget(this.name, this.value); - static TextureTarget valueOf(String name) { return values.firstWhere((e) => e.name == name); } diff --git a/packages/flame_3d/lib/src/parser/gltf/texture_type.dart b/packages/flame_3d/lib/src/parser/gltf/texture_type.dart index 70fd593bbd4..d23096199f9 100644 --- a/packages/flame_3d/lib/src/parser/gltf/texture_type.dart +++ b/packages/flame_3d/lib/src/parser/gltf/texture_type.dart @@ -1,17 +1,12 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Texture formats; values correspond to WebGL enums. -enum TextureType { +enum TextureType(final String name, final int value) { unsignedByte('UNSIGNED_BYTE', 5121), unsignedShort565('UNSIGNED_SHORT_5_6_5', 33635), unsignedShort4444('UNSIGNED_SHORT_4_4_4_4', 32819), unsignedShort5551('UNSIGNED_SHORT_5_5_5_1', 32820); - final String name; - final int value; - - const TextureType(this.name, this.value); - static TextureType valueOf(int value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf/wrap_mode.dart b/packages/flame_3d/lib/src/parser/gltf/wrap_mode.dart index 9b7ac75de66..00a7c7202e9 100644 --- a/packages/flame_3d/lib/src/parser/gltf/wrap_mode.dart +++ b/packages/flame_3d/lib/src/parser/gltf/wrap_mode.dart @@ -1,16 +1,11 @@ import 'package:flame_3d/src/parser/gltf/gltf_node.dart'; /// Wrapping mode. Valid values correspond to WebGL enums. -enum WrapMode { +enum WrapMode(final String name, final int value) { clampToEdge('CLAMP_TO_EDGE', 33071), mirroredRepeat('MIRRORED_REPEAT', 33648), repeat('REPEAT', 10497); - final String name; - final int value; - - const WrapMode(this.name, this.value); - static WrapMode valueOf(int value) { return values.firstWhere((e) => e.value == value); } diff --git a/packages/flame_3d/lib/src/parser/gltf_parser.dart b/packages/flame_3d/lib/src/parser/gltf_parser.dart index b2b13afede0..3267a4335fc 100644 --- a/packages/flame_3d/lib/src/parser/gltf_parser.dart +++ b/packages/flame_3d/lib/src/parser/gltf_parser.dart @@ -5,7 +5,7 @@ import 'package:flame_3d/src/parser/model_parser.dart'; /// Parses GLB and GLTF file formats as per specified by: /// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.pdf -class GltfParser extends ModelParser { +class GltfParser() extends ModelParser { @override Future parseModel(String filePath) async { final root = await parseGltf(filePath); @@ -14,7 +14,7 @@ class GltfParser extends ModelParser { Future parseGltf(String filePath) async { final content = await Flame.assets.readJson(filePath); - return GltfRoot.from( + return await GltfRoot.from( prefix: ModelParser.prefix(filePath), json: content, chunks: [], diff --git a/packages/flame_3d/lib/src/parser/model_parser.dart b/packages/flame_3d/lib/src/parser/model_parser.dart index 37f53f81230..2de7656994f 100644 --- a/packages/flame_3d/lib/src/parser/model_parser.dart +++ b/packages/flame_3d/lib/src/parser/model_parser.dart @@ -3,12 +3,12 @@ import 'package:flame_3d/src/parser/glb_parser.dart'; import 'package:flame_3d/src/parser/gltf_parser.dart'; import 'package:flame_3d/src/parser/obj_parser.dart'; -abstract class ModelParser { +abstract class ModelParser() { Future parseModel(String filePath); static Future parse(String filePath) async { final parser = _getParser(filePath); - return parser.parseModel(filePath); + return await parser.parseModel(filePath); } static ModelParser _getParser(String filePath) { diff --git a/packages/flame_3d/lib/src/parser/obj/surface_tool.dart b/packages/flame_3d/lib/src/parser/obj/surface_tool.dart index b204cd1e69c..9eb76b52fba 100644 --- a/packages/flame_3d/lib/src/parser/obj/surface_tool.dart +++ b/packages/flame_3d/lib/src/parser/obj/surface_tool.dart @@ -8,7 +8,7 @@ import 'package:flame_3d/resources.dart'; // TODO(wolfenrain): heavily inspired by the Godot one, maybe this should be // part of the core package -class SurfaceTool { +class SurfaceTool() { final List _vertices = []; final List _indices = []; diff --git a/packages/flame_3d/lib/src/parser/obj_parser.dart b/packages/flame_3d/lib/src/parser/obj_parser.dart index b754e26b0cc..53a07399ee5 100644 --- a/packages/flame_3d/lib/src/parser/obj_parser.dart +++ b/packages/flame_3d/lib/src/parser/obj_parser.dart @@ -10,7 +10,7 @@ import 'package:flame_3d/src/parser/obj/surface_tool.dart'; // These are keywords used in the OBJ syntax. // cSpell:ignore usemtl newmtl mtllib -class ObjParser extends ModelParser { +class ObjParser() extends ModelParser { @override Future parseModel(String filePath) async { final mesh = await parseMesh(filePath); diff --git a/packages/flame_3d/lib/src/resources/light/ambient_light.dart b/packages/flame_3d/lib/src/resources/light/ambient_light.dart index 755ac2e0162..52223909bfe 100644 --- a/packages/flame_3d/lib/src/resources/light/ambient_light.dart +++ b/packages/flame_3d/lib/src/resources/light/ambient_light.dart @@ -2,9 +2,7 @@ import 'dart:ui' show Color; import 'package:flame_3d/resources.dart'; -class AmbientLight extends LightSource { - AmbientLight({ - super.color = const Color(0xFFFFFFFF), - super.intensity = 0.2, - }); -} +class AmbientLight({ + super.color = const Color(0xFFFFFFFF), + super.intensity = 0.2, +}) extends LightSource; diff --git a/packages/flame_3d/lib/src/resources/light/light.dart b/packages/flame_3d/lib/src/resources/light/light.dart index d93e5c53d74..3613d622fa9 100644 --- a/packages/flame_3d/lib/src/resources/light/light.dart +++ b/packages/flame_3d/lib/src/resources/light/light.dart @@ -9,17 +9,10 @@ import 'package:flame_3d/resources.dart'; /// Instead, it is used to modify how other resources are uploaded. /// /// {@endtemplate} -class Light extends Resource { - final Vector3 position; - - final LightSource source; - - /// {@macro light} - Light({ - required this.position, - required this.source, - }); - +class Light({ + required final Vector3 position, + required final LightSource source, +}) extends Resource { @override void createResource() {} } diff --git a/packages/flame_3d/lib/src/resources/light/light_source.dart b/packages/flame_3d/lib/src/resources/light/light_source.dart index 7b7992f924a..3bc1ef8bda9 100644 --- a/packages/flame_3d/lib/src/resources/light/light_source.dart +++ b/packages/flame_3d/lib/src/resources/light/light_source.dart @@ -5,12 +5,7 @@ import 'package:flame_3d/resources.dart'; /// Describes the properties of a light source. /// There are three types of light sources: point, directional, and spot. /// Currently only [PointLight] is implemented. -abstract class LightSource { - final Color color; - final double intensity; - - LightSource({ - required this.color, - required this.intensity, - }); -} +abstract class LightSource({ + required final Color color, + required final double intensity, +}); diff --git a/packages/flame_3d/lib/src/resources/light/point_light.dart b/packages/flame_3d/lib/src/resources/light/point_light.dart index 7e60bcfe3f6..a7f9a93cf81 100644 --- a/packages/flame_3d/lib/src/resources/light/point_light.dart +++ b/packages/flame_3d/lib/src/resources/light/point_light.dart @@ -1,9 +1,7 @@ import 'package:flame_3d/resources.dart'; /// A point light that emits light in all directions equally. -class PointLight extends LightSource { - PointLight({ - required super.color, - required super.intensity, - }); -} +class PointLight({ + required super.color, + required super.intensity, +}) extends LightSource; diff --git a/packages/flame_3d/lib/src/resources/material/material.dart b/packages/flame_3d/lib/src/resources/material/material.dart index 6dc6964ddd8..09e02754afe 100644 --- a/packages/flame_3d/lib/src/resources/material/material.dart +++ b/packages/flame_3d/lib/src/resources/material/material.dart @@ -7,13 +7,10 @@ import 'package:flame_3d/resources.dart'; /// Base material [Resource], it holds the shader library that should be used /// for the material. /// {@endtemplate} -abstract class Material extends Resource { - /// {@macro material} - Material({ - required this._vertexShader, - required this._fragmentShader, - }); - +abstract class Material({ + required var Shader _vertexShader, + required var Shader _fragmentShader, +}) extends Resource { static Material defaultMaterial = SpatialMaterial() ..albedoColor = const Color(0xFFFF00FF); @@ -26,14 +23,12 @@ abstract class Material extends Resource { } Shader get vertexShader => _vertexShader; - Shader _vertexShader; set vertexShader(Shader shader) { _vertexShader = shader; recreateResource = true; } Shader get fragmentShader => _fragmentShader; - Shader _fragmentShader; set fragmentShader(Shader shader) { _fragmentShader = shader; recreateResource = true; diff --git a/packages/flame_3d/lib/src/resources/material/spatial_material.dart b/packages/flame_3d/lib/src/resources/material/spatial_material.dart index d5c763724ae..cc7d578b4fc 100644 --- a/packages/flame_3d/lib/src/resources/material/spatial_material.dart +++ b/packages/flame_3d/lib/src/resources/material/spatial_material.dart @@ -3,39 +3,33 @@ import 'dart:ui' hide FragmentShader; import 'package:flame_3d/graphics.dart'; import 'package:flame_3d/resources.dart'; -class SpatialMaterial extends Material { - SpatialMaterial({ - this.albedoColor = const Color(0xFFFFFFFF), - Texture? albedoTexture, - this.metallic = 0.8, - this.roughness = 0.6, - }) : albedoTexture = albedoTexture ?? Texture.standard, - super( - vertexShader: VertexShader.fromAsset( - 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', - slots: ['VertexInfo', 'JointMatrices'], - ), - fragmentShader: FragmentShader.fromAsset( - 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', - slots: [ - 'albedoTexture', - 'Material', - 'AmbientLight', - 'Lights', - 'Camera', - ], - ), - ); - +class SpatialMaterial({ /// The material's base color. - Color albedoColor; + var Color albedoColor = const Color(0xFFFFFFFF), + Texture? albedoTexture, + var double metallic = 0.8, + var double roughness = 0.6, +}) extends Material { + this + : super( + vertexShader: VertexShader.fromAsset( + 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', + slots: ['VertexInfo', 'JointMatrices'], + ), + fragmentShader: FragmentShader.fromAsset( + 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', + slots: [ + 'albedoTexture', + 'Material', + 'AmbientLight', + 'Lights', + 'Camera', + ], + ), + ); /// The texture that will be multiplied by [albedoColor]. - Texture albedoTexture; - - double metallic; - - double roughness; + Texture albedoTexture = albedoTexture ?? Texture.standard; @override void apply(covariant RenderContext3D context) { diff --git a/packages/flame_3d/lib/src/resources/material/unlit_material.dart b/packages/flame_3d/lib/src/resources/material/unlit_material.dart index bd999cf557e..e5f85d325ac 100644 --- a/packages/flame_3d/lib/src/resources/material/unlit_material.dart +++ b/packages/flame_3d/lib/src/resources/material/unlit_material.dart @@ -15,28 +15,26 @@ import 'package:flame_3d/resources.dart'; /// - Emissive/self-lit surfaces /// - Sky boxes and debug rendering /// {@endtemplate} -class UnlitMaterial extends Material { - /// {@macro unlit_material} - UnlitMaterial({ - this.albedoColor = const Color(0xFFFFFFFF), - Texture? albedoTexture, - }) : albedoTexture = albedoTexture ?? Texture.standard, - super( - vertexShader: VertexShader.fromAsset( - 'packages/flame_3d/assets/shaders/unlit_material.shaderbundle', - slots: ['VertexInfo', 'JointMatrices'], - ), - fragmentShader: FragmentShader.fromAsset( - 'packages/flame_3d/assets/shaders/unlit_material.shaderbundle', - slots: ['albedoTexture', 'Material'], - ), - ); - +class UnlitMaterial({ /// The material's base color, multiplied with [albedoTexture]. - Color albedoColor; + var Color albedoColor = const Color(0xFFFFFFFF), + Texture? albedoTexture, +}) extends Material { + /// {@macro unlit_material} + this + : super( + vertexShader: VertexShader.fromAsset( + 'packages/flame_3d/assets/shaders/unlit_material.shaderbundle', + slots: ['VertexInfo', 'JointMatrices'], + ), + fragmentShader: FragmentShader.fromAsset( + 'packages/flame_3d/assets/shaders/unlit_material.shaderbundle', + slots: ['albedoTexture', 'Material'], + ), + ); /// The texture to render. Multiplied by [albedoColor]. - Texture albedoTexture; + Texture albedoTexture = albedoTexture ?? Texture.standard; @override void apply(covariant RenderContext3D context) { diff --git a/packages/flame_3d/lib/src/resources/mesh/cone_mesh.dart b/packages/flame_3d/lib/src/resources/mesh/cone_mesh.dart index b38c0c491de..ef6c1cea0e4 100644 --- a/packages/flame_3d/lib/src/resources/mesh/cone_mesh.dart +++ b/packages/flame_3d/lib/src/resources/mesh/cone_mesh.dart @@ -9,18 +9,18 @@ import 'package:flame_3d/resources.dart'; /// /// The default texture mapping follows the standard arrangement of the circular /// base on the top left quadrant and the flattened side on the bottom half. -class ConeMesh extends Mesh { +class ConeMesh({ + required double radius, + required double height, + required Material material, + int segments = 32, +}) extends Mesh { /// Creates a conical mesh with a circular base of radius [radius] on the x-z /// plane and a height of [height] pointing upwards parallel to the y-axis. /// /// You can optionally specify the number of segments used for the /// triangulation (the higher, the more "high-res" the cone will be). - ConeMesh({ - required double radius, - required double height, - required Material material, - int segments = 32, - }) { + this { _addBaseSurface( radius: radius, material: material, diff --git a/packages/flame_3d/lib/src/resources/mesh/cuboid_mesh.dart b/packages/flame_3d/lib/src/resources/mesh/cuboid_mesh.dart index f3b8998d4b3..910ddf026fc 100644 --- a/packages/flame_3d/lib/src/resources/mesh/cuboid_mesh.dart +++ b/packages/flame_3d/lib/src/resources/mesh/cuboid_mesh.dart @@ -4,13 +4,13 @@ import 'package:flame_3d/resources.dart'; /// {@template cuboid_mesh} /// Represents a Cuboid's geometry with a single surface. /// {@endtemplate} -class CuboidMesh extends Mesh { +class CuboidMesh({ + required Vector3 size, + Material? material, + bool useFaceNormals = true, +}) extends Mesh { /// {@macro cuboid_mesh} - CuboidMesh({ - required Vector3 size, - Material? material, - bool useFaceNormals = true, - }) : size = size.asUnmodifiableView() { + this { final Vector3(:x, :y, :z) = size / 2; Vertex vertex({ @@ -178,5 +178,5 @@ class CuboidMesh extends Mesh { } /// The full size of the cuboid along each axis. - final Vector3 size; + final Vector3 size = size.asUnmodifiableView(); } diff --git a/packages/flame_3d/lib/src/resources/mesh/cylinder_mesh.dart b/packages/flame_3d/lib/src/resources/mesh/cylinder_mesh.dart index bac2d4565dc..8934537515b 100644 --- a/packages/flame_3d/lib/src/resources/mesh/cylinder_mesh.dart +++ b/packages/flame_3d/lib/src/resources/mesh/cylinder_mesh.dart @@ -4,13 +4,16 @@ import 'package:flame/geometry.dart'; import 'package:flame_3d/game.dart'; import 'package:flame_3d/resources.dart'; -class CylinderMesh extends Mesh { - CylinderMesh({ - required this.radius, - required this.height, - int segments = 16, - Material? material, - }) { +class CylinderMesh({ + /// The radius of the cylinder. + required final double radius, + + /// The full height of the cylinder along the y-axis. + required final double height, + int segments = 16, + Material? material, +}) extends Mesh { + this { final vertices = []; final halfHeight = height / 2.0; @@ -91,10 +94,4 @@ class CylinderMesh extends Mesh { ), ); } - - /// The radius of the cylinder. - final double radius; - - /// The full height of the cylinder along the y-axis. - final double height; } diff --git a/packages/flame_3d/lib/src/resources/mesh/mesh.dart b/packages/flame_3d/lib/src/resources/mesh/mesh.dart index 6ab2a753820..538d4ad94db 100644 --- a/packages/flame_3d/lib/src/resources/mesh/mesh.dart +++ b/packages/flame_3d/lib/src/resources/mesh/mesh.dart @@ -9,9 +9,9 @@ import 'package:flame_3d/resources.dart'; /// This class isn't a true resource, it does not upload it self to the GPU. /// Instead it uploads [Surface]s, it acts as a proxy. /// {@endtemplate} -class Mesh extends Resource { +class Mesh() extends Resource { /// {@macro mesh} - Mesh() : _surfaces = []; + this : _surfaces = []; final List _surfaces; Aabb3? _aabb; diff --git a/packages/flame_3d/lib/src/resources/mesh/plane_mesh.dart b/packages/flame_3d/lib/src/resources/mesh/plane_mesh.dart index faea9893c1c..15a4287e44a 100644 --- a/packages/flame_3d/lib/src/resources/mesh/plane_mesh.dart +++ b/packages/flame_3d/lib/src/resources/mesh/plane_mesh.dart @@ -4,12 +4,12 @@ import 'package:flame_3d/resources.dart'; /// {@template plane_mesh} /// Represents a 2D Plane's geometry with a single surface. /// {@endtemplate} -class PlaneMesh extends Mesh { +class PlaneMesh({ + required Vector2 size, + Material? material, +}) extends Mesh { /// {@macro plane_mesh} - PlaneMesh({ - required Vector2 size, - Material? material, - }) { + this { final Vector2(:x, :y) = size / 2; final vertices = [ diff --git a/packages/flame_3d/lib/src/resources/mesh/sphere_mesh.dart b/packages/flame_3d/lib/src/resources/mesh/sphere_mesh.dart index 1e96e9cb1b3..c036d1f77b7 100644 --- a/packages/flame_3d/lib/src/resources/mesh/sphere_mesh.dart +++ b/packages/flame_3d/lib/src/resources/mesh/sphere_mesh.dart @@ -6,13 +6,14 @@ import 'package:flame_3d/resources.dart'; /// {@template sphere_mesh} /// Represents a Sphere's geometry with a single surface. /// {@endtemplate} -class SphereMesh extends Mesh { +class SphereMesh({ + /// The radius of the sphere. + required final double radius, + int segments = 64, + Material? material, +}) extends Mesh { /// {@macro sphere_mesh} - SphereMesh({ - required this.radius, - int segments = 64, - Material? material, - }) { + this { final vertices = []; for (var i = 0; i <= segments; i++) { final theta = i * (2 * math.pi) / segments; @@ -56,7 +57,4 @@ class SphereMesh extends Mesh { ), ); } - - /// The radius of the sphere. - final double radius; } diff --git a/packages/flame_3d/lib/src/resources/mesh/surface.dart b/packages/flame_3d/lib/src/resources/mesh/surface.dart index 82bce7359d8..b1f341259c8 100644 --- a/packages/flame_3d/lib/src/resources/mesh/surface.dart +++ b/packages/flame_3d/lib/src/resources/mesh/surface.dart @@ -5,25 +5,25 @@ import 'package:flame_3d/game.dart'; import 'package:flame_3d/graphics.dart'; import 'package:flame_3d/resources.dart'; -enum PrimitiveType { +enum PrimitiveType() { triangles, } /// {@template surface} /// Base surface [Resource], it describes a single surface to be rendered. /// {@endtemplate} -class Surface extends Resource { - /// {@macro surface} - Surface({ - required List vertices, - required List indices, - Material? material, - this.jointMap, - /** +class Surface({ + required List vertices, + required List indices, + Material? material, + var Map? jointMap, + /** * If `true`, the normals will be calculated if they are not provided. */ - bool calculateNormals = true, - }) : material = material ?? Material.defaultMaterial { + bool calculateNormals = true, +}) extends Resource { + /// {@macro surface} + this { final normalizedVertices = _normalize( vertices: vertices, indices: indices, @@ -54,9 +54,7 @@ class Surface extends Resource { _calculateAabb(normalizedVertices); } - Material material; - Map? jointMap; - + Material material = material ?? Material.defaultMaterial; Aabb3 get aabb => _aabb; late Aabb3 _aabb; diff --git a/packages/flame_3d/lib/src/resources/mesh/vertex.dart b/packages/flame_3d/lib/src/resources/mesh/vertex.dart index 540fbc6252b..345aeeb2197 100644 --- a/packages/flame_3d/lib/src/resources/mesh/vertex.dart +++ b/packages/flame_3d/lib/src/resources/mesh/vertex.dart @@ -11,49 +11,41 @@ import 'package:meta/meta.dart'; /// color. /// {@endtemplate} @immutable -class Vertex { - /// {@macro vertex} - Vertex({ - required Vector3 position, - required Vector2 texCoord, - this.color = const Color(0xFFFFFFFF), - Vector3? normal, - Vector4? joints, - Vector4? weights, - }) : position = position.immutable, - texCoord = texCoord.immutable, - normal = normal?.immutable, - joints = joints?.immutable, - weights = weights?.immutable, - _storage = Float32List.fromList([ - ...position.storage, // 1, 2, 3 - ...texCoord.storage, // 4, 5 - ...[color.r, color.g, color.b, color.a], // 6, 7, 8, 9 - ...(normal ?? Vector3.zero()).storage, // 10, 11, 12 - ...(joints ?? Vector4.zero()).storage, // 13, 14, 15, 16 - ...(weights ?? Vector4.zero()).storage, // 17, 18, 19, 20 - ]); +// ignore: prefer_const_constructors_in_immutables +class Vertex({ + required Vector3 position, + required Vector2 texCoord, + /// The color on the vertex. + final Color color = const Color(0xFFFFFFFF), + Vector3? normal, + Vector4? joints, + Vector4? weights, +}) { Float32List get storage => _storage; - final Float32List _storage; + final Float32List _storage = Float32List.fromList([ + ...position.storage, // 1, 2, 3 + ...texCoord.storage, // 4, 5 + ...[color.r, color.g, color.b, color.a], // 6, 7, 8, 9 + ...(normal ?? Vector3.zero()).storage, // 10, 11, 12 + ...(joints ?? Vector4.zero()).storage, // 13, 14, 15, 16 + ...(weights ?? Vector4.zero()).storage, // 17, 18, 19, 20 + ]); /// The position of the vertex in 3D space. - final ImmutableVector3 position; + final ImmutableVector3 position = position.immutable; /// The UV coordinates of the texture to map. - final ImmutableVector2 texCoord; + final ImmutableVector2 texCoord = texCoord.immutable; /// The normal vector of the vertex. - final ImmutableVector3? normal; + final ImmutableVector3? normal = normal?.immutable; /// The joints of the vertex. - final ImmutableVector4? joints; + final ImmutableVector4? joints = joints?.immutable; /// The weights of the vertex. - final ImmutableVector4? weights; - - /// The color on the vertex. - final Color color; + final ImmutableVector4? weights = weights?.immutable; @override bool operator ==(Object other) => diff --git a/packages/flame_3d/lib/src/resources/resource.dart b/packages/flame_3d/lib/src/resources/resource.dart index 2bbeb8cb8d5..f4426ff4fd2 100644 --- a/packages/flame_3d/lib/src/resources/resource.dart +++ b/packages/flame_3d/lib/src/resources/resource.dart @@ -5,7 +5,7 @@ /// A Resource is the base class for any resource typed classes. The primary /// use case is to be a data container. /// {@endtemplate} -abstract class Resource { +abstract class Resource() { R? _resource; bool recreateResource = true; diff --git a/packages/flame_3d/lib/src/resources/shader/fragment_shader.dart b/packages/flame_3d/lib/src/resources/shader/fragment_shader.dart index cc40af1e81f..e3a85d4fbe6 100644 --- a/packages/flame_3d/lib/src/resources/shader/fragment_shader.dart +++ b/packages/flame_3d/lib/src/resources/shader/fragment_shader.dart @@ -6,11 +6,11 @@ import 'package:flame_3d/resources.dart'; /// Typically used to compute the final color of each pixel based on material /// properties, lighting, and textures. /// {@endtemplate} -class FragmentShader extends Shader { +class FragmentShader.fromAsset( + super.assetName, { + super.entryPoint = 'TextureFragment', + super.slots = const [], +}) extends Shader { /// {@macro fragment_shader} - FragmentShader.fromAsset( - super.assetName, { - super.entryPoint = 'TextureFragment', - super.slots = const [], - }) : super.fromAsset(); + this : super.fromAsset(); } diff --git a/packages/flame_3d/lib/src/resources/shader/shader.dart b/packages/flame_3d/lib/src/resources/shader/shader.dart index d01dc730269..2842467bee2 100644 --- a/packages/flame_3d/lib/src/resources/shader/shader.dart +++ b/packages/flame_3d/lib/src/resources/shader/shader.dart @@ -16,7 +16,19 @@ import 'package:flame_3d/resources.dart'; /// Samplers are auto-detected at compile time via [GpuUniformSlot.sizeInBytes] /// returning `null` — no need to declare them separately. /// {@endtemplate} -class Shader extends Resource { +class Shader._( + final GpuShader Function(String key) _getShader, { + + /// The shader entry point name within the bundle. + required final String entryPoint, + + /// Names of all uniform slots — both struct blocks and samplers. + /// + /// The type of each slot is auto-detected at compile time: + /// struct blocks have a non-null [GpuUniformSlot.sizeInBytes], + /// samplers return `null`. + required final List slots, +}) extends Resource { /// Load a [Shader] from asset. Shader.fromAsset( String assetName, { @@ -28,24 +40,6 @@ class Shader extends Resource { slots: slots, ); - Shader._( - this._getShader, { - required this.entryPoint, - required this.slots, - }); - - /// The shader entry point name within the bundle. - final String entryPoint; - - /// Names of all uniform slots — both struct blocks and samplers. - /// - /// The type of each slot is auto-detected at compile time: - /// struct blocks have a non-null [GpuUniformSlot.sizeInBytes], - /// samplers return `null`. - final List slots; - - final GpuShader Function(String key) _getShader; - final Map _slots = {}; final Map _bindings = {}; @@ -172,22 +166,17 @@ class Shader extends Resource { } } -sealed class _SlotBinding { - _SlotBinding(this.slot); - - final GpuUniformSlot slot; - +sealed class _SlotBinding(final GpuUniformSlot slot) { T get resource; } -class _UniformBinding extends _SlotBinding { - _UniformBinding(super.slot) - : _data = Float32List(slot.sizeInBytes! ~/ Float32List.bytesPerElement); - +class _UniformBinding(super.slot) extends _SlotBinding { @override ByteBuffer get resource => _data.buffer; - final Float32List _data; + final Float32List _data = Float32List( + slot.sizeInBytes! ~/ Float32List.bytesPerElement, + ); final Map _memberOffsets = {}; /// Write a struct member (optionally array-indexed) directly into the buffer. @@ -223,9 +212,5 @@ class _UniformBinding extends _SlotBinding { } } -class _TextureBinding extends _SlotBinding { - _TextureBinding(super.slot, this.resource); - - @override - Texture resource; -} +class _TextureBinding(super.slot, @override var Texture resource) + extends _SlotBinding; diff --git a/packages/flame_3d/lib/src/resources/shader/vertex_shader.dart b/packages/flame_3d/lib/src/resources/shader/vertex_shader.dart index 370b460af0d..49697d1d508 100644 --- a/packages/flame_3d/lib/src/resources/shader/vertex_shader.dart +++ b/packages/flame_3d/lib/src/resources/shader/vertex_shader.dart @@ -7,11 +7,11 @@ import 'package:flame_3d/resources.dart'; /// Typically used to apply model, view, and projection transforms, as well /// as skeletal animation via joint matrices. /// {@endtemplate} -class VertexShader extends Shader { +class VertexShader.fromAsset( + super.assetName, { + super.entryPoint = 'TextureVertex', + super.slots = const [], +}) extends Shader { /// {@macro vertex_shader} - VertexShader.fromAsset( - super.assetName, { - super.entryPoint = 'TextureVertex', - super.slots = const [], - }) : super.fromAsset(); + this : super.fromAsset(); } diff --git a/packages/flame_3d/lib/src/resources/texture/color_texture.dart b/packages/flame_3d/lib/src/resources/texture/color_texture.dart index 0e4de7e146b..7725bf52fe7 100644 --- a/packages/flame_3d/lib/src/resources/texture/color_texture.dart +++ b/packages/flame_3d/lib/src/resources/texture/color_texture.dart @@ -6,9 +6,10 @@ import 'package:flame_3d/resources.dart'; /// {@template color_texture} /// A texture that holds a single color. By default it creates a 1x1 texture. /// {@endtemplate} -class ColorTexture extends Texture { +class ColorTexture(Color color, {super.width = 1, super.height = 1}) + extends Texture { /// {@macro color_texture} - ColorTexture(Color color, {super.width = 1, super.height = 1}) + this : super( Uint32List.fromList( List.filled( diff --git a/packages/flame_3d/lib/src/resources/texture/image_texture.dart b/packages/flame_3d/lib/src/resources/texture/image_texture.dart index 4f395577ff5..bd24edb8f83 100644 --- a/packages/flame_3d/lib/src/resources/texture/image_texture.dart +++ b/packages/flame_3d/lib/src/resources/texture/image_texture.dart @@ -5,10 +5,8 @@ import 'package:flame_3d/resources.dart'; /// {@template image_texture} /// A texture that holds an image as it's render-able texture. /// {@endtemplate} -class ImageTexture extends Texture { - /// {@macro image_texture} - ImageTexture(super.source, {required super.width, required super.height}); - +class ImageTexture(super.source, {required super.width, required super.height}) + extends Texture { /// Create a [ImageTexture] from the given [image]. static Future create(Image image) async { final Image(:toByteData, :width, :height) = image; diff --git a/packages/flame_3d/lib/src/resources/texture/texture.dart b/packages/flame_3d/lib/src/resources/texture/texture.dart index 22259c37c1e..a2df5369a7c 100644 --- a/packages/flame_3d/lib/src/resources/texture/texture.dart +++ b/packages/flame_3d/lib/src/resources/texture/texture.dart @@ -7,20 +7,12 @@ import 'package:flame_3d/resources.dart'; /// {@template texture} /// Base texture [Resource], represents an image/texture on the GPU. /// {@endtemplate} -class Texture extends Resource { - final ByteData sourceData; - final int width; - final int height; - final PixelFormat format; - - /// {@macro texture} - Texture( - this.sourceData, { - required this.width, - required this.height, - this.format = PixelFormat.rgba8888, - }); - +class Texture( + final ByteData sourceData, { + required final int width, + required final int height, + final PixelFormat format = PixelFormat.rgba8888, +}) extends Resource { @override GpuTexture createResource() { return GpuBackend.instance.createTexture( diff --git a/packages/flame_3d/pubspec.yaml b/packages/flame_3d/pubspec.yaml index 3d515362e4e..6b88c9e3a5f 100644 --- a/packages/flame_3d/pubspec.yaml +++ b/packages/flame_3d/pubspec.yaml @@ -9,8 +9,8 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.19.1 diff --git a/packages/flame_audio/example/lib/main.dart b/packages/flame_audio/example/lib/main.dart index e7944040ce8..e2bebcfde12 100644 --- a/packages/flame_audio/example/lib/main.dart +++ b/packages/flame_audio/example/lib/main.dart @@ -17,7 +17,7 @@ void main() { /// 2. Uses a custom AudioPool for extremely efficient audio loading and pooling /// for tapping elsewhere. /// 3. Uses the Bgm utility for background music. -class AudioGame extends FlameGame with TapCallbacks { +class AudioGame() extends FlameGame with TapCallbacks { static final Paint black = BasicPalette.black.paint(); static final Paint gray = const PaletteEntry(Color(0xFFCCCCCC)).paint(); static final TextPaint text = TextPaint( diff --git a/packages/flame_audio/example/pubspec.yaml b/packages/flame_audio/example/pubspec.yaml index e6b03859fdb..d39330115d2 100644 --- a/packages/flame_audio/example/pubspec.yaml +++ b/packages/flame_audio/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_audio/lib/bgm.dart b/packages/flame_audio/lib/bgm.dart index efb78f5ff59..e86dbaaecfb 100644 --- a/packages/flame_audio/lib/bgm.dart +++ b/packages/flame_audio/lib/bgm.dart @@ -10,20 +10,19 @@ import 'package:flutter/widgets.dart'; /// provided in case this functionality needs to be unloaded but the app needs /// to keep running. /// {@endtemplate} -class Bgm extends WidgetsBindingObserver { +class Bgm({AudioCache? audioCache}) extends WidgetsBindingObserver { + /// {@macro _bgm} + this; + bool _isRegistered = false; /// The [AudioPlayer] instance that is used to play the audio. - AudioPlayer audioPlayer; + AudioPlayer audioPlayer = AudioPlayer() + ..audioCache = audioCache ?? AudioCache.instance; /// Whether [Bgm] is playing or not. bool isPlaying = false; - /// {@macro _bgm} - Bgm({AudioCache? audioCache}) - : audioPlayer = AudioPlayer() - ..audioCache = audioCache ?? AudioCache.instance; - /// Registers a [WidgetsBinding] observer. /// /// This must be called for auto-pause and resume to work properly. diff --git a/packages/flame_audio/lib/flame_audio.dart b/packages/flame_audio/lib/flame_audio.dart index c2d7cee7873..b819c36de69 100644 --- a/packages/flame_audio/lib/flame_audio.dart +++ b/packages/flame_audio/lib/flame_audio.dart @@ -13,7 +13,10 @@ typedef BgmFactory = Bgm Function({required AudioCache audioCache}); /// /// You can use as a helper to very simply play a sound or a background music. /// Alternatively you can create your own instances and control them yourself. -class FlameAudio { +class FlameAudio() { + /// Creates a [FlameAudio] instance. + this; + /// The factory used to create the global [AudioCache] instance. /// /// Useful to override the default [AudioCache] constructor in testing @@ -150,7 +153,7 @@ class FlameAudio { }) async { audioContext ??= _defaultAudioContext; final path = package == null ? sound : 'packages/$package/$sound'; - return AudioPool.create( + return await AudioPool.create( source: AssetSource(path), audioCache: audioCache, minPlayers: minPlayers, diff --git a/packages/flame_audio/pubspec.yaml b/packages/flame_audio/pubspec.yaml index 6a1495f1ec7..45ea753e9db 100644 --- a/packages/flame_audio/pubspec.yaml +++ b/packages/flame_audio/pubspec.yaml @@ -13,8 +13,8 @@ topics: - audio environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: audioplayers: ^6.2.0 diff --git a/packages/flame_behavior_tree/behavior_tree/lib/behavior_tree.dart b/packages/flame_behavior_tree/behavior_tree/lib/behavior_tree.dart index fc8aca18768..2833d913921 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/behavior_tree.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/behavior_tree.dart @@ -1,5 +1,5 @@ /// Behavior tree implementation in dart -library behavior_tree; +library; export 'src/base_node.dart'; export 'src/blackboard.dart'; diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/base_node.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/base_node.dart index 052bfda1afe..e5701486bc0 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/base_node.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/base_node.dart @@ -2,7 +2,7 @@ import 'package:behavior_tree/behavior_tree.dart'; import 'package:meta/meta.dart'; /// A base class for all the nodes. -abstract class BaseNode implements NodeInterface { +abstract class BaseNode() implements NodeInterface { NodeStatus _status = NodeStatus.notStarted; /// The parent node in the behavior tree. diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard.dart index 251c1e78a77..e1c9ee84a70 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard.dart @@ -2,7 +2,7 @@ /// /// The Blackboard provides a centralized location for storing and retrieving /// data that needs to be shared between nodes in a behavior tree. -class Blackboard { +class Blackboard() { final Map _data = {}; /// Gets a value from the blackboard. diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard_provider.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard_provider.dart index 135c91a5954..e83d6756cfd 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard_provider.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/blackboard_provider.dart @@ -5,7 +5,7 @@ import 'package:behavior_tree/behavior_tree.dart'; /// This should typically be implemented by game components that have behavior /// trees, allowing the tree root to fetch the blackboard from its owning /// component. -abstract interface class BlackboardProvider { +abstract interface class BlackboardProvider() { /// Gets the blackboard for this provider. Blackboard? get blackboard; } diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart index b98c57692a9..d00997eea3e 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart @@ -1,14 +1,15 @@ import 'package:behavior_tree/behavior_tree.dart'; /// A composite node that stops at its first non-failing child node. -class Selector extends BaseNode implements NodeInterface { +class Selector({List? children}) + extends BaseNode + implements NodeInterface { /// Creates a selector node for given [children] nodes. - Selector({List? children}) - : _children = children ?? [] { + this { _children.forEach(setParent); } - final List _children; + final List _children = children ?? []; @override void tick() { diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart index 8e26f0fa693..b890562de4e 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart @@ -1,14 +1,15 @@ import 'package:behavior_tree/behavior_tree.dart'; /// A composite node that stops at its first successful child node. -class Sequence extends BaseNode implements NodeInterface { +class Sequence({List? children}) + extends BaseNode + implements NodeInterface { /// Creates a sequence node for given [children] nodes. - Sequence({List? children}) - : _children = children ?? [] { + this { _children.forEach(setParent); } - final List _children; + final List _children = children ?? []; @override void tick() { diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/inverter.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/inverter.dart index 437b88e7eda..be0316d1c06 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/inverter.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/inverter.dart @@ -2,16 +2,16 @@ import 'package:behavior_tree/behavior_tree.dart'; /// A decorator node that inverts [child]'s status if it is not /// [NodeStatus.running]. -class Inverter extends BaseNode implements NodeInterface { +class Inverter( + /// The child node whose status needs to be inverted. + final NodeInterface child, +) extends BaseNode implements NodeInterface { /// Creates an inverter node for given [child] node. - Inverter(this.child) { + this { setParent(child); _invertStatus(); } - /// The child node whose status needs to be inverted. - final NodeInterface child; - @override void tick() { child.tick(); diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart index c925b08e7a1..fc7aac3d6bd 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart @@ -1,18 +1,21 @@ import 'package:behavior_tree/behavior_tree.dart'; /// A decorator node that limits the number of times [child] can be ticked. -class Limiter extends BaseNode implements NodeInterface { +class Limiter( + /// The child node whose ticks are to be limited. + final NodeInterface child, + + /// The max number of times [child] can be ticked. + final int limit, { + final NodeStatus? _statusAfterLimit, +}) extends BaseNode implements NodeInterface { /// Creates a limiter node for given [child] node and [limit]. /// /// Once this node has been ticked [limit] number of times, it stops ticking /// the child node. After this, [status] will keep returning the status of /// child the last time it was ticked. This behavior can be overridden by /// providing an optional [_statusAfterLimit]. - Limiter( - this.child, - this.limit, { - this._statusAfterLimit, - }) { + this { setParent(child); status = (_tickCount < limit) ? child.status @@ -20,13 +23,6 @@ class Limiter extends BaseNode implements NodeInterface { } var _tickCount = 0; - final NodeStatus? _statusAfterLimit; - - /// The child node whose ticks are to be limited. - final NodeInterface child; - - /// The max number of times [child] can be ticked. - final int limit; /// Returns the number of times [child] has been ticked. int get tickCount => _tickCount; diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/node.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/node.dart index 9bed85a11af..75dfc8d540c 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/node.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/node.dart @@ -1,7 +1,7 @@ import 'package:behavior_tree/behavior_tree.dart'; /// The valid values for status of a node. -enum NodeStatus { +enum NodeStatus() { /// Indicates that the node has not been ticked yet. notStarted, @@ -18,7 +18,7 @@ enum NodeStatus { /// An interface which all the nodes implement. /// /// Some examples are [Selector], [Sequence], [Inverter] and [Limiter]. -abstract interface class NodeInterface { +abstract interface class NodeInterface() { /// Returns the current status of this node. NodeStatus get status; diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/async_task.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/async_task.dart index aa06bf49469..8f699a7a150 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/async_task.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/async_task.dart @@ -8,12 +8,9 @@ typedef AsyncTaskCallback = Future Function(); /// While the callback is executing, this node will report [status] as /// [NodeStatus.running]. Once the callback finishes, the status will be updated /// to the returned value of the callback. -class AsyncTask extends BaseNode implements NodeInterface { - /// Creates an async task node for given [callback]. - AsyncTask(AsyncTaskCallback callback) : _callback = callback; - - final AsyncTaskCallback _callback; - +class AsyncTask(final AsyncTaskCallback _callback) + extends BaseNode + implements NodeInterface { @override void tick() { if (status != NodeStatus.running) { diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/condition.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/condition.dart index 1e1c37135f1..7c1f5b6cc6c 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/condition.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/condition.dart @@ -4,13 +4,10 @@ typedef ConditionCallback = bool Function(); /// This is a leaf node that will updates its [status] based on /// [conditionCallback]. -class Condition extends BaseNode { - /// Creates a condition node for given [conditionCallback]. - Condition(this.conditionCallback); - +class Condition( /// The callback that will be executed when the condition is ticked. - final ConditionCallback conditionCallback; - + final ConditionCallback conditionCallback, +) extends BaseNode { @override void tick() { status = conditionCallback() ? NodeStatus.success : NodeStatus.failure; diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/task.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/task.dart index 7ffc147ed23..69d87e699be 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/task.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/tasks/task.dart @@ -4,14 +4,11 @@ import 'package:behavior_tree/behavior_tree.dart'; typedef TaskCallback = NodeStatus Function(); /// This is a leaf node that will execute the given task when ticked. -class Task extends BaseNode implements NodeInterface { - /// Creates a task node for given [taskCallback]. - Task(this.taskCallback); - +class Task( /// The callback that will be executed when the task is ticked. /// It should return the status of the task. - final TaskCallback taskCallback; - + final TaskCallback taskCallback, +) extends BaseNode implements NodeInterface { @override void tick() => status = taskCallback(); } diff --git a/packages/flame_behavior_tree/behavior_tree/pubspec.yaml b/packages/flame_behavior_tree/behavior_tree/pubspec.yaml index 2326558e387..3fa2fae2f12 100644 --- a/packages/flame_behavior_tree/behavior_tree/pubspec.yaml +++ b/packages/flame_behavior_tree/behavior_tree/pubspec.yaml @@ -9,7 +9,7 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: meta: ^1.12.0 diff --git a/packages/flame_behavior_tree/behavior_tree/test/blackboard_test.dart b/packages/flame_behavior_tree/behavior_tree/test/blackboard_test.dart index f6c4a8d783e..8ba3c5901e8 100644 --- a/packages/flame_behavior_tree/behavior_tree/test/blackboard_test.dart +++ b/packages/flame_behavior_tree/behavior_tree/test/blackboard_test.dart @@ -274,14 +274,10 @@ void main() { // Test helper classes -class _MockBlackboardProvider implements BlackboardProvider { - _MockBlackboardProvider(this.blackboard); +class _MockBlackboardProvider(@override final Blackboard blackboard) + implements BlackboardProvider; - @override - final Blackboard blackboard; -} - -class _TestTask extends BaseNode { +class _TestTask() extends BaseNode { int? accessedValue; @override @@ -291,7 +287,7 @@ class _TestTask extends BaseNode { } } -class _IncrementTask extends BaseNode { +class _IncrementTask() extends BaseNode { @override void tick() { final current = blackboard?.get('counter') ?? 0; @@ -300,7 +296,7 @@ class _IncrementTask extends BaseNode { } } -class _IncrementSharedTask extends BaseNode { +class _IncrementSharedTask() extends BaseNode { @override void tick() { final current = blackboard?.get('shared') ?? 0; @@ -309,7 +305,7 @@ class _IncrementSharedTask extends BaseNode { } } -class _CheckFlagTask extends BaseNode { +class _CheckFlagTask() extends BaseNode { bool wasExecuted = false; @override @@ -320,7 +316,7 @@ class _CheckFlagTask extends BaseNode { } } -class _SetFlagTask extends BaseNode { +class _SetFlagTask() extends BaseNode { @override void tick() { blackboard?.set('flag', true); @@ -328,7 +324,7 @@ class _SetFlagTask extends BaseNode { } } -class _ConditionTask extends BaseNode { +class _ConditionTask() extends BaseNode { @override void tick() { final condition = blackboard?.get('condition') ?? false; @@ -336,7 +332,7 @@ class _ConditionTask extends BaseNode { } } -class _CountExecutionTask extends BaseNode { +class _CountExecutionTask() extends BaseNode { @override void tick() { final count = blackboard?.get('executeCount') ?? 0; diff --git a/packages/flame_behavior_tree/behavior_tree/test/inverter_test.dart b/packages/flame_behavior_tree/behavior_tree/test/inverter_test.dart index e6a93c33d61..df4e8ef5ce3 100644 --- a/packages/flame_behavior_tree/behavior_tree/test/inverter_test.dart +++ b/packages/flame_behavior_tree/behavior_tree/test/inverter_test.dart @@ -42,4 +42,4 @@ void main() { }); } -class _MockNode extends Mock implements NodeInterface {} +class _MockNode() extends Mock implements NodeInterface; diff --git a/packages/flame_behavior_tree/behavior_tree/test/limiter_test.dart b/packages/flame_behavior_tree/behavior_tree/test/limiter_test.dart index 963442666c3..6325c23be56 100644 --- a/packages/flame_behavior_tree/behavior_tree/test/limiter_test.dart +++ b/packages/flame_behavior_tree/behavior_tree/test/limiter_test.dart @@ -68,4 +68,4 @@ void main() { }); } -class _MockNode extends Mock implements NodeInterface {} +class _MockNode() extends Mock implements NodeInterface; diff --git a/packages/flame_behavior_tree/behavior_tree/test/selector_test.dart b/packages/flame_behavior_tree/behavior_tree/test/selector_test.dart index baef7ef3ef2..2fff3ada3fe 100644 --- a/packages/flame_behavior_tree/behavior_tree/test/selector_test.dart +++ b/packages/flame_behavior_tree/behavior_tree/test/selector_test.dart @@ -104,14 +104,11 @@ void main() { }); } -class _MockNode extends Mock implements NodeInterface {} - -class _StatusAfterNTries extends BaseNode implements NodeInterface { - _StatusAfterNTries(this.nTries, this.statusAfterTries); - - final int nTries; - final NodeStatus statusAfterTries; +class _MockNode() extends Mock implements NodeInterface; +class _StatusAfterNTries(final int nTries, final NodeStatus statusAfterTries) + extends BaseNode + implements NodeInterface { var _tickCount = 0; int get tickCount => _tickCount; diff --git a/packages/flame_behavior_tree/behavior_tree/test/sequence_test.dart b/packages/flame_behavior_tree/behavior_tree/test/sequence_test.dart index 9d492d4e460..c7e3c9c2317 100644 --- a/packages/flame_behavior_tree/behavior_tree/test/sequence_test.dart +++ b/packages/flame_behavior_tree/behavior_tree/test/sequence_test.dart @@ -104,14 +104,11 @@ void main() { }); } -class _MockNode extends Mock implements NodeInterface {} - -class _StatusAfterNTries extends BaseNode implements NodeInterface { - _StatusAfterNTries(this.nTries, this.statusAfterTries); - - final int nTries; - final NodeStatus statusAfterTries; +class _MockNode() extends Mock implements NodeInterface; +class _StatusAfterNTries(final int nTries, final NodeStatus statusAfterTries) + extends BaseNode + implements NodeInterface { var _tickCount = 0; int get tickCount => _tickCount; diff --git a/packages/flame_behavior_tree/example/lib/main.dart b/packages/flame_behavior_tree/example/lib/main.dart index da3a3f8df05..453489f45ab 100644 --- a/packages/flame_behavior_tree/example/lib/main.dart +++ b/packages/flame_behavior_tree/example/lib/main.dart @@ -18,9 +18,7 @@ void main() { runApp(const MainApp()); } -class MainApp extends StatelessWidget { - const MainApp({super.key}); - +class const MainApp({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( @@ -39,7 +37,7 @@ class MainApp extends StatelessWidget { } } -class GameWorld extends World with HasGameRef { +class GameWorld() extends World with HasGameRef { @override Future onLoad() async { gameRef.camera.moveTo(Vector2(gameWidth * 0.5, gameHeight * 0.5)); @@ -70,9 +68,10 @@ class GameWorld extends World with HasGameRef { } } -class Door extends RectangleComponent with TapCallbacks { - Door({super.position, super.size, super.anchor}) - : super(paint: BasicPalette.brown.paint()); +class Door({super.position, super.size, super.anchor}) + extends RectangleComponent + with TapCallbacks { + this : super(paint: BasicPalette.brown.paint()); bool isOpen = false; bool _isInProgress = false; @@ -115,14 +114,14 @@ class Door extends RectangleComponent with TapCallbacks { } } -class Agent extends PositionComponent with HasBehaviorTree { - Agent({required this.door, required this.house, required Vector2 position}) - : _startPosition = position.clone(), - super(position: position); +class Agent({ + required final Door door, + required final PositionComponent house, + required Vector2 position, +}) extends PositionComponent with HasBehaviorTree { + this : super(position: position); - final Door door; - final PositionComponent house; - final Vector2 _startPosition; + final Vector2 _startPosition = position.clone(); @override Future onLoad() async { @@ -240,7 +239,7 @@ class Agent extends PositionComponent with HasBehaviorTree { // Custom behavior tree nodes that use the blackboard -class CheckMovingCondition extends BaseNode { +class CheckMovingCondition() extends BaseNode { @override void tick() { final isMoving = blackboard?.get('isMoving') ?? false; @@ -248,7 +247,7 @@ class CheckMovingCondition extends BaseNode { } } -class CheckWantsToGoOutsideCondition extends BaseNode { +class CheckWantsToGoOutsideCondition() extends BaseNode { @override void tick() { final wantsToGoOutside = blackboard?.get('wantsToGoOutside') ?? false; @@ -256,7 +255,7 @@ class CheckWantsToGoOutsideCondition extends BaseNode { } } -class CheckIsInsideCondition extends BaseNode { +class CheckIsInsideCondition() extends BaseNode { @override void tick() { final isInside = blackboard?.get('isInside') ?? false; @@ -264,7 +263,7 @@ class CheckIsInsideCondition extends BaseNode { } } -class CheckIsOutsideCondition extends BaseNode { +class CheckIsOutsideCondition() extends BaseNode { @override void tick() { final isInside = blackboard?.get('isInside') ?? false; @@ -272,20 +271,14 @@ class CheckIsOutsideCondition extends BaseNode { } } -class CheckIfDoorIsOpenCondition extends BaseNode { - CheckIfDoorIsOpenCondition(this.door); - final Door door; - +class CheckIfDoorIsOpenCondition(final Door door) extends BaseNode { @override void tick() { status = door.isOpen ? NodeStatus.success : NodeStatus.failure; } } -class KnockTheDoorTask extends BaseNode { - KnockTheDoorTask(this.door); - final Door door; - +class KnockTheDoorTask(final Door door) extends BaseNode { @override void tick() { door.knock(); @@ -293,11 +286,10 @@ class KnockTheDoorTask extends BaseNode { } } -class WalkTowardsDoorInsideTask extends BaseNode { - WalkTowardsDoorInsideTask({required this.door, required this.agent}); - final Door door; - final Agent agent; - +class WalkTowardsDoorInsideTask({ + required final Door door, + required final Agent agent, +}) extends BaseNode { @override void tick() { final isAtTheDoor = blackboard?.get('isAtTheDoor') ?? false; @@ -324,11 +316,8 @@ class WalkTowardsDoorInsideTask extends BaseNode { } } -class StepOutTheDoorTask extends BaseNode { - StepOutTheDoorTask({required this.door, required this.agent}); - final Door door; - final Agent agent; - +class StepOutTheDoorTask({required final Door door, required final Agent agent}) + extends BaseNode { @override void tick() { final isInside = blackboard?.get('isInside') ?? false; @@ -353,14 +342,10 @@ class StepOutTheDoorTask extends BaseNode { } } -class WalkTowardsInitialPositionTask extends BaseNode { - WalkTowardsInitialPositionTask({ - required this.startPosition, - required this.agent, - }); - final Vector2 startPosition; - final Agent agent; - +class WalkTowardsInitialPositionTask({ + required final Vector2 startPosition, + required final Agent agent, +}) extends BaseNode { @override void tick() { final isAtTheDoor = blackboard?.get('isAtTheDoor') ?? false; @@ -389,11 +374,10 @@ class WalkTowardsInitialPositionTask extends BaseNode { } } -class WalkTowardsDoorOutsideTask extends BaseNode { - WalkTowardsDoorOutsideTask({required this.door, required this.agent}); - final Door door; - final Agent agent; - +class WalkTowardsDoorOutsideTask({ + required final Door door, + required final Agent agent, +}) extends BaseNode { @override void tick() { final isAtTheDoor = blackboard?.get('isAtTheDoor') ?? false; @@ -418,11 +402,10 @@ class WalkTowardsDoorOutsideTask extends BaseNode { } } -class WalkTowardsCenterOfTheHouseTask extends BaseNode { - WalkTowardsCenterOfTheHouseTask({required this.house, required this.agent}); - final PositionComponent house; - final Agent agent; - +class WalkTowardsCenterOfTheHouseTask({ + required final PositionComponent house, + required final Agent agent, +}) extends BaseNode { @override void tick() { final isAtCenterOfHouse = diff --git a/packages/flame_behavior_tree/example/pubspec.yaml b/packages/flame_behavior_tree/example/pubspec.yaml index e896a9bffa0..745e090cff4 100644 --- a/packages/flame_behavior_tree/example/pubspec.yaml +++ b/packages/flame_behavior_tree/example/pubspec.yaml @@ -9,7 +9,7 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_behavior_tree/lib/flame_behavior_tree.dart b/packages/flame_behavior_tree/lib/flame_behavior_tree.dart index e90ce54b309..7b0e7dba3a1 100644 --- a/packages/flame_behavior_tree/lib/flame_behavior_tree.dart +++ b/packages/flame_behavior_tree/lib/flame_behavior_tree.dart @@ -1,5 +1,6 @@ /// A bridge package that integrates behavior_tree package with flame. -library flame_behavior_tree; +library; export 'package:behavior_tree/behavior_tree.dart'; + export 'src/has_behavior_tree.dart'; diff --git a/packages/flame_behavior_tree/pubspec.yaml b/packages/flame_behavior_tree/pubspec.yaml index 04d89b0b340..40aa751ba24 100644 --- a/packages/flame_behavior_tree/pubspec.yaml +++ b/packages/flame_behavior_tree/pubspec.yaml @@ -11,8 +11,8 @@ topics: - flame environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: behavior_tree: ^0.1.6-dev.0+2 diff --git a/packages/flame_behavior_tree/test/has_behavior_tree_test.dart b/packages/flame_behavior_tree/test/has_behavior_tree_test.dart index e7930790cf5..dcaf7dc5fca 100644 --- a/packages/flame_behavior_tree/test/has_behavior_tree_test.dart +++ b/packages/flame_behavior_tree/test/has_behavior_tree_test.dart @@ -277,13 +277,13 @@ void main() { }); } -class _BehaviorTreeComponent extends Component with HasBehaviorTree {} +class _BehaviorTreeComponent() extends Component with HasBehaviorTree; -class _MockNode extends Mock implements NodeInterface {} +class _MockNode() extends Mock implements NodeInterface; // Test helper nodes for blackboard testing -class _TestTask extends BaseNode { +class _TestTask() extends BaseNode { Object? retrievedValue; @override @@ -299,7 +299,7 @@ class _TestTask extends BaseNode { } } -class _IncrementTask extends BaseNode { +class _IncrementTask() extends BaseNode { @override void tick() { final current = blackboard?.get('counter') ?? 0; @@ -308,7 +308,7 @@ class _IncrementTask extends BaseNode { } } -class _IncrementSharedTask extends BaseNode { +class _IncrementSharedTask() extends BaseNode { @override void tick() { final current = blackboard?.get('shared') ?? 0; diff --git a/packages/flame_behaviors/example/lib/behaviors/spawning_behavior.dart b/packages/flame_behaviors/example/lib/behaviors/spawning_behavior.dart index 4a727617d87..1f9a63ca958 100644 --- a/packages/flame_behaviors/example/lib/behaviors/spawning_behavior.dart +++ b/packages/flame_behaviors/example/lib/behaviors/spawning_behavior.dart @@ -6,7 +6,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/entities/entities.dart'; import 'package:flame_behaviors_example/main.dart'; -class SpawningBehavior extends TappableBehavior { +class SpawningBehavior() extends TappableBehavior { final _rng = Random(); @override @@ -46,4 +46,7 @@ class SpawningBehavior extends TappableBehavior { } } -enum Shapes { circle, rectangle } +enum Shapes() { + circle, + rectangle, +} diff --git a/packages/flame_behaviors/example/lib/entities/behaviors/moving_behavior.dart b/packages/flame_behaviors/example/lib/entities/behaviors/moving_behavior.dart index f4172f6c491..52732504c45 100644 --- a/packages/flame_behaviors/example/lib/entities/behaviors/moving_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/behaviors/moving_behavior.dart @@ -1,11 +1,8 @@ import 'package:flame/extensions.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; -class MovingBehavior extends Behavior { - MovingBehavior({required this.velocity}); - - final Vector2 velocity; - +class MovingBehavior({required final Vector2 velocity}) + extends Behavior { @override void update(double dt) { parent.position.add(velocity * dt); diff --git a/packages/flame_behaviors/example/lib/entities/behaviors/rotating_behavior.dart b/packages/flame_behaviors/example/lib/entities/behaviors/rotating_behavior.dart index 7a4a285ef34..2010470eec3 100644 --- a/packages/flame_behaviors/example/lib/entities/behaviors/rotating_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/behaviors/rotating_behavior.dart @@ -4,11 +4,9 @@ import 'dart:math'; import 'package:flame/components.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; -class RotatingBehavior extends Behavior with HasGameRef { - RotatingBehavior({required this.rotationSpeed}); - - final double rotationSpeed; - +class RotatingBehavior({required final double rotationSpeed}) + extends Behavior + with HasGameRef { late final ScreenHitbox screenHitbox; @override diff --git a/packages/flame_behaviors/example/lib/entities/behaviors/screen_colliding_behavior.dart b/packages/flame_behaviors/example/lib/entities/behaviors/screen_colliding_behavior.dart index f51f61586be..d6703b8f9be 100644 --- a/packages/flame_behaviors/example/lib/entities/behaviors/screen_colliding_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/behaviors/screen_colliding_behavior.dart @@ -3,7 +3,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; /// Simplified "screen wrapping" behavior, while not perfect it does showcase /// the possibility of acting on collision with non-entities. -class ScreenCollidingBehavior +class ScreenCollidingBehavior() extends CollisionBehavior { @override void onCollisionEnd(ScreenHitbox other) { diff --git a/packages/flame_behaviors/example/lib/entities/circle/behaviors/circle_collision_behavior.dart b/packages/flame_behaviors/example/lib/entities/circle/behaviors/circle_collision_behavior.dart index e8148f357c9..48334fc2b40 100644 --- a/packages/flame_behaviors/example/lib/entities/circle/behaviors/circle_collision_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/circle/behaviors/circle_collision_behavior.dart @@ -3,7 +3,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/entities/entities.dart'; import 'package:material_ui/material_ui.dart'; -class CircleCollisionBehavior extends CollisionBehavior { +class CircleCollisionBehavior() extends CollisionBehavior { final _collisionColor = Colors.green.withValues(alpha: 0.8); @override diff --git a/packages/flame_behaviors/example/lib/entities/circle/behaviors/dragging_behavior.dart b/packages/flame_behaviors/example/lib/entities/circle/behaviors/dragging_behavior.dart index f419ecc5c70..e3d42cd6372 100644 --- a/packages/flame_behaviors/example/lib/entities/circle/behaviors/dragging_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/circle/behaviors/dragging_behavior.dart @@ -3,7 +3,7 @@ import 'package:flame/extensions.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/entities/entities.dart'; -class DraggingBehavior extends DraggableBehavior { +class DraggingBehavior() extends DraggableBehavior { MovingBehavior? movement; Vector2? originalVelocity; diff --git a/packages/flame_behaviors/example/lib/entities/circle/behaviors/rectangle_collision_behavior.dart b/packages/flame_behaviors/example/lib/entities/circle/behaviors/rectangle_collision_behavior.dart index f45a28921e5..b425ccc4679 100644 --- a/packages/flame_behaviors/example/lib/entities/circle/behaviors/rectangle_collision_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/circle/behaviors/rectangle_collision_behavior.dart @@ -3,7 +3,8 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/entities/entities.dart'; import 'package:material_ui/material_ui.dart'; -class RectangleCollisionBehavior extends CollisionBehavior { +class RectangleCollisionBehavior() + extends CollisionBehavior { final _collisionColor = Colors.yellow.withValues(alpha: 0.8); @override diff --git a/packages/flame_behaviors/example/lib/entities/circle/behaviors/tapping_behavior.dart b/packages/flame_behaviors/example/lib/entities/circle/behaviors/tapping_behavior.dart index d0317a07c02..f3b29cd1a93 100644 --- a/packages/flame_behaviors/example/lib/entities/circle/behaviors/tapping_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/circle/behaviors/tapping_behavior.dart @@ -8,7 +8,7 @@ import 'package:flame_behaviors_example/entities/entities.dart'; /// It does so simply by existing: the tap is delivered to this behavior, and /// since it does not set `continuePropagation`, it never reaches the game-level /// SpawningBehavior underneath. -class TappingBehavior extends TappableBehavior { +class TappingBehavior() extends TappableBehavior { @override void onTapDown(TapDownEvent event) {} } diff --git a/packages/flame_behaviors/example/lib/entities/circle/circle.dart b/packages/flame_behaviors/example/lib/entities/circle/circle.dart index f0435cb2def..5ed0a63977b 100644 --- a/packages/flame_behaviors/example/lib/entities/circle/circle.dart +++ b/packages/flame_behaviors/example/lib/entities/circle/circle.dart @@ -7,25 +7,26 @@ import 'package:flame_behaviors_example/entities/circle/behaviors/behaviors.dart import 'package:flame_behaviors_example/entities/entities.dart'; import 'package:material_ui/material_ui.dart'; -class Circle extends PositionedEntity with HasPaint { - Circle({ - required double rotationSpeed, - required Vector2 velocity, - super.position, - super.size, - }) : super( - anchor: Anchor.center, - behaviors: [ - PropagatingCollisionBehavior(CircleHitbox()), - CircleCollisionBehavior(), - RectangleCollisionBehavior(), - ScreenCollidingBehavior(), - MovingBehavior(velocity: velocity), - RotatingBehavior(rotationSpeed: rotationSpeed), - TappingBehavior(), - DraggingBehavior(), - ], - ); +class Circle({ + required double rotationSpeed, + required Vector2 velocity, + super.position, + super.size, +}) extends PositionedEntity with HasPaint { + this + : super( + anchor: Anchor.center, + behaviors: [ + PropagatingCollisionBehavior(CircleHitbox()), + CircleCollisionBehavior(), + RectangleCollisionBehavior(), + ScreenCollidingBehavior(), + MovingBehavior(velocity: velocity), + RotatingBehavior(rotationSpeed: rotationSpeed), + TappingBehavior(), + DraggingBehavior(), + ], + ); final defaultColor = Colors.blue.withValues(alpha: 0.8); diff --git a/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/circle_colliding_behavior.dart b/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/circle_colliding_behavior.dart index 3a560c2510b..d2dc8b65c77 100644 --- a/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/circle_colliding_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/circle_colliding_behavior.dart @@ -3,7 +3,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/entities/entities.dart'; import 'package:material_ui/material_ui.dart'; -class CircleCollidingBehavior extends CollisionBehavior { +class CircleCollidingBehavior() extends CollisionBehavior { final _collisionColor = Colors.green.withValues(alpha: 0.8); @override diff --git a/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/freezing_behavior.dart b/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/freezing_behavior.dart index c2c45867933..b0acf41608c 100644 --- a/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/freezing_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/freezing_behavior.dart @@ -3,7 +3,7 @@ import 'package:flame/extensions.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/entities/entities.dart'; -class FreezingBehavior extends TappableBehavior { +class FreezingBehavior() extends TappableBehavior { MovingBehavior? movement; Vector2? originalVelocity; diff --git a/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/rectangle_colliding_behavior.dart b/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/rectangle_colliding_behavior.dart index c603403c7c4..898c469cc63 100644 --- a/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/rectangle_colliding_behavior.dart +++ b/packages/flame_behaviors/example/lib/entities/rectangle/behaviors/rectangle_colliding_behavior.dart @@ -3,7 +3,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/entities/entities.dart'; import 'package:material_ui/material_ui.dart'; -class RectangleCollidingBehavior +class RectangleCollidingBehavior() extends CollisionBehavior { final _collisionColor = Colors.yellow.withValues(alpha: 0.8); diff --git a/packages/flame_behaviors/example/lib/entities/rectangle/rectangle.dart b/packages/flame_behaviors/example/lib/entities/rectangle/rectangle.dart index 509d82ff9b4..59f08542757 100644 --- a/packages/flame_behaviors/example/lib/entities/rectangle/rectangle.dart +++ b/packages/flame_behaviors/example/lib/entities/rectangle/rectangle.dart @@ -5,24 +5,25 @@ import 'package:flame_behaviors_example/entities/entities.dart'; import 'package:flame_behaviors_example/entities/rectangle/behaviors/behaviors.dart'; import 'package:material_ui/material_ui.dart'; -class Rectangle extends PositionedEntity with HasPaint { - Rectangle({ - required double rotationSpeed, - required Vector2 velocity, - super.position, - super.size, - }) : super( - anchor: Anchor.center, - behaviors: [ - PropagatingCollisionBehavior(RectangleHitbox()), - RectangleCollidingBehavior(), - CircleCollidingBehavior(), - ScreenCollidingBehavior(), - MovingBehavior(velocity: velocity), - RotatingBehavior(rotationSpeed: rotationSpeed), - FreezingBehavior(), - ], - ); +class Rectangle({ + required double rotationSpeed, + required Vector2 velocity, + super.position, + super.size, +}) extends PositionedEntity with HasPaint { + this + : super( + anchor: Anchor.center, + behaviors: [ + PropagatingCollisionBehavior(RectangleHitbox()), + RectangleCollidingBehavior(), + CircleCollidingBehavior(), + ScreenCollidingBehavior(), + MovingBehavior(velocity: velocity), + RotatingBehavior(rotationSpeed: rotationSpeed), + FreezingBehavior(), + ], + ); final defaultColor = Colors.red.withValues(alpha: 0.8); diff --git a/packages/flame_behaviors/example/lib/main.dart b/packages/flame_behaviors/example/lib/main.dart index cb1709e937d..85b186f0a7a 100644 --- a/packages/flame_behaviors/example/lib/main.dart +++ b/packages/flame_behaviors/example/lib/main.dart @@ -4,7 +4,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_behaviors_example/behaviors/behaviors.dart'; import 'package:material_ui/material_ui.dart'; -class ExampleGame extends FlameGame with EntityMixin, HasCollisionDetection { +class ExampleGame() extends FlameGame with EntityMixin, HasCollisionDetection { @override Future onLoad() async { add(FpsTextComponent(position: Vector2.zero())); @@ -13,7 +13,7 @@ class ExampleGame extends FlameGame with EntityMixin, HasCollisionDetection { // Game-specific behaviors add(SpawningBehavior()); - return super.onLoad(); + await super.onLoad(); } } diff --git a/packages/flame_behaviors/example/pubspec.yaml b/packages/flame_behaviors/example/pubspec.yaml index 34fea6f6db4..574c55c9fc6 100644 --- a/packages/flame_behaviors/example/pubspec.yaml +++ b/packages/flame_behaviors/example/pubspec.yaml @@ -5,7 +5,7 @@ version: 1.0.0+1 publish_to: none environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_behaviors/lib/src/behaviors/behavior.dart b/packages/flame_behaviors/lib/src/behaviors/behavior.dart index 9dc7dac45a5..939211d3b78 100644 --- a/packages/flame_behaviors/lib/src/behaviors/behavior.dart +++ b/packages/flame_behaviors/lib/src/behaviors/behavior.dart @@ -8,11 +8,11 @@ import 'package:flame_behaviors/flame_behaviors.dart'; /// A behavior can have it's own [Component]s for adding extra functionality /// related to the behavior. It cannot, however, have its own [Behavior]s. /// {@endtemplate} -abstract class Behavior extends Component - with ParentIsA { - /// {@macro behavior} - Behavior({super.children, super.priority, super.key}); - +abstract class Behavior({ + super.children, + super.priority, + super.key, +}) extends Component with ParentIsA { @override void add(Component component) { assert(component is! EntityMixin, 'Behaviors cannot have entities.'); diff --git a/packages/flame_behaviors/lib/src/behaviors/events/draggable_behavior.dart b/packages/flame_behaviors/lib/src/behaviors/events/draggable_behavior.dart index a0782e00873..9954ebcf805 100644 --- a/packages/flame_behaviors/lib/src/behaviors/events/draggable_behavior.dart +++ b/packages/flame_behaviors/lib/src/behaviors/events/draggable_behavior.dart @@ -4,9 +4,8 @@ import 'package:flame_behaviors/flame_behaviors.dart'; /// {@template draggable_behavior} /// A behavior that makes an [Entity] draggable. /// {@endtemplate} -abstract class DraggableBehavior - extends Behavior - with DragCallbacks { - /// {@macro draggable_behavior} - DraggableBehavior({super.children, super.priority, super.key}); -} +abstract class DraggableBehavior({ + super.children, + super.priority, + super.key, +}) extends Behavior with DragCallbacks; diff --git a/packages/flame_behaviors/lib/src/behaviors/events/hoverable_behavior.dart b/packages/flame_behaviors/lib/src/behaviors/events/hoverable_behavior.dart index 522c5701b23..42992ec3713 100644 --- a/packages/flame_behaviors/lib/src/behaviors/events/hoverable_behavior.dart +++ b/packages/flame_behaviors/lib/src/behaviors/events/hoverable_behavior.dart @@ -8,9 +8,8 @@ import 'package:flame_behaviors/flame_behaviors.dart'; /// handles propagation of hover events from the root game to individual /// behaviors. /// {@endtemplate} -abstract class HoverableBehavior - extends Behavior - with HoverCallbacks { - /// {@macro hoverable_behavior} - HoverableBehavior({super.children, super.priority, super.key}); -} +abstract class HoverableBehavior({ + super.children, + super.priority, + super.key, +}) extends Behavior with HoverCallbacks; diff --git a/packages/flame_behaviors/lib/src/behaviors/events/tappable_behavior.dart b/packages/flame_behaviors/lib/src/behaviors/events/tappable_behavior.dart index 90c6fb29e3b..89559468ebb 100644 --- a/packages/flame_behaviors/lib/src/behaviors/events/tappable_behavior.dart +++ b/packages/flame_behaviors/lib/src/behaviors/events/tappable_behavior.dart @@ -4,9 +4,8 @@ import 'package:flame_behaviors/flame_behaviors.dart'; /// {@template tappable_behavior} /// A behavior that makes an [Entity] tappable. /// {@endtemplate} -abstract class TappableBehavior - extends Behavior - with TapCallbacks { - /// {@macro tappable_behavior} - TappableBehavior({super.children, super.priority, super.key}); -} +abstract class TappableBehavior({ + super.children, + super.priority, + super.key, +}) extends Behavior with TapCallbacks; diff --git a/packages/flame_behaviors/lib/src/behaviors/propagating_collision_behavior.dart b/packages/flame_behaviors/lib/src/behaviors/propagating_collision_behavior.dart index a9ea68fb91c..a12d28db22b 100644 --- a/packages/flame_behaviors/lib/src/behaviors/propagating_collision_behavior.dart +++ b/packages/flame_behaviors/lib/src/behaviors/propagating_collision_behavior.dart @@ -11,11 +11,7 @@ import 'package:flutter/foundation.dart'; abstract class CollisionBehavior< Collider extends Component, Parent extends EntityMixin -> - extends Behavior { - /// {@macro collision_behavior} - CollisionBehavior({super.children, super.priority, super.key}); - +>({super.children, super.priority, super.key}) extends Behavior { /// Check if the given component is an instance of [Collider]. bool isValid(Component c) => c is Collider; @@ -68,14 +64,13 @@ abstract class CollisionBehavior< /// [PositionedEntity] which does exactly that but any kind of position /// component will work. /// {@endtemplate} -class PropagatingCollisionBehavior - extends Behavior - with CollisionCallbacks { +class PropagatingCollisionBehavior( + final ShapeHitbox _hitbox, { + super.priority, + super.key, +}) extends Behavior with CollisionCallbacks { /// {@macro propagating_collision_behavior} - PropagatingCollisionBehavior(this._hitbox, {super.priority, super.key}) - : super(children: [_hitbox]); - - final ShapeHitbox _hitbox; + this : super(children: [_hitbox]); @override @mustCallSuper diff --git a/packages/flame_behaviors/lib/src/behaviors/screen_collision_behavior.dart b/packages/flame_behaviors/lib/src/behaviors/screen_collision_behavior.dart index 39c82159cdf..38523b4b342 100644 --- a/packages/flame_behaviors/lib/src/behaviors/screen_collision_behavior.dart +++ b/packages/flame_behaviors/lib/src/behaviors/screen_collision_behavior.dart @@ -28,8 +28,8 @@ import 'package:flame_behaviors/flame_behaviors.dart'; /// [PropagatingCollisionBehavior] and the game to register a /// [ScreenHitbox] for the screen edges. /// {@endtemplate} -abstract class ScreenCollisionBehavior - extends CollisionBehavior { - /// {@macro screen_collision_behavior} - ScreenCollisionBehavior({super.children, super.priority, super.key}); -} +abstract class ScreenCollisionBehavior({ + super.children, + super.priority, + super.key, +}) extends CollisionBehavior; diff --git a/packages/flame_behaviors/lib/src/entity.dart b/packages/flame_behaviors/lib/src/entity.dart index 5dc658d788a..f58d364fc52 100644 --- a/packages/flame_behaviors/lib/src/entity.dart +++ b/packages/flame_behaviors/lib/src/entity.dart @@ -62,17 +62,18 @@ mixin EntityMixin on Component { /// The visualization of the entity is defined by the [Component]s that are /// attached to it. /// {@endtemplate} -abstract class Entity extends Component with EntityMixin { +abstract class Entity({ + super.children, + super.priority, + super.key, + Iterable? behaviors, +}) extends Component with EntityMixin { /// {@macro entity} - Entity({ - super.children, - super.priority, - super.key, - Iterable? behaviors, - }) : assert( - children?.whereType().isEmpty ?? true, - 'Behaviors cannot be added to as a child directly.', - ) { + this + : assert( + children?.whereType().isEmpty ?? true, + 'Behaviors cannot be added to as a child directly.', + ) { if (behaviors != null) { addAll(behaviors); } @@ -85,23 +86,24 @@ abstract class Entity extends Component with EntityMixin { /// This entity is based on the [PositionComponent] and can be positioned /// on the screen. /// {@endtemplate} -abstract class PositionedEntity extends PositionComponent with EntityMixin { +abstract class PositionedEntity({ + super.position, + super.size, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, + Iterable? behaviors, +}) extends PositionComponent with EntityMixin { /// {@macro positioned_entity} - PositionedEntity({ - super.position, - super.size, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - Iterable? behaviors, - }) : assert( - children?.whereType().isEmpty ?? true, - 'Behaviors cannot be added to as a child directly.', - ) { + this + : assert( + children?.whereType().isEmpty ?? true, + 'Behaviors cannot be added to as a child directly.', + ) { if (behaviors != null) { addAll(behaviors); } diff --git a/packages/flame_behaviors/pubspec.yaml b/packages/flame_behaviors/pubspec.yaml index ca5a98e5722..bc5bc153430 100644 --- a/packages/flame_behaviors/pubspec.yaml +++ b/packages/flame_behaviors/pubspec.yaml @@ -5,8 +5,8 @@ version: 2.0.0-dev.0 homepage: https://github.com/flame-engine/flame/tree/main/packages/flame_behaviors environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_behaviors/test/src/behaviors/behavior_test.dart b/packages/flame_behaviors/test/src/behaviors/behavior_test.dart index 90e3b7885cd..4ab60fcd8e4 100644 --- a/packages/flame_behaviors/test/src/behaviors/behavior_test.dart +++ b/packages/flame_behaviors/test/src/behaviors/behavior_test.dart @@ -3,11 +3,11 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _TestEntity extends PositionedEntity { - _TestEntity({super.behaviors}) : super(size: Vector2.all(32)); +class _TestEntity({super.behaviors}) extends PositionedEntity { + this : super(size: Vector2.all(32)); } -class _TestBehavior extends Behavior<_TestEntity> {} +class _TestBehavior() extends Behavior<_TestEntity>; void main() { group('Behavior', () { diff --git a/packages/flame_behaviors/test/src/behaviors/events/draggable_behavior_test.dart b/packages/flame_behaviors/test/src/behaviors/events/draggable_behavior_test.dart index 98fdc0ed9cc..3b368fcc8a2 100644 --- a/packages/flame_behaviors/test/src/behaviors/events/draggable_behavior_test.dart +++ b/packages/flame_behaviors/test/src/behaviors/events/draggable_behavior_test.dart @@ -1,7 +1,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter_test/flutter_test.dart'; -class _TestBehavior extends DraggableBehavior {} +class _TestBehavior() extends DraggableBehavior; void main() { group('$DraggableBehavior', () { diff --git a/packages/flame_behaviors/test/src/behaviors/events/hoverable_behavior_test.dart b/packages/flame_behaviors/test/src/behaviors/events/hoverable_behavior_test.dart index a1690cfd0c9..271eb72378f 100644 --- a/packages/flame_behaviors/test/src/behaviors/events/hoverable_behavior_test.dart +++ b/packages/flame_behaviors/test/src/behaviors/events/hoverable_behavior_test.dart @@ -1,7 +1,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter_test/flutter_test.dart'; -class _TestBehavior extends HoverableBehavior {} +class _TestBehavior() extends HoverableBehavior; void main() { group('$HoverableBehavior', () { diff --git a/packages/flame_behaviors/test/src/behaviors/events/tappable_behavior_test.dart b/packages/flame_behaviors/test/src/behaviors/events/tappable_behavior_test.dart index 0e543521660..ef5d265fc64 100644 --- a/packages/flame_behaviors/test/src/behaviors/events/tappable_behavior_test.dart +++ b/packages/flame_behaviors/test/src/behaviors/events/tappable_behavior_test.dart @@ -1,7 +1,7 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter_test/flutter_test.dart'; -class _TestBehavior extends TappableBehavior {} +class _TestBehavior() extends TappableBehavior; void main() { group('$TappableBehavior', () { diff --git a/packages/flame_behaviors/test/src/behaviors/propagating_collision_behavior_test.dart b/packages/flame_behaviors/test/src/behaviors/propagating_collision_behavior_test.dart index d577019b56f..126f117df98 100644 --- a/packages/flame_behaviors/test/src/behaviors/propagating_collision_behavior_test.dart +++ b/packages/flame_behaviors/test/src/behaviors/propagating_collision_behavior_test.dart @@ -5,27 +5,24 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _EntityA extends PositionedEntity { - _EntityA({super.behaviors}) : super(size: Vector2.all(16)); +class _EntityA({super.behaviors}) extends PositionedEntity { + this : super(size: Vector2.all(16)); } -class _EntityB extends PositionedEntity { - _EntityB({super.behaviors}) : super(size: Vector2.all(16)); +class _EntityB({super.behaviors}) extends PositionedEntity { + this : super(size: Vector2.all(16)); } -class _EntityC extends PositionedEntity { - _EntityC() : super(size: Vector2.all(16)); +class _EntityC() extends PositionedEntity { + this : super(size: Vector2.all(16)); } -class _EntityD extends Entity { - _EntityD(); -} +class _EntityD() extends Entity; abstract class _CollisionBehavior< A extends Component, B extends PositionedEntity -> - extends CollisionBehavior { +>() extends CollisionBehavior { bool onCollisionStartCalled = false; bool onCollisionCalled = false; bool onCollisionEndCalled = false; @@ -49,14 +46,14 @@ abstract class _CollisionBehavior< } } -class _CollisionBehaviorAtoB extends _CollisionBehavior<_EntityB, _EntityA> {} +class _CollisionBehaviorAtoB() extends _CollisionBehavior<_EntityB, _EntityA>; -class _CollisionBehaviorAtoC extends _CollisionBehavior<_EntityC, _EntityA> {} +class _CollisionBehaviorAtoC() extends _CollisionBehavior<_EntityC, _EntityA>; -class _CollisionBehaviorAtoComponent - extends _CollisionBehavior {} +class _CollisionBehaviorAtoComponent() + extends _CollisionBehavior; -class _TestGame extends FlameGame with HasCollisionDetection {} +class _TestGame() extends FlameGame with HasCollisionDetection; void main() { final flameTester = FlameTester(_TestGame.new); diff --git a/packages/flame_behaviors/test/src/behaviors/screen_collision_behavior_test.dart b/packages/flame_behaviors/test/src/behaviors/screen_collision_behavior_test.dart index 6e52ba7ddea..20cbf04020b 100644 --- a/packages/flame_behaviors/test/src/behaviors/screen_collision_behavior_test.dart +++ b/packages/flame_behaviors/test/src/behaviors/screen_collision_behavior_test.dart @@ -5,12 +5,11 @@ import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _Entity extends PositionedEntity { - _Entity({super.behaviors, super.position}) - : super(size: Vector2.all(16), anchor: Anchor.center); +class _Entity({super.behaviors, super.position}) extends PositionedEntity { + this : super(size: Vector2.all(16), anchor: Anchor.center); } -class _TrackingScreenCollisionBehavior +class _TrackingScreenCollisionBehavior() extends ScreenCollisionBehavior<_Entity> { bool startCalled = false; bool collisionCalled = false; @@ -37,8 +36,8 @@ class _TrackingScreenCollisionBehavior } } -class _TestGame extends FlameGame with HasCollisionDetection { - _TestGame() : super(children: [ScreenHitbox()]); +class _TestGame() extends FlameGame with HasCollisionDetection { + this : super(children: [ScreenHitbox()]); } void main() { diff --git a/packages/flame_behaviors/test/src/entity_test.dart b/packages/flame_behaviors/test/src/entity_test.dart index 27c3f344502..387742b1226 100644 --- a/packages/flame_behaviors/test/src/entity_test.dart +++ b/packages/flame_behaviors/test/src/entity_test.dart @@ -4,11 +4,9 @@ import 'package:flutter_test/flutter_test.dart'; import '../helpers/helpers.dart'; -class _TestEntity extends Entity { - _TestEntity({super.behaviors}); -} +class _TestEntity({super.behaviors}) extends Entity; -class _TestBehavior extends Behavior<_TestEntity> {} +class _TestBehavior() extends Behavior<_TestEntity>; void main() { group('Entity', () { diff --git a/packages/flame_bloc/example/lib/main.dart b/packages/flame_bloc/example/lib/main.dart index 1c7c5f444c4..cce7130e895 100644 --- a/packages/flame_bloc/example/lib/main.dart +++ b/packages/flame_bloc/example/lib/main.dart @@ -5,9 +5,7 @@ void main() { runApp(const MyApp()); } -class MyApp extends StatelessWidget { - const MyApp({super.key}); - +class const MyApp({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return const MaterialApp( diff --git a/packages/flame_bloc/example/lib/src/game.dart b/packages/flame_bloc/example/lib/src/game.dart index 0c8c3a7455e..7cd6e59d396 100644 --- a/packages/flame_bloc/example/lib/src/game.dart +++ b/packages/flame_bloc/example/lib/src/game.dart @@ -7,9 +7,7 @@ import 'package:flame_bloc_example/src/inventory/view/inventory.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:material_ui/material_ui.dart'; -class GamePage extends StatelessWidget { - const GamePage({super.key}); - +class const GamePage({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( @@ -24,9 +22,7 @@ class GamePage extends StatelessWidget { } } -class GameView extends StatelessWidget { - const GameView({super.key}); - +class const GameView({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return const Column( @@ -45,9 +41,7 @@ class GameView extends StatelessWidget { } } -class Game extends StatelessWidget { - const Game({super.key}); - +class const Game({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return GameWidget( diff --git a/packages/flame_bloc/example/lib/src/game/components/bullet.dart b/packages/flame_bloc/example/lib/src/game/components/bullet.dart index 552190c89ef..48da23f1337 100644 --- a/packages/flame_bloc/example/lib/src/game/components/bullet.dart +++ b/packages/flame_bloc/example/lib/src/game/components/bullet.dart @@ -4,22 +4,18 @@ import 'package:flame_bloc_example/src/game/components/enemy.dart'; import 'package:flame_bloc_example/src/game/game.dart'; import 'package:flame_bloc_example/src/inventory/bloc/inventory_bloc.dart'; -class BulletComponent extends SpriteAnimationComponent +class BulletComponent( + double x, + double y, + final Weapon weapon, { + var double xDirection = 0.0, +}) extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks { static const bulletSpeed = -500; bool destroyed = false; - double xDirection; - - final Weapon weapon; - - BulletComponent( - double x, - double y, - this.weapon, { - this.xDirection = 0.0, - }) : super(position: Vector2(x, y)) { + this : super(position: Vector2(x, y)) { size = Vector2(_mapWidth(), 20); add(RectangleHitbox()); diff --git a/packages/flame_bloc/example/lib/src/game/components/enemy.dart b/packages/flame_bloc/example/lib/src/game/components/enemy.dart index 8cfa36d6474..245c2973ac3 100644 --- a/packages/flame_bloc/example/lib/src/game/components/enemy.dart +++ b/packages/flame_bloc/example/lib/src/game/components/enemy.dart @@ -4,14 +4,14 @@ import 'package:flame/components.dart'; import 'package:flame_bloc_example/src/game/components/explosion.dart'; import 'package:flame_bloc_example/src/game/game.dart'; -class EnemyComponent extends SpriteAnimationComponent +class EnemyComponent(double x, double y) + extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks { static const enemySpeed = 50; bool destroyed = false; - EnemyComponent(double x, double y) - : super(position: Vector2(x, y), size: Vector2.all(25)) { + this : super(position: Vector2(x, y), size: Vector2.all(25)) { add(RectangleHitbox(collisionType: CollisionType.passive)); } diff --git a/packages/flame_bloc/example/lib/src/game/components/enemy_creator.dart b/packages/flame_bloc/example/lib/src/game/components/enemy_creator.dart index 9c3de8d68bd..bc081db2552 100644 --- a/packages/flame_bloc/example/lib/src/game/components/enemy_creator.dart +++ b/packages/flame_bloc/example/lib/src/game/components/enemy_creator.dart @@ -5,10 +5,10 @@ import 'package:flame/components.dart'; import 'package:flame_bloc_example/src/game/components/enemy.dart'; import 'package:flame_bloc_example/src/game/game.dart'; -class EnemyCreator extends TimerComponent with HasGameRef { +class EnemyCreator() extends TimerComponent with HasGameRef { Random random = Random(); - EnemyCreator() : super(period: 1, repeat: true) { + this : super(period: 1, repeat: true) { timer.onTick = _spawn; } diff --git a/packages/flame_bloc/example/lib/src/game/components/explosion.dart b/packages/flame_bloc/example/lib/src/game/components/explosion.dart index f6bdab54ca0..35de8f4c173 100644 --- a/packages/flame_bloc/example/lib/src/game/components/explosion.dart +++ b/packages/flame_bloc/example/lib/src/game/components/explosion.dart @@ -2,9 +2,10 @@ import 'package:flame/components.dart'; import 'package:flame_bloc_example/src/game/game.dart'; -class ExplosionComponent extends SpriteAnimationComponent +class ExplosionComponent(double x, double y) + extends SpriteAnimationComponent with HasGameRef { - ExplosionComponent(double x, double y) + this : super( position: Vector2(x, y), size: Vector2.all(50), diff --git a/packages/flame_bloc/example/lib/src/game/components/player.dart b/packages/flame_bloc/example/lib/src/game/components/player.dart index 0a906a09d97..f9a151987a8 100644 --- a/packages/flame_bloc/example/lib/src/game/components/player.dart +++ b/packages/flame_bloc/example/lib/src/game/components/player.dart @@ -9,7 +9,8 @@ import 'package:flame_bloc_example/src/game_stats/bloc/game_stats_bloc.dart'; import 'package:flame_bloc_example/src/inventory/bloc/inventory_bloc.dart'; import 'package:flutter/services.dart'; -class PlayerController extends Component +class PlayerController() + extends Component with HasGameRef, FlameBlocListenable { @@ -28,7 +29,8 @@ class PlayerController extends Component } } -class PlayerComponent extends SpriteAnimationComponent +class PlayerComponent() + extends SpriteAnimationComponent with HasGameRef, CollisionCallbacks, @@ -37,8 +39,7 @@ class PlayerComponent extends SpriteAnimationComponent bool destroyed = false; late Timer bulletCreator; - PlayerComponent() - : super(size: Vector2(50, 75), position: Vector2(100, 500)) { + this : super(size: Vector2(50, 75), position: Vector2(100, 500)) { bulletCreator = Timer(period: 0.5, repeat: true, onTick: _createBullet); add(RectangleHitbox()); diff --git a/packages/flame_bloc/example/lib/src/game/game.dart b/packages/flame_bloc/example/lib/src/game/game.dart index 2948d698558..a63908a80f1 100644 --- a/packages/flame_bloc/example/lib/src/game/game.dart +++ b/packages/flame_bloc/example/lib/src/game/game.dart @@ -8,7 +8,9 @@ import 'package:flame_bloc_example/src/game/components/player.dart'; import 'package:flame_bloc_example/src/game_stats/bloc/game_stats_bloc.dart'; import 'package:flame_bloc_example/src/inventory/bloc/inventory_bloc.dart'; -class GameStatsController extends Component with HasGameRef { +class GameStatsController() + extends Component + with HasGameRef { @override Future? onLoad() async { add( @@ -25,18 +27,13 @@ class GameStatsController extends Component with HasGameRef { } } -class SpaceShooterGame extends FlameGame +class SpaceShooterGame({ + required final GameStatsBloc statsBloc, + required final InventoryBloc inventoryBloc, +}) extends FlameGame with DragCallbacks, HasCollisionDetection, HasKeyboardHandlerComponents { late PlayerComponent player; - final GameStatsBloc statsBloc; - final InventoryBloc inventoryBloc; - - SpaceShooterGame({ - required this.statsBloc, - required this.inventoryBloc, - }); - @override Future onLoad() async { add( diff --git a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_bloc.dart b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_bloc.dart index 896e1bcb64e..b9573ab1a98 100644 --- a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_bloc.dart +++ b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_bloc.dart @@ -4,8 +4,8 @@ import 'package:flutter_bloc/flutter_bloc.dart'; part 'game_stats_event.dart'; part 'game_stats_state.dart'; -class GameStatsBloc extends Bloc { - GameStatsBloc() : super(const GameStatsState.empty()) { +class GameStatsBloc() extends Bloc { + this : super(const GameStatsState.empty()) { on( (event, emit) => emit( state.copyWith(score: state.score + event.score), diff --git a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_event.dart b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_event.dart index 4c47f23ee80..5654ce809f2 100644 --- a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_event.dart +++ b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_event.dart @@ -1,35 +1,23 @@ part of 'game_stats_bloc.dart'; -abstract class GameStatsEvent extends Equatable { - const GameStatsEvent(); -} - -class ScoreEventAdded extends GameStatsEvent { - const ScoreEventAdded(this.score); - - final int score; +abstract class const GameStatsEvent() extends Equatable; +class const ScoreEventAdded(final int score) extends GameStatsEvent { @override List get props => [score]; } -class PlayerDied extends GameStatsEvent { - const PlayerDied(); - +class const PlayerDied() extends GameStatsEvent { @override List get props => []; } -class PlayerRespawned extends GameStatsEvent { - const PlayerRespawned(); - +class const PlayerRespawned() extends GameStatsEvent { @override List get props => []; } -class GameReset extends GameStatsEvent { - const GameReset(); - +class const GameReset() extends GameStatsEvent { @override List get props => []; } diff --git a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart index 8fea2020e4b..6a706bf2599 100644 --- a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart +++ b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart @@ -1,23 +1,17 @@ part of 'game_stats_bloc.dart'; -enum GameStatus { +enum GameStatus() { initial, respawn, respawned, gameOver, } -class GameStatsState extends Equatable { - final int score; - final int lives; - final GameStatus status; - - const GameStatsState({ - required this.score, - required this.lives, - required this.status, - }); - +class const GameStatsState({ + required final int score, + required final int lives, + required final GameStatus status, +}) extends Equatable { const GameStatsState.empty() : this( score: 0, diff --git a/packages/flame_bloc/example/lib/src/game_stats/view/game_stat.dart b/packages/flame_bloc/example/lib/src/game_stats/view/game_stat.dart index 3748b5570ab..9921550b57f 100644 --- a/packages/flame_bloc/example/lib/src/game_stats/view/game_stat.dart +++ b/packages/flame_bloc/example/lib/src/game_stats/view/game_stat.dart @@ -2,9 +2,7 @@ import 'package:flame_bloc_example/src/game_stats/bloc/game_stats_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:material_ui/material_ui.dart'; -class GameStat extends StatelessWidget { - const GameStat({super.key}); - +class const GameStat({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return BlocConsumer( diff --git a/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_bloc.dart b/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_bloc.dart index dfe210306d9..84a7e3ce330 100644 --- a/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_bloc.dart +++ b/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_bloc.dart @@ -4,8 +4,8 @@ import 'package:flutter_bloc/flutter_bloc.dart'; part 'inventory_event.dart'; part 'inventory_state.dart'; -class InventoryBloc extends Bloc { - InventoryBloc() : super(const InventoryState.empty()) { +class InventoryBloc() extends Bloc { + this : super(const InventoryState.empty()) { on( (event, emit) => emit( state.copyWith(weapon: event.weapon), diff --git a/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_event.dart b/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_event.dart index 21189752c7c..5afcb223c35 100644 --- a/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_event.dart +++ b/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_event.dart @@ -1,21 +1,13 @@ part of 'inventory_bloc.dart'; -abstract class InventoryEvent extends Equatable { - const InventoryEvent(); -} - -class WeaponEquipped extends InventoryEvent { - final Weapon weapon; - - const WeaponEquipped(this.weapon); +abstract class const InventoryEvent() extends Equatable; +class const WeaponEquipped(final Weapon weapon) extends InventoryEvent { @override List get props => [weapon]; } -class NextWeaponEquipped extends InventoryEvent { - const NextWeaponEquipped(); - +class const NextWeaponEquipped() extends InventoryEvent { @override List get props => []; } diff --git a/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_state.dart b/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_state.dart index e4f847ee101..416292bd9b7 100644 --- a/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_state.dart +++ b/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_state.dart @@ -1,18 +1,14 @@ part of 'inventory_bloc.dart'; -enum Weapon { +enum Weapon() { bullet, laser, plasma, } -class InventoryState extends Equatable { - final Weapon weapon; - - const InventoryState({ - required this.weapon, - }); - +class const InventoryState({ + required final Weapon weapon, +}) extends Equatable { const InventoryState.empty() : this(weapon: Weapon.bullet); InventoryState copyWith({ diff --git a/packages/flame_bloc/example/lib/src/inventory/view/inventory.dart b/packages/flame_bloc/example/lib/src/inventory/view/inventory.dart index 5e9abd5f9f5..4fb92de08ac 100644 --- a/packages/flame_bloc/example/lib/src/inventory/view/inventory.dart +++ b/packages/flame_bloc/example/lib/src/inventory/view/inventory.dart @@ -2,9 +2,7 @@ import 'package:flame_bloc_example/src/inventory/bloc/inventory_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:material_ui/material_ui.dart'; -class Inventory extends StatelessWidget { - const Inventory({super.key}); - +class const Inventory({super.key}) extends StatelessWidget { Color _mapWeaponColor(Weapon weapon) { return switch (weapon) { Weapon.bullet => Colors.orange, diff --git a/packages/flame_bloc/example/pubspec.yaml b/packages/flame_bloc/example/pubspec.yaml index 14a919f894b..07b858054a1 100644 --- a/packages/flame_bloc/example/pubspec.yaml +++ b/packages/flame_bloc/example/pubspec.yaml @@ -7,8 +7,8 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: equatable: ^2.0.5 diff --git a/packages/flame_bloc/lib/src/flame_bloc_listener.dart b/packages/flame_bloc/lib/src/flame_bloc_listener.dart index 32efe51addd..df036deaa02 100644 --- a/packages/flame_bloc/lib/src/flame_bloc_listener.dart +++ b/packages/flame_bloc/lib/src/flame_bloc_listener.dart @@ -6,25 +6,20 @@ import 'package:flame_bloc/flame_bloc.dart'; /// {@template flame_bloc_listener} /// A [Component] which can listen to changes in a [Bloc] state. /// {@endtemplate} -class FlameBlocListener, S> extends Component - with FlameBlocListenable { +class FlameBlocListener, S>({ + required final void Function(S state) _onNewState, + final void Function(S state)? _onInitialState, + B? bloc, + final bool Function(S previousState, S newState)? _listenWhen, + super.key, +}) extends Component with FlameBlocListenable { /// {@macro flame_bloc_listener} - FlameBlocListener({ - required this._onNewState, - this._onInitialState, - B? bloc, - this._listenWhen, - super.key, - }) { + this { if (bloc != null) { this.bloc = bloc; } } - final void Function(S state) _onNewState; - final void Function(S state)? _onInitialState; - final bool Function(S previousState, S newState)? _listenWhen; - @override void onNewState(S state) => _onNewState(state); diff --git a/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart b/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart index 8f9f377a5bd..49ee7605a8e 100644 --- a/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart +++ b/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart @@ -6,20 +6,17 @@ import 'package:flame_bloc/flame_bloc.dart'; /// Similar to [FlameBlocProvider], but provides multiples blocs down /// to the component tree /// {@endtemplate} -class FlameMultiBlocProvider extends Component { +class FlameMultiBlocProvider({ + required final List _providers, + List? children, + super.key, +}) extends Component { /// {@macro flame_multi_bloc_provider} - FlameMultiBlocProvider({ - required List providers, - List? children, - super.key, - }) : _providers = providers, - _initialChildren = children, - assert(providers.isNotEmpty, 'At least one provider must be given') { + this : assert(_providers.isNotEmpty, 'At least one provider must be given') { _addProviders(); } - final List _providers; - final List? _initialChildren; + final List? _initialChildren = children; FlameBlocProvider? _lastProvider; void _addProviders() { diff --git a/packages/flame_bloc/pubspec.yaml b/packages/flame_bloc/pubspec.yaml index 6a4191ba09e..c0376b0df74 100644 --- a/packages/flame_bloc/pubspec.yaml +++ b/packages/flame_bloc/pubspec.yaml @@ -12,8 +12,8 @@ topics: - state-management environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: bloc: ">=8.1.1 <10.0.0" diff --git a/packages/flame_bloc/test/inventory_cubit.dart b/packages/flame_bloc/test/inventory_cubit.dart index 06163f43037..7a9d45af2d9 100644 --- a/packages/flame_bloc/test/inventory_cubit.dart +++ b/packages/flame_bloc/test/inventory_cubit.dart @@ -1,12 +1,12 @@ import 'package:bloc/bloc.dart'; -enum InventoryState { +enum InventoryState() { sword, bow, } -class InventoryCubit extends Cubit { - InventoryCubit() : super(InventoryState.sword); +class InventoryCubit() extends Cubit { + this : super(InventoryState.sword); void selectBow() { emit(InventoryState.bow); diff --git a/packages/flame_bloc/test/player_cubit.dart b/packages/flame_bloc/test/player_cubit.dart index ee4cdcbb04c..84ddade8a15 100644 --- a/packages/flame_bloc/test/player_cubit.dart +++ b/packages/flame_bloc/test/player_cubit.dart @@ -1,9 +1,13 @@ import 'package:bloc/bloc.dart'; -enum PlayerState { alive, dead, sad } +enum PlayerState() { + alive, + dead, + sad, +} -class PlayerCubit extends Cubit { - PlayerCubit() : super(PlayerState.alive); +class PlayerCubit() extends Cubit { + this : super(PlayerState.alive); void kill() { emit(PlayerState.dead); diff --git a/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart b/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart index e7a47f331b0..7535b630f60 100644 --- a/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart +++ b/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart @@ -7,7 +7,8 @@ import 'package:flutter_test/flutter_test.dart'; import '../inventory_cubit.dart'; import '../player_cubit.dart'; -class _PlayerListener extends Component +class _PlayerListener() + extends Component with FlameBlocListenable { PlayerState? last; @override @@ -25,7 +26,8 @@ class _PlayerListener extends Component } } -class _SadPlayerListener extends Component +class _SadPlayerListener() + extends Component with FlameBlocListenable { PlayerState? last; @@ -49,7 +51,8 @@ class _SadPlayerListener extends Component } } -class _BlocAccessingListener extends Component +class _BlocAccessingListener() + extends Component with FlameBlocListenable { PlayerCubit? initialBloc; @@ -233,17 +236,13 @@ void main() { }); } -class _CustomBlocRoute extends Route { - _CustomBlocRoute({ - Component Function()? builder, - this._onPush, - this._onPop, - this._build, - }) : super(builder); - - final void Function(Route, Route?)? _onPush; - final void Function(Route, Route)? _onPop; - final Component Function(Route)? _build; +class _CustomBlocRoute({ + Component Function()? builder, + final void Function(Route, Route?)? _onPush, + final void Function(Route, Route)? _onPop, + final Component Function(Route)? _build, +}) extends Route { + this : super(builder); @override void onPush(Route? route) => _onPush?.call(this, route); diff --git a/packages/flame_bloc/test/src/flame_bloc_listener_test.dart b/packages/flame_bloc/test/src/flame_bloc_listener_test.dart index 2a93183233f..a8ff9c68b02 100644 --- a/packages/flame_bloc/test/src/flame_bloc_listener_test.dart +++ b/packages/flame_bloc/test/src/flame_bloc_listener_test.dart @@ -61,7 +61,7 @@ void main() { final component = FlameBlocListener( onNewState: states.add, - listenWhen: (_, __) => false, + listenWhen: (_, _) => false, ); await provider.ensureAdd(component); diff --git a/packages/flame_bloc/test/src/flame_bloc_provider_test.dart b/packages/flame_bloc/test/src/flame_bloc_provider_test.dart index 1359a664cdc..81126f0c52f 100644 --- a/packages/flame_bloc/test/src/flame_bloc_provider_test.dart +++ b/packages/flame_bloc/test/src/flame_bloc_provider_test.dart @@ -5,10 +5,12 @@ import 'package:flutter_test/flutter_test.dart'; import '../inventory_cubit.dart'; -class _InventoryReader extends Component - with FlameBlocReader {} +class _InventoryReader() + extends Component + with FlameBlocReader; -class _InventoryListener extends Component +class _InventoryListener() + extends Component with FlameBlocListenable { InventoryState? lastState; diff --git a/packages/flame_bloc/test/src/flame_bloc_reader_test.dart b/packages/flame_bloc/test/src/flame_bloc_reader_test.dart index fcf062de498..a22fcc151f0 100644 --- a/packages/flame_bloc/test/src/flame_bloc_reader_test.dart +++ b/packages/flame_bloc/test/src/flame_bloc_reader_test.dart @@ -6,8 +6,9 @@ import 'package:flutter_test/flutter_test.dart'; import '../inventory_cubit.dart'; import '../player_cubit.dart'; -class _PlayerReader extends Component - with FlameBlocReader {} +class _PlayerReader() + extends Component + with FlameBlocReader; void main() { group('FlameBlocReader', () { diff --git a/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart b/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart index 4fbdbbc533f..9f4ab5b8e1e 100644 --- a/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart +++ b/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart @@ -6,10 +6,12 @@ import 'package:flutter_test/flutter_test.dart'; import '../inventory_cubit.dart'; import '../player_cubit.dart'; -class _InventoryReader extends Component - with FlameBlocReader {} +class _InventoryReader() + extends Component + with FlameBlocReader; -class _InventoryListener extends Component +class _InventoryListener() + extends Component with FlameBlocListenable { InventoryState? lastState; @@ -19,10 +21,12 @@ class _InventoryListener extends Component } } -class _PlayerReader extends Component - with FlameBlocReader {} +class _PlayerReader() + extends Component + with FlameBlocReader; -class _PlayerListener extends Component +class _PlayerListener() + extends Component with FlameBlocListenable { PlayerState? lastState; diff --git a/packages/flame_cli/lib/src/command_categories.dart b/packages/flame_cli/lib/src/command_categories.dart index 2921a34debe..0487257ca74 100644 --- a/packages/flame_cli/lib/src/command_categories.dart +++ b/packages/flame_cli/lib/src/command_categories.dart @@ -3,7 +3,7 @@ /// The categories are shown in alphabetical order, which matches the order /// in which they are typically used: create the game, launch it, look at it, /// change it, play it. -abstract final class CommandCategories { +abstract final class CommandCategories() { static const creating = 'Creating a game'; static const launching = 'Launching the game'; static const observing = 'Observing the game'; diff --git a/packages/flame_cli/lib/src/commands/control_commands.dart b/packages/flame_cli/lib/src/commands/control_commands.dart index aa1d66451f4..1626a7a818a 100644 --- a/packages/flame_cli/lib/src/commands/control_commands.dart +++ b/packages/flame_cli/lib/src/commands/control_commands.dart @@ -9,9 +9,9 @@ import 'package:flame_cli/src/run_controller.dart'; import 'package:io/io.dart'; /// Hot reloads the game through `flame run`. -class ReloadCommand extends _RunRequestCommand { - ReloadCommand(super.out, super.workingDirectory) - : super(request: RunRequest.reload); +class ReloadCommand(super.out, super.workingDirectory) + extends _RunRequestCommand { + this : super(request: RunRequest.reload); @override String get name => 'reload'; @@ -22,9 +22,9 @@ class ReloadCommand extends _RunRequestCommand { } /// Hot restarts the game through `flame run`. -class RestartCommand extends _RunRequestCommand { - RestartCommand(super.out, super.workingDirectory) - : super(request: RunRequest.restart); +class RestartCommand(super.out, super.workingDirectory) + extends _RunRequestCommand { + this : super(request: RunRequest.restart); @override String get name => 'restart'; @@ -34,8 +34,12 @@ class RestartCommand extends _RunRequestCommand { 'Hot restart the game, which has to have been started with `flame run`.'; } -abstract class _RunRequestCommand extends Command { - _RunRequestCommand(this.out, this.workingDirectory, {required this.request}) { +abstract class _RunRequestCommand( + final StringSink out, + final Directory workingDirectory, { + required final RunRequest request, +}) extends Command { + this { argParser.addOption( 'port', abbr: 'p', @@ -47,10 +51,6 @@ abstract class _RunRequestCommand extends Command { ); } - final StringSink out; - final Directory workingDirectory; - final RunRequest request; - @override String get category => CommandCategories.launching; diff --git a/packages/flame_cli/lib/src/commands/create_command.dart b/packages/flame_cli/lib/src/commands/create_command.dart index c36ed57b4fc..5c872824db5 100644 --- a/packages/flame_cli/lib/src/commands/create_command.dart +++ b/packages/flame_cli/lib/src/commands/create_command.dart @@ -15,14 +15,13 @@ import 'package:path/path.dart' as p; /// It runs `flutter create` for the platform folders and the pubspec, writes /// the files of the chosen template on top, and adds the Flame packages with /// `flutter pub add`, so that the newest compatible versions are used. -class CreateCommand extends Command { - CreateCommand( - this.out, - this.workingDirectory, { - ProcessStarter? startProcess, - StringSink? err, - }) : _startProcess = startProcess ?? Process.start, - _err = err ?? stderr { +class CreateCommand( + final StringSink out, + final Directory workingDirectory, { + ProcessStarter? startProcess, + StringSink? err, +}) extends Command { + this { argParser ..addOption( 'project-name', @@ -77,10 +76,8 @@ class CreateCommand extends Command { ); } - final StringSink out; - final Directory workingDirectory; - final ProcessStarter _startProcess; - final StringSink _err; + final ProcessStarter _startProcess = startProcess ?? Process.start; + final StringSink _err = err ?? stderr; @override String get name => 'create'; diff --git a/packages/flame_cli/lib/src/commands/debug_command.dart b/packages/flame_cli/lib/src/commands/debug_command.dart index 4085c4298b1..53a60885f44 100644 --- a/packages/flame_cli/lib/src/commands/debug_command.dart +++ b/packages/flame_cli/lib/src/commands/debug_command.dart @@ -5,8 +5,8 @@ import 'package:flame_cli/src/flame_connection.dart'; import 'package:io/io.dart'; /// Shows or changes the debug mode of the game, or of a single component. -class DebugCommand extends FlameCommand { - DebugCommand(super.out, super.workingDirectory) { +class DebugCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser.addOption( 'component', abbr: 'c', @@ -53,7 +53,7 @@ class DebugCommand extends FlameCommand { if (enable == null) { final response = await connection.call( 'getDebugMode', - args: {if (componentId != null) 'id': componentId}, + args: {'id': ?componentId}, ); final enabled = response['debug_mode'] == true; out.writeln('Debug mode is ${enabled ? 'on' : 'off'} for $target.'); @@ -64,7 +64,7 @@ class DebugCommand extends FlameCommand { 'setDebugMode', args: { 'debug_mode': enable.toString(), - if (componentId != null) 'id': componentId, + 'id': ?componentId, }, ); out.writeln('Turned debug mode ${enable ? 'on' : 'off'} for $target.'); diff --git a/packages/flame_cli/lib/src/commands/devtools_command.dart b/packages/flame_cli/lib/src/commands/devtools_command.dart index f2e9599bb88..851b7013c8a 100644 --- a/packages/flame_cli/lib/src/commands/devtools_command.dart +++ b/packages/flame_cli/lib/src/commands/devtools_command.dart @@ -15,15 +15,17 @@ import 'package:flame_cli/src/flame_connection.dart'; /// is checked to be reachable before the DevTools are started. The Flame /// extension is enabled in the `devtools_options.yaml` of the project, so /// that the DevTools show the Flame tab without asking. -class DevToolsCommand extends Command { - DevToolsCommand( - this.workingDirectory, { - ProcessStarter? startProcess, - GameConnector? connect, - this.out, - this.err, - }) : _startProcess = startProcess ?? Process.start, - _connect = connect ?? FlameConnection.connect { +class DevToolsCommand( + final Directory workingDirectory, { + ProcessStarter? startProcess, + GameConnector? connect, + + /// Where the output of `dart devtools` is mirrored to, the standard output + /// and error of this process by default. + final StringSink? out, + final StringSink? err, +}) extends Command { + this { argParser ..addOption( 'uri', @@ -43,14 +45,8 @@ class DevToolsCommand extends Command { ); } - final Directory workingDirectory; - final ProcessStarter _startProcess; - final GameConnector _connect; - - /// Where the output of `dart devtools` is mirrored to, the standard output - /// and error of this process by default. - final StringSink? out; - final StringSink? err; + final ProcessStarter _startProcess = startProcess ?? Process.start; + final GameConnector _connect = connect ?? FlameConnection.connect; @override String get name => 'devtools'; @@ -91,6 +87,6 @@ class DevToolsCommand extends Command { workingDirectory: workingDirectory, ); await forwardOutput(process, out ?? stdout, err ?? stderr); - return process.exitCode; + return await process.exitCode; } } diff --git a/packages/flame_cli/lib/src/commands/diff_command.dart b/packages/flame_cli/lib/src/commands/diff_command.dart index 1ae019490de..e765f7f98ec 100644 --- a/packages/flame_cli/lib/src/commands/diff_command.dart +++ b/packages/flame_cli/lib/src/commands/diff_command.dart @@ -9,8 +9,9 @@ import 'package:io/io.dart'; import 'package:path/path.dart' as p; /// Compares two PNG images, for example two snapshots. -class DiffCommand extends Command { - DiffCommand(this.out, this.workingDirectory) { +class DiffCommand(final StringSink out, final Directory workingDirectory) + extends Command { + this { argParser ..addOption( 'output', @@ -34,9 +35,6 @@ class DiffCommand extends Command { ); } - final StringSink out; - final Directory workingDirectory; - @override String get name => 'diff'; diff --git a/packages/flame_cli/lib/src/commands/flame_command.dart b/packages/flame_cli/lib/src/commands/flame_command.dart index 989f1649584..c17da725c7f 100644 --- a/packages/flame_cli/lib/src/commands/flame_command.dart +++ b/packages/flame_cli/lib/src/commands/flame_command.dart @@ -12,8 +12,11 @@ typedef GameConnector = Future Function(String uri); /// /// The game is found through the `--uri` option, or if that isn't given, /// through the file that `flame run` writes the URI of the game to. -abstract class FlameCommand extends Command { - FlameCommand(this.out, this.workingDirectory) { +abstract class FlameCommand( + final StringSink out, + final Directory workingDirectory, +) extends Command { + this { argParser.addOption( 'uri', abbr: 'u', @@ -24,9 +27,6 @@ abstract class FlameCommand extends Command { ); } - final StringSink out; - final Directory workingDirectory; - /// Validates the options, before a connection to the game is made. void validate() {} @@ -65,7 +65,7 @@ Future connectToGame( uriOption: uriOption, ); if (file == null) { - return connect(uri); + return await connect(uri); } try { diff --git a/packages/flame_cli/lib/src/commands/game_loop_commands.dart b/packages/flame_cli/lib/src/commands/game_loop_commands.dart index 83cdd478424..0a49858a98f 100644 --- a/packages/flame_cli/lib/src/commands/game_loop_commands.dart +++ b/packages/flame_cli/lib/src/commands/game_loop_commands.dart @@ -5,9 +5,7 @@ import 'package:flame_cli/src/flame_connection.dart'; import 'package:io/io.dart'; /// Pauses the game loop. -class PauseCommand extends FlameCommand { - PauseCommand(super.out, super.workingDirectory); - +class PauseCommand(super.out, super.workingDirectory) extends FlameCommand { @override String get name => 'pause'; @@ -28,9 +26,7 @@ class PauseCommand extends FlameCommand { } /// Resumes the game loop. -class ResumeCommand extends FlameCommand { - ResumeCommand(super.out, super.workingDirectory); - +class ResumeCommand(super.out, super.workingDirectory) extends FlameCommand { @override String get name => 'resume'; @@ -49,8 +45,8 @@ class ResumeCommand extends FlameCommand { } /// Advances the paused game by a number of frames. -class StepCommand extends FlameCommand { - StepCommand(super.out, super.workingDirectory) { +class StepCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser ..addOption( 'time', diff --git a/packages/flame_cli/lib/src/commands/input_commands.dart b/packages/flame_cli/lib/src/commands/input_commands.dart index ebac419abf1..aff99be8e9b 100644 --- a/packages/flame_cli/lib/src/commands/input_commands.dart +++ b/packages/flame_cli/lib/src/commands/input_commands.dart @@ -7,8 +7,9 @@ import 'package:flame_cli/src/flame_connection.dart'; import 'package:io/io.dart'; /// Sends taps, drags and key presses to the game. -class InputCommand extends Command { - InputCommand(StringSink out, Directory workingDirectory) { +class InputCommand(StringSink out, Directory workingDirectory) + extends Command { + this { addSubcommand(_TapCommand(out, workingDirectory)); addSubcommand(_DragCommand(out, workingDirectory)); addSubcommand(_KeyCommand(out, workingDirectory)); @@ -26,9 +27,7 @@ class InputCommand extends Command { 'terminal.'; } -class _TapCommand extends FlameCommand { - _TapCommand(super.out, super.workingDirectory); - +class _TapCommand(super.out, super.workingDirectory) extends FlameCommand { @override String get name => 'tap'; @@ -61,8 +60,8 @@ class _TapCommand extends FlameCommand { } } -class _DragCommand extends FlameCommand { - _DragCommand(super.out, super.workingDirectory) { +class _DragCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser.addOption( 'steps', abbr: 's', @@ -118,8 +117,8 @@ class _DragCommand extends FlameCommand { } } -class _KeyCommand extends FlameCommand { - _KeyCommand(super.out, super.workingDirectory) { +class _KeyCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser ..addFlag( 'down', diff --git a/packages/flame_cli/lib/src/commands/inspect_command.dart b/packages/flame_cli/lib/src/commands/inspect_command.dart index 0b768fafeac..9efd1d0146e 100644 --- a/packages/flame_cli/lib/src/commands/inspect_command.dart +++ b/packages/flame_cli/lib/src/commands/inspect_command.dart @@ -6,8 +6,8 @@ import 'package:flame_cli/src/json_output.dart'; import 'package:io/io.dart'; /// Prints information about a single component. -class InspectCommand extends FlameCommand { - InspectCommand(super.out, super.workingDirectory) { +class InspectCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser.addFlag( 'json', negatable: false, diff --git a/packages/flame_cli/lib/src/commands/logs_command.dart b/packages/flame_cli/lib/src/commands/logs_command.dart index 9340912dbb8..b7c214d854b 100644 --- a/packages/flame_cli/lib/src/commands/logs_command.dart +++ b/packages/flame_cli/lib/src/commands/logs_command.dart @@ -8,8 +8,9 @@ import 'package:flame_cli/src/project_files.dart'; import 'package:io/io.dart'; /// Prints the output of the `flutter run` that `flame run` started. -class LogsCommand extends Command { - LogsCommand(this.out, this.workingDirectory) { +class LogsCommand(final StringSink out, final Directory workingDirectory) + extends Command { + this { argParser ..addOption( 'lines', @@ -27,9 +28,6 @@ class LogsCommand extends Command { ); } - final StringSink out; - final Directory workingDirectory; - @override String get name => 'logs'; diff --git a/packages/flame_cli/lib/src/commands/overlay_commands.dart b/packages/flame_cli/lib/src/commands/overlay_commands.dart index cd4af3f98df..fe39f7a00af 100644 --- a/packages/flame_cli/lib/src/commands/overlay_commands.dart +++ b/packages/flame_cli/lib/src/commands/overlay_commands.dart @@ -8,8 +8,8 @@ import 'package:flame_cli/src/json_output.dart'; import 'package:io/io.dart'; /// Lists the registered overlays of the game and which of them are active. -class OverlaysCommand extends FlameCommand { - OverlaysCommand(super.out, super.workingDirectory) { +class OverlaysCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser.addFlag( 'json', negatable: false, @@ -50,8 +50,9 @@ class OverlaysCommand extends FlameCommand { } /// Shows, hides or navigates to an overlay. -class OverlayCommand extends Command { - OverlayCommand(StringSink out, Directory workingDirectory) { +class OverlayCommand(StringSink out, Directory workingDirectory) + extends Command { + this { addSubcommand(_SetOverlayCommand(out, workingDirectory, active: true)); addSubcommand(_SetOverlayCommand(out, workingDirectory, active: false)); addSubcommand(_OnlyOverlayCommand(out, workingDirectory)); @@ -67,11 +68,11 @@ class OverlayCommand extends Command { String get description => 'Show or hide an overlay of the game.'; } -class _SetOverlayCommand extends FlameCommand { - _SetOverlayCommand(super.out, super.workingDirectory, {required this.active}); - - final bool active; - +class _SetOverlayCommand( + super.out, + super.workingDirectory, { + required final bool active, +}) extends FlameCommand { @override String get name => active ? 'show' : 'hide'; @@ -101,9 +102,8 @@ class _SetOverlayCommand extends FlameCommand { } } -class _OnlyOverlayCommand extends FlameCommand { - _OnlyOverlayCommand(super.out, super.workingDirectory); - +class _OnlyOverlayCommand(super.out, super.workingDirectory) + extends FlameCommand { @override String get name => 'only'; diff --git a/packages/flame_cli/lib/src/commands/run_command.dart b/packages/flame_cli/lib/src/commands/run_command.dart index 176f7e813cc..73f4712a520 100644 --- a/packages/flame_cli/lib/src/commands/run_command.dart +++ b/packages/flame_cli/lib/src/commands/run_command.dart @@ -10,14 +10,13 @@ import 'package:flame_cli/src/run_controller.dart'; import 'package:io/io.dart'; /// Starts a process, with the same signature as [Process.start]. -typedef ProcessStarter = - Future Function( - String executable, - List arguments, { - String? workingDirectory, - bool runInShell, - ProcessStartMode mode, - }); +typedef ProcessStarter = Future Function( + String executable, + List arguments, { + String? workingDirectory, + bool runInShell, + ProcessStartMode mode, +}); /// Starts `flutter` with [arguments] through [startProcess], and turns a /// failure to start it into a [FlameCliException] that tells the user to @@ -96,26 +95,20 @@ Future forwardOutput(Process process, StringSink out, StringSink err) { /// The output of `flutter run` is also written to the log file of the project /// for the `logs` command, and `reload` and `restart` requests are accepted /// through a [RunController]. -class RunCommand extends Command { - RunCommand( - this.workingDirectory, { - ProcessStarter? startProcess, - this.input, - this.out, - this.err, - }) : _startProcess = startProcess ?? Process.start; - - final Directory workingDirectory; - final ProcessStarter _startProcess; - - /// Where the output of `flutter run` is mirrored to, the standard output - /// and error of this process by default. - final StringSink? out; - final StringSink? err; +class RunCommand( + final Directory workingDirectory, { + ProcessStarter? startProcess, /// The input of the terminal, which is forwarded to `flutter run` so that /// its keys, such as `r` for hot reload, keep working. - final Stream>? input; + final Stream>? input, + + /// Where the output of `flutter run` is mirrored to, the standard output + /// and error of this process by default. + final StringSink? out, + final StringSink? err, +}) extends Command { + final ProcessStarter _startProcess = startProcess ?? Process.start; final _argParser = ArgParser.allowAnything(); @@ -168,7 +161,7 @@ class RunCommand extends Command { outSink.writeln(helpHeader); final process = await _startFlutterRun(['--help']); await forwardOutput(process, outSink, errSink); - return process.exitCode; + return await process.exitCode; } if (arguments.any((a) => a.startsWith('--vmservice-out-file'))) { throw UsageException( @@ -237,12 +230,10 @@ class RunCommand extends Command { } } -class _TerminalMode { - _TerminalMode({required this.echoMode, required this.lineMode}); - - final bool echoMode; - final bool lineMode; - +class _TerminalMode({ + required final bool echoMode, + required final bool lineMode, +}) { void restore() { try { stdin diff --git a/packages/flame_cli/lib/src/commands/set_command.dart b/packages/flame_cli/lib/src/commands/set_command.dart index 92d7a8e6ba5..457d63e0984 100644 --- a/packages/flame_cli/lib/src/commands/set_command.dart +++ b/packages/flame_cli/lib/src/commands/set_command.dart @@ -6,8 +6,8 @@ import 'package:flame_cli/src/flame_connection.dart'; import 'package:io/io.dart'; /// Changes the attributes of a component. -class SetCommand extends FlameCommand { - SetCommand(super.out, super.workingDirectory) { +class SetCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser ..addOption( 'position', diff --git a/packages/flame_cli/lib/src/commands/snapshot_command.dart b/packages/flame_cli/lib/src/commands/snapshot_command.dart index e4bbde9de5d..3e18c102b0a 100644 --- a/packages/flame_cli/lib/src/commands/snapshot_command.dart +++ b/packages/flame_cli/lib/src/commands/snapshot_command.dart @@ -10,8 +10,8 @@ import 'package:io/io.dart'; import 'package:path/path.dart' as p; /// Renders the whole game, the world, or a single component, to a PNG image. -class SnapshotCommand extends FlameCommand { - SnapshotCommand(super.out, super.workingDirectory) { +class SnapshotCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser ..addOption( 'output', @@ -108,7 +108,7 @@ class SnapshotCommand extends FlameCommand { args: { 'pixelRatio': pixelRatio, if (argResults!.flag('world')) 'world': 'true', - if (rect != null) 'rect': rect, + 'rect': ?rect, }, ) : await connection.call( diff --git a/packages/flame_cli/lib/src/commands/tree_command.dart b/packages/flame_cli/lib/src/commands/tree_command.dart index 0413e24c07b..9fc3cc5a9f6 100644 --- a/packages/flame_cli/lib/src/commands/tree_command.dart +++ b/packages/flame_cli/lib/src/commands/tree_command.dart @@ -8,8 +8,8 @@ import 'package:io/io.dart'; /// Prints the component tree of the game, with the id and the attributes of /// every component. -class TreeCommand extends FlameCommand { - TreeCommand(super.out, super.workingDirectory) { +class TreeCommand(super.out, super.workingDirectory) extends FlameCommand { + this { argParser ..addOption( 'filter', diff --git a/packages/flame_cli/lib/src/create_templates.dart b/packages/flame_cli/lib/src/create_templates.dart index ea5de364f55..1f7241dd780 100644 --- a/packages/flame_cli/lib/src/create_templates.dart +++ b/packages/flame_cli/lib/src/create_templates.dart @@ -3,17 +3,11 @@ /// /// The [files] are relative to the project directory, and `{{name}}` in /// their contents is replaced with the project name. -class CreateTemplate { - const CreateTemplate({ - required this.name, - required this.description, - required this.files, - }); - - final String name; - final String description; - final Map files; - +class const CreateTemplate({ + required final String name, + required final String description, + required final Map files, +}) { /// Whether the template comes with tests, and thus needs `flame_test`. bool get hasTests => files.keys.any((path) => path.startsWith('test/')); diff --git a/packages/flame_cli/lib/src/flame_cli_exception.dart b/packages/flame_cli/lib/src/flame_cli_exception.dart index e422ce36ac5..edf45adca0c 100644 --- a/packages/flame_cli/lib/src/flame_cli_exception.dart +++ b/packages/flame_cli/lib/src/flame_cli_exception.dart @@ -2,15 +2,10 @@ import 'package:io/io.dart'; /// An error that stops a command, with a message that is meant to be shown to /// the user and the [exitCode] that the process should exit with. -class FlameCliException implements Exception { - const FlameCliException( - this.message, { - this.exitCode = ExitCode.software, - }); - - final String message; - final ExitCode exitCode; - +class const FlameCliException( + final String message, { + final ExitCode exitCode = ExitCode.software, +}) implements Exception { @override String toString() => message; } diff --git a/packages/flame_cli/lib/src/flame_command_runner.dart b/packages/flame_cli/lib/src/flame_command_runner.dart index d2da3c31ab7..1d569d73569 100644 --- a/packages/flame_cli/lib/src/flame_command_runner.dart +++ b/packages/flame_cli/lib/src/flame_command_runner.dart @@ -21,20 +21,20 @@ import 'package:io/io.dart'; /// The runner of the `flame` command, which returns the exit code instead of /// throwing when a command fails. -class FlameCommandRunner extends CommandRunner { - FlameCommandRunner({ - StringSink? out, - StringSink? err, - Directory? workingDirectory, - ProcessStarter? startProcess, - GameConnector? connect, - Stream>? input, - }) : _err = err ?? stderr, - super( - 'flame', - 'Create Flame games, and launch, observe, change and play the ones ' - 'that are running in debug mode.', - ) { +class FlameCommandRunner({ + StringSink? out, + StringSink? err, + Directory? workingDirectory, + ProcessStarter? startProcess, + GameConnector? connect, + Stream>? input, +}) extends CommandRunner { + this + : super( + 'flame', + 'Create Flame games, and launch, observe, change and play the ones ' + 'that are running in debug mode.', + ) { final output = out ?? stdout; final directory = workingDirectory ?? Directory.current; addCommand( @@ -75,7 +75,7 @@ class FlameCommandRunner extends CommandRunner { addCommand(DiffCommand(output, directory)); } - final StringSink _err; + final StringSink _err = err ?? stderr; @override Future run(Iterable args) async { diff --git a/packages/flame_cli/lib/src/flame_connection.dart b/packages/flame_cli/lib/src/flame_connection.dart index cd3f41ddad8..11597cdeac6 100644 --- a/packages/flame_cli/lib/src/flame_connection.dart +++ b/packages/flame_cli/lib/src/flame_connection.dart @@ -5,18 +5,15 @@ import 'package:vm_service/vm_service_io.dart'; /// A connection to a Flame game that is running in debug mode, through the /// service extensions that Flame registers for the DevTools extension. -class FlameConnection { - FlameConnection._(this.uri, this._service, this._isolateId, this._extensions); - - static const _extensionPrefix = 'ext.flame_devtools.'; - +class FlameConnection._( /// The URI of the Dart VM Service that the connection was made to, as it /// was passed to [connect]. - final String uri; - - final VmService _service; - final String _isolateId; - final Set _extensions; + final String uri, + final VmService _service, + final String _isolateId, + final Set _extensions, +) { + static const _extensionPrefix = 'ext.flame_devtools.'; /// Connects to the Dart VM Service at [uri] and finds the isolate that runs /// the Flame game. diff --git a/packages/flame_cli/lib/src/image_diff.dart b/packages/flame_cli/lib/src/image_diff.dart index fe04c718cf4..b62c6bdbe66 100644 --- a/packages/flame_cli/lib/src/image_diff.dart +++ b/packages/flame_cli/lib/src/image_diff.dart @@ -3,25 +3,18 @@ import 'dart:math'; import 'package:image/image.dart' as img; /// The result of comparing two images with [diffImages]. -class ImageDiff { - ImageDiff({ - required this.differingPixels, - required this.totalPixels, - required this.bounds, - required this.image, - }); - - final int differingPixels; - final int totalPixels; +class ImageDiff({ + required final int differingPixels, + required final int totalPixels, /// The smallest rectangle that contains all the differing pixels, as /// `(left, top, width, height)`, or null if the images are identical. - final ({int left, int top, int width, int height})? bounds; + required final ({int left, int top, int width, int height})? bounds, /// The differing pixels in red on top of a dimmed version of the second /// image. - final img.Image image; - + required final img.Image image, +}) { double get percentage => differingPixels / totalPixels * 100; /// A one line description of the difference. diff --git a/packages/flame_cli/lib/src/run_controller.dart b/packages/flame_cli/lib/src/run_controller.dart index acdfd966cf7..77dce7ce338 100644 --- a/packages/flame_cli/lib/src/run_controller.dart +++ b/packages/flame_cli/lib/src/run_controller.dart @@ -6,14 +6,12 @@ import 'package:flame_cli/src/project_files.dart'; /// The request that the `reload` and `restart` commands send to `flame run`, /// as one line on the control port. -enum RunRequest { - reload('r'), - restart('R'); - - const RunRequest(this.key); - +enum RunRequest( /// The key that `flutter run` expects for the request. - final String key; + final String key, +) { + reload('r'), + restart('R'), } /// Manages a `flutter run` [process] that was started by `flame run`. @@ -31,29 +29,20 @@ enum RunRequest { /// `flame run` takes them over, the controller stops writing to the log and /// leaves the files alone when it exits, and when the newer run stops it /// takes the files back. -class RunController { - RunController({ - required this.process, - required this.projectDirectory, - this.input, - StringSink? out, - StringSink? err, - this.responseTimeout = const Duration(minutes: 2), - this.ownershipCheckInterval = const Duration(seconds: 1), - }) : _out = out ?? stdout, - _err = err ?? stderr; - - final Process process; - final Directory projectDirectory; - final Stream>? input; - final Duration responseTimeout; +class RunController({ + required final Process process, + required final Directory projectDirectory, + final Stream>? input, + StringSink? out, + StringSink? err, + final Duration responseTimeout = const Duration(minutes: 2), /// How often the control port file is checked to find out whether a newer /// `flame run` has taken over the project, or has stopped again. - final Duration ownershipCheckInterval; - - final StringSink _out; - final StringSink _err; + final Duration ownershipCheckInterval = const Duration(seconds: 1), +}) { + final StringSink _out = out ?? stdout; + final StringSink _err = err ?? stderr; final _lines = StreamController.broadcast(); Future _requests = Future.value(); diff --git a/packages/flame_cli/pubspec.yaml b/packages/flame_cli/pubspec.yaml index 2e6c3d9c5b3..05f9387e885 100644 --- a/packages/flame_cli/pubspec.yaml +++ b/packages/flame_cli/pubspec.yaml @@ -13,7 +13,7 @@ topics: - debugging environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: args: ^2.5.0 diff --git a/packages/flame_cli/test/create_command_test.dart b/packages/flame_cli/test/create_command_test.dart index a96505d55aa..68357e3379d 100644 --- a/packages/flame_cli/test/create_command_test.dart +++ b/packages/flame_cli/test/create_command_test.dart @@ -182,14 +182,13 @@ void main() { out: out, err: err, workingDirectory: directory, - startProcess: - ( - _, - _, { - workingDirectory, - runInShell = false, - mode = ProcessStartMode.normal, - }) async => FakeProcess(exitCode: 1), + startProcess: ( + _, + _, { + workingDirectory, + runInShell = false, + mode = ProcessStartMode.normal, + }) async => FakeProcess(exitCode: 1), ); expect(await runner.run(['create', 'my_game']), ExitCode.software.code); diff --git a/packages/flame_cli/test/devtools_command_test.dart b/packages/flame_cli/test/devtools_command_test.dart index b99599e5add..3753fcdaced 100644 --- a/packages/flame_cli/test/devtools_command_test.dart +++ b/packages/flame_cli/test/devtools_command_test.dart @@ -23,17 +23,12 @@ ProcessStarter _starter( workingDirectory, runInShell = false, mode = ProcessStartMode.normal, - }) async => onStart(executable, arguments, workingDirectory); + }) async => await onStart(executable, arguments, workingDirectory); } /// A connection to a game that is reachable at [uri], and that records /// whether it was disposed. -class _FakeConnection implements FlameConnection { - _FakeConnection(this.uri); - - @override - final String uri; - +class _FakeConnection(@override final String uri) implements FlameConnection { bool disposed = false; @override diff --git a/packages/flame_cli/test/fake_process.dart b/packages/flame_cli/test/fake_process.dart index 5dcfd9202c0..c020092c827 100644 --- a/packages/flame_cli/test/fake_process.dart +++ b/packages/flame_cli/test/fake_process.dart @@ -4,8 +4,8 @@ import 'dart:io'; /// A [Process] whose output is controlled by the test, and whose input is /// recorded. -class FakeProcess implements Process { - FakeProcess({int? exitCode}) { +class FakeProcess({int? exitCode}) implements Process { + this { if (exitCode != null) { exit(exitCode); } @@ -58,11 +58,8 @@ class FakeProcess implements Process { } } -class _InputConsumer implements StreamConsumer> { - _InputConsumer(this.buffer); - - final StringBuffer buffer; - +class _InputConsumer(final StringBuffer buffer) + implements StreamConsumer> { @override Future addStream(Stream> stream) { return stream.forEach((bytes) => buffer.write(utf8.decode(bytes))); diff --git a/packages/flame_cli/test/run_command_test.dart b/packages/flame_cli/test/run_command_test.dart index ad7d916b5b0..e24e81374df 100644 --- a/packages/flame_cli/test/run_command_test.dart +++ b/packages/flame_cli/test/run_command_test.dart @@ -21,7 +21,7 @@ ProcessStarter _starter( workingDirectory, runInShell = false, mode = ProcessStartMode.normal, - }) async => onStart(executable, arguments, workingDirectory); + }) async => await onStart(executable, arguments, workingDirectory); } void main() { diff --git a/packages/flame_console/example/lib/commands/clear_effects_command.dart b/packages/flame_console/example/lib/commands/clear_effects_command.dart index b18ee5e1e19..c344444e324 100644 --- a/packages/flame_console/example/lib/commands/clear_effects_command.dart +++ b/packages/flame_console/example/lib/commands/clear_effects_command.dart @@ -3,7 +3,7 @@ import 'package:flame/effects.dart'; import 'package:flame_console/flame_console.dart'; import 'package:flame_console_example/game.dart'; -class ClearEffectsCommand extends FlameConsoleCommand { +class ClearEffectsCommand() extends FlameConsoleCommand { @override String get name => 'clear_effects'; diff --git a/packages/flame_console/example/lib/game.dart b/packages/flame_console/example/lib/game.dart index 62e03118de9..25c4918c32a 100644 --- a/packages/flame_console/example/lib/game.dart +++ b/packages/flame_console/example/lib/game.dart @@ -9,7 +9,7 @@ import 'package:flame/palette.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; -class MyGame extends FlameGame with HasKeyboardHandlerComponents { +class MyGame() extends FlameGame with HasKeyboardHandlerComponents { @override FutureOr onLoad() async { await super.onLoad(); diff --git a/packages/flame_console/example/lib/main.dart b/packages/flame_console/example/lib/main.dart index ee2fcb0dcaa..ad3c9b461d6 100644 --- a/packages/flame_console/example/lib/main.dart +++ b/packages/flame_console/example/lib/main.dart @@ -8,14 +8,12 @@ void main() { runApp(const MaterialApp(home: MyGameApp())); } -class MyGameApp extends StatefulWidget { - const MyGameApp({super.key}); - +class const MyGameApp({super.key}) extends StatefulWidget { @override State createState() => _MyGameAppState(); } -class _MyGameAppState extends State { +class _MyGameAppState() extends State { late final MyGame _game; @override diff --git a/packages/flame_console/example/pubspec.yaml b/packages/flame_console/example/pubspec.yaml index 3b73bbc234d..4dc533d93e5 100644 --- a/packages/flame_console/example/pubspec.yaml +++ b/packages/flame_console/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_console/lib/src/commands/commands.dart b/packages/flame_console/lib/src/commands/commands.dart index f9e883826e7..2598e0a4979 100644 --- a/packages/flame_console/lib/src/commands/commands.dart +++ b/packages/flame_console/lib/src/commands/commands.dart @@ -12,7 +12,7 @@ export 'debug_command.dart'; export 'ls_command.dart'; export 'remove_command.dart'; -abstract class FlameConsoleCommand +abstract class FlameConsoleCommand() extends TerminuiCommand { List listAllChildren(Component component) { return [ @@ -52,7 +52,7 @@ abstract class FlameConsoleCommand } } -abstract class QueryCommand +abstract class QueryCommand() extends FlameConsoleCommand { (String?, String) processChildren(List children); @@ -87,7 +87,7 @@ abstract class QueryCommand ); } -class FlameConsoleCommands { +class FlameConsoleCommands() { static List commands = [ LsConsoleCommand(), RemoveConsoleCommand(), diff --git a/packages/flame_console/lib/src/commands/debug_command.dart b/packages/flame_console/lib/src/commands/debug_command.dart index 6bb1df6de27..0c7cfddf476 100644 --- a/packages/flame_console/lib/src/commands/debug_command.dart +++ b/packages/flame_console/lib/src/commands/debug_command.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame_console/src/commands/commands.dart'; -class DebugConsoleCommand extends QueryCommand { +class DebugConsoleCommand() extends QueryCommand { @override (String?, String) processChildren(List children) { for (final child in children) { diff --git a/packages/flame_console/lib/src/commands/ls_command.dart b/packages/flame_console/lib/src/commands/ls_command.dart index 43a47317918..1132dc20ece 100644 --- a/packages/flame_console/lib/src/commands/ls_command.dart +++ b/packages/flame_console/lib/src/commands/ls_command.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame_console/flame_console.dart'; -class LsConsoleCommand extends QueryCommand { +class LsConsoleCommand() extends QueryCommand { @override (String?, String) processChildren(List children) { final out = StringBuffer(); diff --git a/packages/flame_console/lib/src/commands/pause_command.dart b/packages/flame_console/lib/src/commands/pause_command.dart index a7017a68698..f31bc6e01ad 100644 --- a/packages/flame_console/lib/src/commands/pause_command.dart +++ b/packages/flame_console/lib/src/commands/pause_command.dart @@ -2,7 +2,8 @@ import 'package:args/args.dart'; import 'package:flame/game.dart'; import 'package:flame_console/flame_console.dart'; -class PauseConsoleCommand extends FlameConsoleCommand { +class PauseConsoleCommand() + extends FlameConsoleCommand { @override (String?, String) execute(G game, ArgResults results) { if (game.isPaused) { diff --git a/packages/flame_console/lib/src/commands/remove_command.dart b/packages/flame_console/lib/src/commands/remove_command.dart index d320b63822b..645c83eb775 100644 --- a/packages/flame_console/lib/src/commands/remove_command.dart +++ b/packages/flame_console/lib/src/commands/remove_command.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame_console/flame_console.dart'; -class RemoveConsoleCommand extends QueryCommand { +class RemoveConsoleCommand() extends QueryCommand { @override (String?, String) processChildren(List children) { for (final component in children) { diff --git a/packages/flame_console/lib/src/commands/resume_command.dart b/packages/flame_console/lib/src/commands/resume_command.dart index 4af4a9cdd9f..d1c538fec5e 100644 --- a/packages/flame_console/lib/src/commands/resume_command.dart +++ b/packages/flame_console/lib/src/commands/resume_command.dart @@ -2,7 +2,8 @@ import 'package:args/args.dart'; import 'package:flame/game.dart'; import 'package:flame_console/flame_console.dart'; -class ResumeConsoleCommand extends FlameConsoleCommand { +class ResumeConsoleCommand() + extends FlameConsoleCommand { @override (String?, String) execute(G game, ArgResults results) { if (!game.isPaused) { diff --git a/packages/flame_console/lib/src/view/console_view.dart b/packages/flame_console/lib/src/view/console_view.dart index a8427415755..1734dfccc86 100644 --- a/packages/flame_console/lib/src/view/console_view.dart +++ b/packages/flame_console/lib/src/view/console_view.dart @@ -24,41 +24,25 @@ import 'package:terminui/terminui.dart'; /// ), /// }, /// ) -class FlameConsoleView extends StatefulWidget { - const FlameConsoleView({ - required this.game, - required this.onClose, - this.customCommands, - this.repository, - this.containerBuilder, - this.cursorBuilder, - this.cursorColor, - this.historyBuilder, - this.textStyle, - super.key, - }); - - final G game; - final List>? customCommands; - final VoidCallback onClose; - final TerminuiRepository? repository; - - final ContainerBuilder? containerBuilder; - final WidgetBuilder? cursorBuilder; - final HistoryBuilder? historyBuilder; - - final Color? cursorColor; - final TextStyle? textStyle; - +class const FlameConsoleView({ + required final G game, + required final VoidCallback onClose, + final List>? customCommands, + final TerminuiRepository? repository, + final ContainerBuilder? containerBuilder, + final WidgetBuilder? cursorBuilder, + final Color? cursorColor, + final HistoryBuilder? historyBuilder, + final TextStyle? textStyle, + super.key, +}) extends StatefulWidget { @override State createState() => _ConsoleViewState(); } -class _ConsoleKeyboardHandler extends Component with KeyboardHandler { - _ConsoleKeyboardHandler(this._onKeyEvent); - - final KeyEventResult Function(KeyEvent, Set) _onKeyEvent; - +class _ConsoleKeyboardHandler( + final KeyEventResult Function(KeyEvent, Set) _onKeyEvent, +) extends Component with KeyboardHandler { @override bool onKeyEvent(KeyEvent event, Set keysPressed) { _onKeyEvent(event, keysPressed); @@ -66,7 +50,7 @@ class _ConsoleKeyboardHandler extends Component with KeyboardHandler { } } -class _ConsoleViewState extends State { +class _ConsoleViewState() extends State { late final List _commandList = [ ...FlameConsoleCommands.commands, if (widget.customCommands != null) ...widget.customCommands!, diff --git a/packages/flame_console/pubspec.yaml b/packages/flame_console/pubspec.yaml index 705105d86a6..2dcf7146580 100644 --- a/packages/flame_console/pubspec.yaml +++ b/packages/flame_console/pubspec.yaml @@ -13,8 +13,8 @@ topics: - utils environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: args: ^2.5.0 diff --git a/packages/flame_console/test/src/commands_test.dart b/packages/flame_console/test/src/commands_test.dart index 5df8462898b..b7813e4c926 100644 --- a/packages/flame_console/test/src/commands_test.dart +++ b/packages/flame_console/test/src/commands_test.dart @@ -4,7 +4,7 @@ import 'package:flame_console/flame_console.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -class _NoopCommand extends FlameConsoleCommand { +class _NoopCommand() extends FlameConsoleCommand { @override String get description => ''; diff --git a/packages/flame_devtools/lib/main.dart b/packages/flame_devtools/lib/main.dart index 4f8f357360c..398ed942e00 100644 --- a/packages/flame_devtools/lib/main.dart +++ b/packages/flame_devtools/lib/main.dart @@ -10,9 +10,7 @@ void main() { runApp(const FlameDevTools()); } -class FlameDevTools extends StatelessWidget { - const FlameDevTools({super.key}); - +class const FlameDevTools({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return const DevToolsExtension( diff --git a/packages/flame_devtools/lib/providers/component_priority_provider.dart b/packages/flame_devtools/lib/providers/component_priority_provider.dart index 28a6c2b1e28..f3dc0f5f50c 100644 --- a/packages/flame_devtools/lib/providers/component_priority_provider.dart +++ b/packages/flame_devtools/lib/providers/component_priority_provider.dart @@ -3,6 +3,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; final componentPriorityProvider = FutureProvider.autoDispose.family( (ref, id) async { - return Repository.getComponentPriority(id: id); + return await Repository.getComponentPriority(id: id); }, ); diff --git a/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart b/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart index a38dbfe5301..5fe11d38b53 100644 --- a/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart +++ b/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart @@ -4,6 +4,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; final positionComponentAttributesProvider = FutureProvider.autoDispose .family( (ref, id) async { - return Repository.getPositionComponentAttributes(id: id); + return await Repository.getPositionComponentAttributes(id: id); }, ); diff --git a/packages/flame_devtools/lib/repository.dart b/packages/flame_devtools/lib/repository.dart index 571e09ff643..403101b2dfc 100644 --- a/packages/flame_devtools/lib/repository.dart +++ b/packages/flame_devtools/lib/repository.dart @@ -1,7 +1,7 @@ import 'package:devtools_extensions/devtools_extensions.dart'; import 'package:flame/devtools.dart'; -abstract final class Repository { +abstract final class Repository() { static Future getComponentTree() async { final componentTreeResponse = await serviceManager .callServiceExtensionOnMainIsolate( @@ -134,12 +134,10 @@ abstract final class Repository { } } -class Overlays { - final List registered; - final List active; - - Overlays({required this.registered, required this.active}); - +class Overlays({ + required final List registered, + required final List active, +}) { factory Overlays.fromJson(Map json) { return Overlays( registered: List.from(json['overlays'] as List), @@ -148,25 +146,15 @@ class Overlays { } } -class PositionComponentAttributes { - final double x; - final double y; - final double width; - final double height; - final double angle; - final double scaleX; - final double scaleY; - - PositionComponentAttributes({ - required this.x, - required this.y, - required this.width, - required this.height, - required this.angle, - required this.scaleX, - required this.scaleY, - }); - +class PositionComponentAttributes({ + required final double x, + required final double y, + required final double width, + required final double height, + required final double angle, + required final double scaleX, + required final double scaleY, +}) { factory PositionComponentAttributes.fromJson(Map json) { return PositionComponentAttributes( x: (json['x'] as num).toDouble(), diff --git a/packages/flame_devtools/lib/widgets/component_priority_form.dart b/packages/flame_devtools/lib/widgets/component_priority_form.dart index 9910672d849..fba237d620d 100644 --- a/packages/flame_devtools/lib/widgets/component_priority_form.dart +++ b/packages/flame_devtools/lib/widgets/component_priority_form.dart @@ -4,14 +4,10 @@ import 'package:flame_devtools/widgets/incremental_number_form_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class ComponentPriorityForm extends ConsumerWidget { - const ComponentPriorityForm({ - required this.componentId, - super.key, - }); - - final int componentId; - +class const ComponentPriorityForm({ + required final int componentId, + super.key, +}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final priority = ref.watch(componentPriorityProvider(componentId)); diff --git a/packages/flame_devtools/lib/widgets/component_snapshot.dart b/packages/flame_devtools/lib/widgets/component_snapshot.dart index dd6e2796278..61376ee3f49 100644 --- a/packages/flame_devtools/lib/widgets/component_snapshot.dart +++ b/packages/flame_devtools/lib/widgets/component_snapshot.dart @@ -5,19 +5,15 @@ import 'package:flame/widgets.dart'; import 'package:flame_devtools/repository.dart'; import 'package:flutter/material.dart' hide Image; -class ComponentSnapshot extends StatefulWidget { - const ComponentSnapshot({ - required this.id, - super.key, - }); - - final int id; - +class const ComponentSnapshot({ + required final int id, + super.key, +}) extends StatefulWidget { @override State createState() => _ComponentSnapshotState(); } -class _ComponentSnapshotState extends State { +class _ComponentSnapshotState() extends State { late Future _snapshot; @override @@ -60,19 +56,15 @@ class _ComponentSnapshotState extends State { /// is removed or when [base64] changes, without going through the global Flame /// images cache, so the same component id can show different snapshots over /// time without serving a stale cached frame. -class Base64Image extends StatefulWidget { - const Base64Image({ - required this.base64, - super.key, - }); - - final String base64; - +class const Base64Image({ + required final String base64, + super.key, +}) extends StatefulWidget { @override State createState() => _Base64ImageState(); } -class _Base64ImageState extends State { +class _Base64ImageState() extends State { late Future _imageFuture; ui.Image? _image; var _decodeGeneration = 0; diff --git a/packages/flame_devtools/lib/widgets/component_tree.dart b/packages/flame_devtools/lib/widgets/component_tree.dart index 1f62b75c3c7..161f24b545a 100644 --- a/packages/flame_devtools/lib/widgets/component_tree.dart +++ b/packages/flame_devtools/lib/widgets/component_tree.dart @@ -8,9 +8,7 @@ import 'package:flame_devtools/widgets/position_component_attributes_form.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class ComponentTree extends StatelessWidget { - const ComponentTree({super.key}); - +class const ComponentTree({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return devtools_ui.SplitPane( @@ -27,9 +25,7 @@ class ComponentTree extends StatelessWidget { } } -class ComponentTreeSection extends ConsumerWidget { - const ComponentTreeSection({super.key}); - +class const ComponentTreeSection({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); @@ -103,9 +99,7 @@ class ComponentTreeSection extends ConsumerWidget { } } -class ComponentSection extends ConsumerWidget { - const ComponentSection({super.key}); - +class const ComponentSection({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final node = ref.watch(selectedTreeNodeProvider)?.data; diff --git a/packages/flame_devtools/lib/widgets/component_tree_model.dart b/packages/flame_devtools/lib/widgets/component_tree_model.dart index c4301f4dee3..c69fd5af197 100644 --- a/packages/flame_devtools/lib/widgets/component_tree_model.dart +++ b/packages/flame_devtools/lib/widgets/component_tree_model.dart @@ -37,17 +37,14 @@ final componentTreeLoaderProvider = FutureProvider((ref) async { }); @immutable -class ComponentTreeModel { - ComponentTreeModel({ - this.nodeHash = 0, - this.componentCount = 0, - TreeNode? treeRoot, - }) : treeRoot = treeRoot ?? TreeNode.root(); - - final TreeNode treeRoot; - final int componentCount; - final int nodeHash; - +// ignore: prefer_const_constructors_in_immutables +class ComponentTreeModel({ + final int nodeHash = 0, + final int componentCount = 0, + TreeNode? treeRoot, +}) { + final TreeNode treeRoot = + treeRoot ?? TreeNode.root(); static Future refreshComponentTree( ComponentTreeModel previousModel, ) async { diff --git a/packages/flame_devtools/lib/widgets/debug_mode_button.dart b/packages/flame_devtools/lib/widgets/debug_mode_button.dart index e43c7b3b033..ec05d9ef15d 100644 --- a/packages/flame_devtools/lib/widgets/debug_mode_button.dart +++ b/packages/flame_devtools/lib/widgets/debug_mode_button.dart @@ -1,16 +1,12 @@ import 'package:flame_devtools/repository.dart'; import 'package:flutter/material.dart'; -class DebugModeButton extends StatefulWidget { - const DebugModeButton({super.key, this.id}); - - final int? id; - +class const DebugModeButton({super.key, final int? id}) extends StatefulWidget { @override State createState() => _DebugModeButtonState(); } -class _DebugModeButtonState extends State { +class _DebugModeButtonState() extends State { late Future _debugMode; @override diff --git a/packages/flame_devtools/lib/widgets/game_loop_controls.dart b/packages/flame_devtools/lib/widgets/game_loop_controls.dart index 565b5c2a27d..d900710ab95 100644 --- a/packages/flame_devtools/lib/widgets/game_loop_controls.dart +++ b/packages/flame_devtools/lib/widgets/game_loop_controls.dart @@ -2,14 +2,12 @@ import 'package:flame_devtools/repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -class GameLoopControls extends StatefulWidget { - const GameLoopControls({super.key}); - +class const GameLoopControls({super.key}) extends StatefulWidget { @override State createState() => _GameLoopControlsState(); } -class _GameLoopControlsState extends State { +class _GameLoopControlsState() extends State { Future? _paused; final _stepTimeController = TextEditingController(); double get stepTime => double.tryParse(_stepTimeController.text) ?? 0; diff --git a/packages/flame_devtools/lib/widgets/incremental_number_form_field.dart b/packages/flame_devtools/lib/widgets/incremental_number_form_field.dart index a2c800ed863..f36a88174b7 100644 --- a/packages/flame_devtools/lib/widgets/incremental_number_form_field.dart +++ b/packages/flame_devtools/lib/widgets/incremental_number_form_field.dart @@ -1,23 +1,17 @@ import 'package:flutter/material.dart'; -class IncrementalNumberFormField extends StatefulWidget { - const IncrementalNumberFormField({ - required this.initialValue, - required this.label, - this.onChanged, - super.key, - }); - - final String label; - final T initialValue; - final void Function(T)? onChanged; - +class const IncrementalNumberFormField({ + required final T initialValue, + required final String label, + final void Function(T)? onChanged, + super.key, +}) extends StatefulWidget { @override State> createState() => _IncrementalNumberFormFieldState(); } -class _IncrementalNumberFormFieldState +class _IncrementalNumberFormFieldState() extends State> { late final _controller = TextEditingController() ..text = widget.initialValue.toString(); diff --git a/packages/flame_devtools/lib/widgets/overlay_navigation.dart b/packages/flame_devtools/lib/widgets/overlay_navigation.dart index fc0a7940a26..6c76af75323 100644 --- a/packages/flame_devtools/lib/widgets/overlay_navigation.dart +++ b/packages/flame_devtools/lib/widgets/overlay_navigation.dart @@ -2,14 +2,12 @@ import 'package:devtools_app_shared/ui.dart' as devtools_ui; import 'package:flame_devtools/repository.dart'; import 'package:flutter/material.dart'; -class OverlayNavigation extends StatefulWidget { - const OverlayNavigation({super.key}); - +class const OverlayNavigation({super.key}) extends StatefulWidget { @override State createState() => _OverlayNavigationState(); } -class _OverlayNavigationState extends State { +class _OverlayNavigationState() extends State { late Future _overlays; @override diff --git a/packages/flame_devtools/lib/widgets/position_component_attributes_form.dart b/packages/flame_devtools/lib/widgets/position_component_attributes_form.dart index 249692b9850..0f290b877b1 100644 --- a/packages/flame_devtools/lib/widgets/position_component_attributes_form.dart +++ b/packages/flame_devtools/lib/widgets/position_component_attributes_form.dart @@ -4,14 +4,10 @@ import 'package:flame_devtools/widgets/incremental_number_form_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class PositionComponentAttributesForm extends ConsumerWidget { - const PositionComponentAttributesForm({ - required this.componentId, - super.key, - }); - - final int componentId; - +class const PositionComponentAttributesForm({ + required final int componentId, + super.key, +}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final attributesData = ref.watch( diff --git a/packages/flame_devtools/pubspec.yaml b/packages/flame_devtools/pubspec.yaml index 584ee5ab0a8..c09461d8b95 100644 --- a/packages/flame_devtools/pubspec.yaml +++ b/packages/flame_devtools/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: animated_tree_view: ^2.3.0 diff --git a/packages/flame_fire_atlas/example/lib/main.dart b/packages/flame_fire_atlas/example/lib/main.dart index 82993612a7a..bf480cad720 100644 --- a/packages/flame_fire_atlas/example/lib/main.dart +++ b/packages/flame_fire_atlas/example/lib/main.dart @@ -11,7 +11,7 @@ void main() { runApp(GameWidget(game: game)); } -class ExampleGame extends FlameGame with TapCallbacks { +class ExampleGame() extends FlameGame with TapCallbacks { late FireAtlas _atlas; @override diff --git a/packages/flame_fire_atlas/example/pubspec.yaml b/packages/flame_fire_atlas/example/pubspec.yaml index a303bb0c0e9..faa29103f50 100644 --- a/packages/flame_fire_atlas/example/pubspec.yaml +++ b/packages/flame_fire_atlas/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_fire_atlas/lib/flame_fire_atlas.dart b/packages/flame_fire_atlas/lib/flame_fire_atlas.dart index b339e34fa24..4ddb0d843b3 100644 --- a/packages/flame_fire_atlas/lib/flame_fire_atlas.dart +++ b/packages/flame_fire_atlas/lib/flame_fire_atlas.dart @@ -1,5 +1,3 @@ -library flame_fire_atlas; - import 'dart:convert'; import 'package:archive/archive.dart'; @@ -25,30 +23,24 @@ extension FireAtlasExtensions on Game { /// Represents the basic information of a selection inside a fire atlas file, /// containing its [id] and its coordinates and dimensions. /// {@endtemplate} -class Selection { +class Selection({ /// The id of the selection. - String id; + required var String id, /// The horizontal coordinate of the selection. - int x; + required var int x, /// The vertical coordinate of the selection. - int y; + required var int y, /// The width of the selection. - int w; + required var int w, /// The height of the selection. - int h; - + required var int h, +}) { /// {@macro _selection} - Selection({ - required this.id, - required this.x, - required this.y, - required this.w, - required this.h, - }); + this; /// Creates a [Selection] from [json]. factory Selection.fromJson(Map json) { @@ -86,11 +78,14 @@ class Selection { /// Check [SpriteSelection] for [Sprite] based selections, and /// [AnimationSelection] for [SpriteAnimation] based selections. /// {@endtemplate} -abstract class BaseSelection { - final Selection _info; +abstract class BaseSelection( + final Selection _info, { + /// A group that this selection belongs to. + final String? group, +}) { /// {@macro _base_selection} - BaseSelection(this._info, {this.group}); + this; /// The id of the selection. String get id => _info.id; @@ -107,9 +102,6 @@ abstract class BaseSelection { /// The height of the selection. int get h => _info.h; - /// A group that this selection belongs to. - final String? group; - /// The selection information. Selection get selection => _info; @@ -136,12 +128,12 @@ abstract class BaseSelection { /// {@template _sprite_selection} /// Represents a specific selection of Flame [Sprite]s. /// {@endtemplate} -class SpriteSelection extends BaseSelection { +class SpriteSelection({ + required Selection info, + super.group, +}) extends BaseSelection { /// {@macro _sprite_selection} - SpriteSelection({ - required Selection info, - super.group, - }) : super(info); + this : super(info); /// Creates a [SpriteSelection] from [json]. factory SpriteSelection.fromJson(Map json) { @@ -172,24 +164,21 @@ class SpriteSelection extends BaseSelection { /// {@template _animation_selection} /// Represents a specific selection of Flame [Sprite]s as an animation. /// {@endtemplate} -class AnimationSelection extends BaseSelection { +class AnimationSelection({ + required Selection info, + /// The number of frames of this animation. - int frameCount; + required var int frameCount, /// The time between each frame. - double stepTime; + required var double stepTime, /// If the animation is looping or not. - bool loop; - + required var bool loop, + super.group, +}) extends BaseSelection { /// {@macro _animation_selection} - AnimationSelection({ - required Selection info, - required this.frameCount, - required this.stepTime, - required this.loop, - super.group, - }) : super(info); + this : super(info); /// Creates a [AnimationSelection] from [json]. factory AnimationSelection.fromJson(Map json) { @@ -244,31 +233,27 @@ class AnimationSelection extends BaseSelection { /// [SpriteAnimation]s. /// /// Use [getSprite] and [getAnimation] to retrieve mapped assets. -class FireAtlas { +class FireAtlas({ /// Id of the FireAtlas, mainly used by the Fire Atlas Editor for file /// identification. - String id; + required var String id, /// The width of the tile. - double tileWidth; + required var double tileWidth, /// The height of the tile. - double tileHeight; + required var double tileHeight, /// Stores the asset data once this instance has loaded. - String? imageData; - Image? _image; - + required var String? imageData, +}) { /// Creates a FireAtlas instance. /// /// This constructor is often used internally; to load a FireAtlas instance /// into you game, check [loadAsset]. - FireAtlas({ - required this.id, - required this.tileWidth, - required this.tileHeight, - required this.imageData, - }); + this; + + Image? _image; /// Holds all the selections of this file. Map selections = {}; diff --git a/packages/flame_fire_atlas/pubspec.yaml b/packages/flame_fire_atlas/pubspec.yaml index 36d064ed3b0..ce1bce36c6c 100644 --- a/packages/flame_fire_atlas/pubspec.yaml +++ b/packages/flame_fire_atlas/pubspec.yaml @@ -13,8 +13,8 @@ topics: - tools environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: archive: ^4.0.2 diff --git a/packages/flame_fire_atlas/test/flame_fire_atlas_test.dart b/packages/flame_fire_atlas/test/flame_fire_atlas_test.dart index a091fbe2fc5..07d837f40e0 100644 --- a/packages/flame_fire_atlas/test/flame_fire_atlas_test.dart +++ b/packages/flame_fire_atlas/test/flame_fire_atlas_test.dart @@ -9,13 +9,13 @@ import 'package:flame_fire_atlas/flame_fire_atlas.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _AssetsCacheMock extends Mock implements AssetsCache {} +class _AssetsCacheMock() extends Mock implements AssetsCache; -class _ImagesMock extends Mock implements Images {} +class _ImagesMock() extends Mock implements Images; -class _ImageMock extends Mock implements Image {} +class _ImageMock() extends Mock implements Image; -class _MockedGame extends Mock implements FlameGame { +class _MockedGame() extends Mock implements FlameGame { final _imagesMock = _ImagesMock(); @override Images get images => _imagesMock; @@ -35,7 +35,7 @@ Future _readTestAtlas() async { final assetsMock = _AssetsCacheMock(); when(() => assetsMock.readBinaryFile('cave.fa')).thenAnswer((_) async { - return _readTestFile(); + return await _readTestFile(); }); final imagesMock = _ImagesMock(); @@ -91,7 +91,7 @@ void main() { final assetsMock = _AssetsCacheMock(); when(() => assetsMock.readBinaryFile('cave.fa')).thenAnswer((_) async { - return _readTestFile(); + return await _readTestFile(); }); final imagesMock = _ImagesMock(); @@ -183,7 +183,7 @@ void main() { final game = _MockedGame(); when(() => game.assets.readBinaryFile('cave.fa')).thenAnswer((_) async { - return _readTestFile(); + return await _readTestFile(); }); when(() => game.images.fromBase64(any(), any())).thenAnswer((_) async { diff --git a/packages/flame_forge2d/example/lib/main.dart b/packages/flame_forge2d/example/lib/main.dart index 379d4704f59..5f26641378a 100644 --- a/packages/flame_forge2d/example/lib/main.dart +++ b/packages/flame_forge2d/example/lib/main.dart @@ -9,7 +9,7 @@ void main() { runApp(const GameWidget.managed(gameFactory: Forge2DExample.new)); } -class Forge2DExample extends Forge2DGame { +class Forge2DExample() extends Forge2DGame { @override Future onLoad() async { await super.onLoad(); @@ -40,8 +40,8 @@ class Forge2DExample extends Forge2DGame { /// Forge2D is tuned for bodies roughly between 0.1 and 10 meters, so the /// world is laid out at a realistic scale and the camera decides how large /// that ends up being on screen. -class Ball extends BodyComponent with TapCallbacks { - Ball({Vector2? initialPosition}) +class Ball({Vector2? initialPosition}) extends BodyComponent with TapCallbacks { + this : super( shapeSpecs: [ ShapeSpec( @@ -64,12 +64,7 @@ class Ball extends BodyComponent with TapCallbacks { } } -class Wall extends BodyComponent { - final Vector2 _start; - final Vector2 _end; - - Wall(this._start, this._end); - +class Wall(final Vector2 _start, final Vector2 _end) extends BodyComponent { @override Body createBody() { final shapeDef = ShapeDef(material: SurfaceMaterial(friction: 0.3)); diff --git a/packages/flame_forge2d/example/pubspec.yaml b/packages/flame_forge2d/example/pubspec.yaml index 0c23a11388c..9a23b0d9612 100644 --- a/packages/flame_forge2d/example/pubspec.yaml +++ b/packages/flame_forge2d/example/pubspec.yaml @@ -7,8 +7,8 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_forge2d/lib/body_component.dart b/packages/flame_forge2d/lib/body_component.dart index 53bb01e4c6f..9a126cc9512 100644 --- a/packages/flame_forge2d/lib/body_component.dart +++ b/packages/flame_forge2d/lib/body_component.dart @@ -11,16 +11,14 @@ import 'package:flutter/foundation.dart'; /// A pairing of a [ShapeGeometry] with an optional [ShapeDef], used by /// [BodyComponent.shapeSpecs] to describe the shapes that should be created /// on the body. -class ShapeSpec { - const ShapeSpec(this.geometry, [this.definition]); - +class const ShapeSpec( /// The geometry of the shape, for example a [Circle] or a [Polygon]. - final ShapeGeometry geometry; + final ShapeGeometry geometry, [ /// The definition that the shape is created with, or the Forge2D defaults /// when null. - final ShapeDef? definition; -} + final ShapeDef? definition, +]); /// Since a pure BodyComponent doesn't have anything drawn on top of it, /// it is a good idea to turn on [debugMode] for it so that the bodies can be @@ -29,21 +27,37 @@ class ShapeSpec { /// You can use the optional [bodyDef] and [shapeSpecs] arguments to create /// the [BodyComponent]'s body without having to create the definitions within /// the component. -class BodyComponent extends Component +class BodyComponent({ + Paint? paint, + super.children, + super.priority, + + /// Specifies if the body's shapes should be rendered. + /// + /// [renderBody] is true by default for [BodyComponent], if set to false + /// the body's shapes wont be rendered. + /// + /// If you render something on top of the [BodyComponent], or doesn't want it + /// to be seen, you probably want to set it to false. + var bool renderBody = true, + + /// The default implementation of [createBody] will use this value to create + /// the [Body], if it is provided. + /// + /// If you do not provide a [BodyDef] here, you must override [createBody]. + var BodyDef? bodyDef, + + /// The default implementation of [createBody] will create these shapes on + /// the [Body] that it creates from [bodyDef]. + var List? shapeSpecs, + super.key, +}) extends Component with HasGameRef, HasPaint implements CoordinateTransform, ReadOnlyPositionProvider, ReadOnlyAngleProvider { - BodyComponent({ - Paint? paint, - super.children, - super.priority, - this.renderBody = true, - this.bodyDef, - this.shapeSpecs, - super.key, - }) { + this { this.paint = paint ?? (Paint()..color = defaultColor); } @@ -58,28 +72,9 @@ class BodyComponent extends Component @visibleForTesting static bool debugWarnedAboutBodyScale = false; - /// The default implementation of [createBody] will use this value to create - /// the [Body], if it is provided. - /// - /// If you do not provide a [BodyDef] here, you must override [createBody]. - BodyDef? bodyDef; - - /// The default implementation of [createBody] will create these shapes on - /// the [Body] that it creates from [bodyDef]. - List? shapeSpecs; - @override Vector2 get position => body.position; - /// Specifies if the body's shapes should be rendered. - /// - /// [renderBody] is true by default for [BodyComponent], if set to false - /// the body's shapes wont be rendered. - /// - /// If you render something on top of the [BodyComponent], or doesn't want it - /// to be seen, you probably want to set it to false. - bool renderBody; - /// You should create the Forge2D [Body] in this method when you extend /// the BodyComponent. /// diff --git a/packages/flame_forge2d/lib/contact_callbacks.dart b/packages/flame_forge2d/lib/contact_callbacks.dart index 4c864df8ba6..861d45eff64 100644 --- a/packages/flame_forge2d/lib/contact_callbacks.dart +++ b/packages/flame_forge2d/lib/contact_callbacks.dart @@ -13,7 +13,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; /// [Forge2DWorld.preSolveCallback] (and [ShapeDef.enablePreSolveEvents] on /// the involved shapes). To measure impact strength, enable /// [ShapeDef.enableHitEvents] and poll the world's `contactEvents.hit`. -mixin class ContactCallbacks { +mixin class ContactCallbacks() { /// Called when two [Shape]s start being in contact. /// /// It is called for sensors and non-sensors. diff --git a/packages/flame_forge2d/lib/contact_events_dispatcher.dart b/packages/flame_forge2d/lib/contact_events_dispatcher.dart index a1aa0256e71..d44669aa79f 100644 --- a/packages/flame_forge2d/lib/contact_events_dispatcher.dart +++ b/packages/flame_forge2d/lib/contact_events_dispatcher.dart @@ -28,7 +28,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; /// [ContactEventsDispatcher] and provide it to your [Forge2DGame] or /// [Forge2DWorld]. /// {@endtemplate} -class ContactEventsDispatcher { +class ContactEventsDispatcher() { /// Called by [Forge2DWorld.update] after each physics step, with the /// events that were generated during that step. void dispatch(ContactEvents contactEvents, SensorEvents sensorEvents) { diff --git a/packages/flame_forge2d/lib/flame_forge2d.dart b/packages/flame_forge2d/lib/flame_forge2d.dart index c4ab7078b86..3dbb96b58c3 100644 --- a/packages/flame_forge2d/lib/flame_forge2d.dart +++ b/packages/flame_forge2d/lib/flame_forge2d.dart @@ -1,5 +1,3 @@ -library flame_forge2d; - export 'package:forge2d/forge2d.dart'; export 'body_component.dart'; diff --git a/packages/flame_forge2d/lib/forge2d_game.dart b/packages/flame_forge2d/lib/forge2d_game.dart index 3266a1e5673..b36cfc850b0 100644 --- a/packages/flame_forge2d/lib/forge2d_game.dart +++ b/packages/flame_forge2d/lib/forge2d_game.dart @@ -6,7 +6,22 @@ import 'package:flame_forge2d/forge2d_world.dart'; import 'package:forge2d/forge2d.dart' show Tolerances, initializeForge2D; /// The base game class for creating games that uses the Forge2D physics engine. -class Forge2DGame extends FlameGame { +class Forge2DGame({ + Forge2DWorld? world, + CameraComponent? camera, + Vector2? gravity, + ContactEventsDispatcher? contactEventsDispatcher, + double metersToPixels = Forge2DViewfinder.defaultMetersToPixels, + + /// How many of the world's length units make up one meter, or null to leave + /// the length unit alone. + /// + /// Forwarded to [initializeForge2D] in [onLoad]. The length unit is + /// process-wide and cannot change once a physics world exists, so this can + /// only be set through the constructor, and games that run at the same time + /// have to agree on it. + final double? lengthUnitsPerMeter, +}) extends FlameGame { /// Creates a game with a [Forge2DWorld]. /// /// The world is measured in meters and rendered with [metersToPixels] @@ -24,28 +39,22 @@ class Forge2DGame extends FlameGame { /// [contactEventsDispatcher] is only used for the world that this /// constructor creates, so pass it to the [Forge2DWorld] itself when you /// provide a [world]. - Forge2DGame({ - Forge2DWorld? world, - CameraComponent? camera, - Vector2? gravity, - ContactEventsDispatcher? contactEventsDispatcher, - double metersToPixels = Forge2DViewfinder.defaultMetersToPixels, - this.lengthUnitsPerMeter, - }) : assert( - world == null || contactEventsDispatcher == null, - 'contactEventsDispatcher is ignored when a world is provided, pass ' - 'it to the Forge2DWorld constructor instead', - ), - super( - world: - ((world?..gravity = gravity ?? world.gravity) ?? - Forge2DWorld( - gravity: gravity, - contactEventsDispatcher: contactEventsDispatcher, - )) - as T, - camera: camera ?? CameraComponent(), - ) { + this + : assert( + world == null || contactEventsDispatcher == null, + 'contactEventsDispatcher is ignored when a world is provided, pass ' + 'it to the Forge2DWorld constructor instead', + ), + super( + world: + ((world?..gravity = gravity ?? world.gravity) ?? + Forge2DWorld( + gravity: gravity, + contactEventsDispatcher: contactEventsDispatcher, + )) + as T, + camera: camera ?? CameraComponent(), + ) { final viewfinder = this.camera.viewfinder; if (viewfinder is Forge2DViewfinder) { viewfinder.metersToPixels = metersToPixels; @@ -62,15 +71,6 @@ class Forge2DGame extends FlameGame { double get metersToPixels => _viewfinder.metersToPixels; set metersToPixels(double value) => _viewfinder.metersToPixels = value; - /// How many of the world's length units make up one meter, or null to leave - /// the length unit alone. - /// - /// Forwarded to [initializeForge2D] in [onLoad]. The length unit is - /// process-wide and cannot change once a physics world exists, so this can - /// only be set through the constructor, and games that run at the same time - /// have to agree on it. - final double? lengthUnitsPerMeter; - Forge2DViewfinder get _viewfinder => camera.viewfinder as Forge2DViewfinder; /// Initializes Forge2D and then loads the game. diff --git a/packages/flame_forge2d/lib/forge2d_viewfinder.dart b/packages/flame_forge2d/lib/forge2d_viewfinder.dart index a0668ea29b0..6a3a291277b 100644 --- a/packages/flame_forge2d/lib/forge2d_viewfinder.dart +++ b/packages/flame_forge2d/lib/forge2d_viewfinder.dart @@ -16,10 +16,11 @@ import 'package:forge2d/forge2d.dart' show Tolerances; /// Only the rendering is affected, so body positions, the [position] of the /// viewfinder, [visibleGameSize], [CameraComponent.visibleWorldRect] and the /// local positions that events report are all still in meters. -class Forge2DViewfinder extends Viewfinder { - Forge2DViewfinder({double metersToPixels = defaultMetersToPixels, super.key}) - : assert(metersToPixels > 0, 'metersToPixels must be positive'), - _metersToPixels = metersToPixels { +class Forge2DViewfinder({ + var double _metersToPixels = defaultMetersToPixels, + super.key, +}) extends Viewfinder { + this : assert(_metersToPixels > 0, 'metersToPixels must be positive') { zoom = 1; } @@ -32,8 +33,6 @@ class Forge2DViewfinder extends Viewfinder { /// this scale lands it in the range that Forge2D is tuned for. static const double defaultMetersToPixels = 100; - double _metersToPixels; - /// The number of pixels that one meter of the physics world is rendered as. double get metersToPixels => _metersToPixels; set metersToPixels(double value) { diff --git a/packages/flame_forge2d/lib/forge2d_world.dart b/packages/flame_forge2d/lib/forge2d_world.dart index d8e45150ddd..c12e69c1921 100644 --- a/packages/flame_forge2d/lib/forge2d_world.dart +++ b/packages/flame_forge2d/lib/forge2d_world.dart @@ -8,29 +8,24 @@ import 'package:forge2d/forge2d.dart' as forge2d; /// [BodyComponent]s and normal Flame components. /// /// Wraps the world class that comes from Forge2D ([forge2d.World]). -class Forge2DWorld extends World { - /// Creates a [Forge2DWorld] with the given [gravity], which defaults to - /// [defaultGravity]. - /// - /// A [definition] can be passed to configure the underlying physics world. - /// Be aware that [WorldDef.gravity] uses the y-up Box2D convention with a - /// default of (0, -10), while Flame's y-axis points down, so set its - /// gravity explicitly (or use the [gravity] argument, which takes - /// precedence) when you provide a definition. - Forge2DWorld({ - Vector2? gravity, - forge2d.WorldDef? definition, - ContactEventsDispatcher? contactEventsDispatcher, - super.children, - }) : _gravity = gravity ?? definition?.gravity ?? defaultGravity, - _definition = definition, - contactEventsDispatcher = - contactEventsDispatcher ?? ContactEventsDispatcher(); - +/// +/// Creates a [Forge2DWorld] with the given [gravity], which defaults to +/// [defaultGravity]. +/// +/// A `definition` can be passed to configure the underlying physics world. +/// Be aware that [WorldDef.gravity] uses the y-up Box2D convention with a +/// default of (0, -10), while Flame's y-axis points down, so set its +/// gravity explicitly (or use the [gravity] argument, which takes +/// precedence) when you provide a definition. +class Forge2DWorld({ + Vector2? gravity, + final forge2d.WorldDef? _definition, + ContactEventsDispatcher? contactEventsDispatcher, + super.children, +}) extends World { static final Vector2 defaultGravity = Vector2(0, 10.0); - Vector2 _gravity; - final forge2d.WorldDef? _definition; + Vector2 _gravity = gravity ?? _definition?.gravity ?? defaultGravity; forge2d.World? _physicsWorld; /// The underlying Forge2D physics world. @@ -73,7 +68,8 @@ class Forge2DWorld extends World { /// Routes the contact and sensor events that the physics world generated /// during a step to the [ContactCallbacks] in the involved userData. - final ContactEventsDispatcher contactEventsDispatcher; + final ContactEventsDispatcher contactEventsDispatcher = + contactEventsDispatcher ?? ContactEventsDispatcher(); /// The number of sub-steps that the physics world performs for each /// [update]. diff --git a/packages/flame_forge2d/pubspec.yaml b/packages/flame_forge2d/pubspec.yaml index cafd2eb2a67..a0b17241971 100644 --- a/packages/flame_forge2d/pubspec.yaml +++ b/packages/flame_forge2d/pubspec.yaml @@ -13,8 +13,8 @@ topics: - physics environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_forge2d/test/body_component_test.dart b/packages/flame_forge2d/test/body_component_test.dart index 347a07bfad0..e39390a8f25 100644 --- a/packages/flame_forge2d/test/body_component_test.dart +++ b/packages/flame_forge2d/test/body_component_test.dart @@ -10,7 +10,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _TestBodyComponent extends BodyComponent with TapCallbacks { +class _TestBodyComponent() extends BodyComponent with TapCallbacks { int tapCount = 0; @override @@ -22,7 +22,7 @@ class _TestBodyComponent extends BodyComponent with TapCallbacks { } } -class _MockCanvas extends Mock implements Canvas {} +class _MockCanvas() extends Mock implements Canvas; void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -689,9 +689,8 @@ void main() { }); } -class _CountingBodyComponent extends BodyComponent { - _CountingBodyComponent({super.bodyDef, super.shapeSpecs}); - +class _CountingBodyComponent({super.bodyDef, super.shapeSpecs}) + extends BodyComponent { int renderedShapes = 0; @override @@ -701,9 +700,7 @@ class _CountingBodyComponent extends BodyComponent { } } -class _ConsistentBodyComponent extends BodyComponent { - _ConsistentBodyComponent({super.bodyDef}); - +class _ConsistentBodyComponent({super.bodyDef}) extends BodyComponent { Forge2DWorld? onMountWorld; Forge2DWorld? onRemoveWorld; diff --git a/packages/flame_forge2d/test/body_scale_warning_test.dart b/packages/flame_forge2d/test/body_scale_warning_test.dart index cb7e86fe87e..de090ba16de 100644 --- a/packages/flame_forge2d/test/body_scale_warning_test.dart +++ b/packages/flame_forge2d/test/body_scale_warning_test.dart @@ -3,12 +3,10 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; -class _ShapeBody extends BodyComponent { - _ShapeBody({required this.geometry, required this.type}); - - final ShapeGeometry geometry; - final BodyType type; - +class _ShapeBody({ + required final ShapeGeometry geometry, + required final BodyType type, +}) extends BodyComponent { @override Body createBody() => world.createBody(BodyDef(type: type))..createShape(geometry, ShapeDef()); diff --git a/packages/flame_forge2d/test/contact_events_dispatcher_test.dart b/packages/flame_forge2d/test/contact_events_dispatcher_test.dart index eaf33dc444d..86f2ab721db 100644 --- a/packages/flame_forge2d/test/contact_events_dispatcher_test.dart +++ b/packages/flame_forge2d/test/contact_events_dispatcher_test.dart @@ -6,7 +6,7 @@ import 'package:test/scaffolding.dart'; import 'helpers/mocks.dart'; -class _CountingDispatcher extends ContactEventsDispatcher { +class _CountingDispatcher() extends ContactEventsDispatcher { int dispatchCount = 0; @override diff --git a/packages/flame_forge2d/test/forge2d_game_test.dart b/packages/flame_forge2d/test/forge2d_game_test.dart index a735c4c1c84..1ac3c983e0b 100644 --- a/packages/flame_forge2d/test/forge2d_game_test.dart +++ b/packages/flame_forge2d/test/forge2d_game_test.dart @@ -2,8 +2,8 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:test/test.dart'; -class _TestForge2dGame extends Forge2DGame { - _TestForge2dGame() : super(metersToPixels: 4.0, gravity: Vector2(0, -10.0)); +class _TestForge2dGame() extends Forge2DGame { + this : super(metersToPixels: 4.0, gravity: Vector2(0, -10.0)); } void main() { diff --git a/packages/flame_forge2d/test/forge2d_world_test.dart b/packages/flame_forge2d/test/forge2d_world_test.dart index 899ab9aa540..ddf7c20561b 100644 --- a/packages/flame_forge2d/test/forge2d_world_test.dart +++ b/packages/flame_forge2d/test/forge2d_world_test.dart @@ -2,8 +2,8 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:test/test.dart'; -class _TestForge2DWorld extends Forge2DWorld { - _TestForge2DWorld() : super(gravity: Vector2(0, 0)); +class _TestForge2DWorld() extends Forge2DWorld { + this : super(gravity: Vector2(0, 0)); } void main() { diff --git a/packages/flame_forge2d/test/helpers/mocks.dart b/packages/flame_forge2d/test/helpers/mocks.dart index 37ae84374ff..0106b5aab90 100644 --- a/packages/flame_forge2d/test/helpers/mocks.dart +++ b/packages/flame_forge2d/test/helpers/mocks.dart @@ -1,4 +1,4 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:mocktail/mocktail.dart'; -class MockContactCallback extends Mock implements ContactCallbacks {} +class MockContactCallback() extends Mock implements ContactCallbacks; diff --git a/packages/flame_forge2d/test/length_units_per_meter_test.dart b/packages/flame_forge2d/test/length_units_per_meter_test.dart index 09999bae6dc..73e221c5c0c 100644 --- a/packages/flame_forge2d/test/length_units_per_meter_test.dart +++ b/packages/flame_forge2d/test/length_units_per_meter_test.dart @@ -5,12 +5,12 @@ import 'package:flutter_test/flutter_test.dart'; // The length unit is process-wide, so this file changes it for every test in // it. `flutter test` runs each test file in its own process, which is what // keeps it from reaching the rest of the suite. -class _ScaledGame extends Forge2DGame { - _ScaledGame() : super(lengthUnitsPerMeter: 100); +class _ScaledGame() extends Forge2DGame { + this : super(lengthUnitsPerMeter: 100); } -class _ConflictingGame extends Forge2DGame { - _ConflictingGame() : super(lengthUnitsPerMeter: 25); +class _ConflictingGame() extends Forge2DGame { + this : super(lengthUnitsPerMeter: 25); } void main() { diff --git a/packages/flame_gamepads/example/lib/main.dart b/packages/flame_gamepads/example/lib/main.dart index 85dd87a3105..bb938e6795a 100644 --- a/packages/flame_gamepads/example/lib/main.dart +++ b/packages/flame_gamepads/example/lib/main.dart @@ -10,13 +10,13 @@ void main() { runApp(GameWidget(game: GamepadsGame())); } -class GamepadsGame extends FlameGame { +class GamepadsGame() extends FlameGame { PlayerComponent? player; static const worldSizeX = 16.0 * 28; static const worldSizeY = 16.0 * 14; - GamepadsGame() + this : super( camera: CameraComponent.withFixedResolution( width: worldSizeX, @@ -45,12 +45,10 @@ class GamepadsGame extends FlameGame { } } -class PlayerComponent extends RectangleComponent with GamepadCallbacks { - final double worldSizeX; - final double worldSizeY; - - PlayerComponent({required this.worldSizeX, required this.worldSizeY}); - +class PlayerComponent({ + required final double worldSizeX, + required final double worldSizeY, +}) extends RectangleComponent with GamepadCallbacks { double inputX = 0; double inputY = 0; diff --git a/packages/flame_gamepads/example/pubspec.yaml b/packages/flame_gamepads/example/pubspec.yaml index d78f274ce47..038a24e8b30 100644 --- a/packages/flame_gamepads/example/pubspec.yaml +++ b/packages/flame_gamepads/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_gamepads/lib/flame_gamepads.dart b/packages/flame_gamepads/lib/flame_gamepads.dart index bf7013b4cd6..df671f7bdde 100644 --- a/packages/flame_gamepads/lib/flame_gamepads.dart +++ b/packages/flame_gamepads/lib/flame_gamepads.dart @@ -1,3 +1 @@ -library flame_gamepads; - export 'src/gamepad_callbacks.dart'; diff --git a/packages/flame_gamepads/pubspec.yaml b/packages/flame_gamepads/pubspec.yaml index 32105b3888d..99dfec7f29e 100644 --- a/packages/flame_gamepads/pubspec.yaml +++ b/packages/flame_gamepads/pubspec.yaml @@ -12,8 +12,8 @@ topics: - gamepads environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_gamepads/test/flame_gamepads_test.dart b/packages/flame_gamepads/test/flame_gamepads_test.dart index 286cc1ccc82..1e984dc6db5 100644 --- a/packages/flame_gamepads/test/flame_gamepads_test.dart +++ b/packages/flame_gamepads/test/flame_gamepads_test.dart @@ -14,11 +14,9 @@ final platformInterface = GamepadsPlatformInterface.instance as MethodChannelGamepadsPlatformInterface; -class _TestComponent extends Component with GamepadCallbacks { - void Function(NormalizedGamepadEvent event) onEvent; - - _TestComponent(this.onEvent); - +class _TestComponent(var void Function(NormalizedGamepadEvent event) onEvent) + extends Component + with GamepadCallbacks { @override void onGamepadEvent(NormalizedGamepadEvent event) { onEvent(event); diff --git a/packages/flame_isolate/example/lib/brains/path_finder.dart b/packages/flame_isolate/example/lib/brains/path_finder.dart index 267d5b9fbe0..464ac1eedad 100755 --- a/packages/flame_isolate/example/lib/brains/path_finder.dart +++ b/packages/flame_isolate/example/lib/brains/path_finder.dart @@ -22,15 +22,10 @@ Iterable? findPath({ ); } -class PathFinderData { - final Map terrain; - final Set unWalkableTiles; - - const PathFinderData._({ - required this.terrain, - required this.unWalkableTiles, - }); - +class const PathFinderData._({ + required final Map terrain, + required final Set unWalkableTiles, +}) { factory PathFinderData.fromWorld({ required Map terrain, required List worldObjects, diff --git a/packages/flame_isolate/example/lib/brains/worker_overmind.dart b/packages/flame_isolate/example/lib/brains/worker_overmind.dart index 58881ed0608..e9e590bc32d 100755 --- a/packages/flame_isolate/example/lib/brains/worker_overmind.dart +++ b/packages/flame_isolate/example/lib/brains/worker_overmind.dart @@ -12,7 +12,8 @@ import 'package:flame_isolate_example/standard/pair.dart'; import 'package:flame_isolate_example/units/worker.dart'; import 'package:flutter/foundation.dart'; -class WorkerOvermind extends Component +class WorkerOvermind() + extends Component with HasGameRef, FlameIsolate { final List> _queuedTasks = []; late Timer _assignTaskInterval; @@ -151,14 +152,8 @@ class WorkerOvermind extends Component } @immutable -class _CalculateWorkData { - final List idleWorkerPositions; - final List destinations; - final PathFinderData pathFinderData; - - const _CalculateWorkData({ - required this.idleWorkerPositions, - required this.destinations, - required this.pathFinderData, - }); -} +class const _CalculateWorkData({ + required final List idleWorkerPositions, + required final List destinations, + required final PathFinderData pathFinderData, +}); diff --git a/packages/flame_isolate/example/lib/brains/worker_overmind_hud.dart b/packages/flame_isolate/example/lib/brains/worker_overmind_hud.dart index 4a82d57622a..01982e88dc2 100644 --- a/packages/flame_isolate/example/lib/brains/worker_overmind_hud.dart +++ b/packages/flame_isolate/example/lib/brains/worker_overmind_hud.dart @@ -3,17 +3,13 @@ import 'package:flame/events.dart'; import 'package:flame/extensions.dart'; import 'package:flutter/rendering.dart'; -enum ComputeType { +enum ComputeType(final String description) { isolate('Running in isolate'), compute('Running in compute function'), - synchronous('Running synchronously'); - - final String description; - - const ComputeType(this.description); + synchronous('Running synchronously'), } -class WorkerOvermindHud extends PositionComponent with TapCallbacks { +class WorkerOvermindHud() extends PositionComponent with TapCallbacks { ComputeType computeType = ComputeType.isolate; @override diff --git a/packages/flame_isolate/example/lib/colonists_game.dart b/packages/flame_isolate/example/lib/colonists_game.dart index 1ebcf379354..7c265ad7f7e 100755 --- a/packages/flame_isolate/example/lib/colonists_game.dart +++ b/packages/flame_isolate/example/lib/colonists_game.dart @@ -14,10 +14,10 @@ import 'package:flame_isolate_example/units/worker.dart'; import 'package:flutter/services.dart'; import 'package:material_ui/material_ui.dart'; -class ColonistsGame extends FlameGame with KeyboardEvents { +class ColonistsGame() extends FlameGame with KeyboardEvents { final PositionComponent _cameraPosition = PositionComponent(); late final GameMap _currentMap; - ColonistsGame() + this : super( camera: CameraComponent.withFixedResolution( width: 400, diff --git a/packages/flame_isolate/example/lib/constants.dart b/packages/flame_isolate/example/lib/constants.dart index 68295805533..85104e6ab50 100755 --- a/packages/flame_isolate/example/lib/constants.dart +++ b/packages/flame_isolate/example/lib/constants.dart @@ -1,3 +1,3 @@ -class Constants { +class Constants() { static const double tileSize = 50; } diff --git a/packages/flame_isolate/example/lib/game_map/game_map.dart b/packages/flame_isolate/example/lib/game_map/game_map.dart index 286fe67be2a..64264bd6eaa 100755 --- a/packages/flame_isolate/example/lib/game_map/game_map.dart +++ b/packages/flame_isolate/example/lib/game_map/game_map.dart @@ -13,7 +13,7 @@ import 'package:flame_isolate_example/terrain/grass.dart'; import 'package:flame_isolate_example/terrain/terrain.dart'; import 'package:flame_isolate_example/units/worker.dart'; -class GameMap extends Component with HasGameRef { +class GameMap() extends Component with HasGameRef { static const mapSizeX = 50; static const mapSizeY = 50; static const totalPositions = mapSizeX * mapSizeY; diff --git a/packages/flame_isolate/example/lib/objects/bread.dart b/packages/flame_isolate/example/lib/objects/bread.dart index 247d6e5f40c..950c3f13dad 100755 --- a/packages/flame_isolate/example/lib/objects/bread.dart +++ b/packages/flame_isolate/example/lib/objects/bread.dart @@ -4,7 +4,7 @@ import 'package:flame_isolate_example/constants.dart'; import 'package:flame_isolate_example/objects/colonists_object.dart'; import 'package:flame_isolate_example/standard/int_vector2.dart'; -class Bread extends StaticColonistsObject { +class Bread(super.x, super.y) extends StaticColonistsObject { @override Sprite objectSprite = Sprite( Flame.images.fromCache('assets/images/bread.png'), @@ -13,8 +13,6 @@ class Bread extends StaticColonistsObject { @override IntVector2 tileSize = const IntVector2(1, 1); - Bread(super.x, super.y); - @override String toString() { return 'Bread(${x / Constants.tileSize.toInt()}, ' diff --git a/packages/flame_isolate/example/lib/objects/cheese.dart b/packages/flame_isolate/example/lib/objects/cheese.dart index e3d9b81bc6a..d410c9329b5 100755 --- a/packages/flame_isolate/example/lib/objects/cheese.dart +++ b/packages/flame_isolate/example/lib/objects/cheese.dart @@ -3,7 +3,7 @@ import 'package:flame/flame.dart'; import 'package:flame_isolate_example/objects/colonists_object.dart'; import 'package:flame_isolate_example/standard/int_vector2.dart'; -class Cheese extends StaticColonistsObject { +class Cheese(super.x, super.y) extends StaticColonistsObject { @override final Sprite objectSprite = Sprite( Flame.images.fromCache('assets/images/cheese.png'), @@ -12,8 +12,6 @@ class Cheese extends StaticColonistsObject { @override final IntVector2 tileSize = const IntVector2(1, 1); - Cheese(super.x, super.y); - @override double difficulty = 8.6; } diff --git a/packages/flame_isolate/example/lib/objects/colonists_object.dart b/packages/flame_isolate/example/lib/objects/colonists_object.dart index 37d1a5da4c0..47292153ee4 100644 --- a/packages/flame_isolate/example/lib/objects/colonists_object.dart +++ b/packages/flame_isolate/example/lib/objects/colonists_object.dart @@ -11,7 +11,8 @@ mixin ColonistsObject on PositionComponent { ); } -abstract class StaticColonistsObject extends SpriteComponent +abstract class StaticColonistsObject(int x, int y) + extends SpriteComponent with ColonistsObject { Sprite get objectSprite; @@ -26,7 +27,7 @@ abstract class StaticColonistsObject extends SpriteComponent y ~/ Constants.tileSize, ); - StaticColonistsObject(int x, int y) { + this { sprite = objectSprite; width = tileSize.x * Constants.tileSize; height = tileSize.y * Constants.tileSize; diff --git a/packages/flame_isolate/example/lib/standard/int_vector2.dart b/packages/flame_isolate/example/lib/standard/int_vector2.dart index 262b8a4529e..4d940e4f34b 100755 --- a/packages/flame_isolate/example/lib/standard/int_vector2.dart +++ b/packages/flame_isolate/example/lib/standard/int_vector2.dart @@ -3,12 +3,7 @@ import 'package:flame/components.dart'; import 'package:quiver/core.dart'; @immutable -class IntVector2 { - final int x; - final int y; - - const IntVector2(this.x, this.y); - +class const IntVector2(final int x, final int y) { /// Manhattan distance on a square grid int distanceTo(IntVector2 b) { return (x - b.x).abs() + (y - b.y).abs(); diff --git a/packages/flame_isolate/example/lib/standard/pair.dart b/packages/flame_isolate/example/lib/standard/pair.dart index b9aca69e7d7..bdffdccf0aa 100755 --- a/packages/flame_isolate/example/lib/standard/pair.dart +++ b/packages/flame_isolate/example/lib/standard/pair.dart @@ -1,6 +1 @@ -class Pair { - final T first; - final E second; - - Pair(this.first, this.second); -} +class Pair(final T first, final E second); diff --git a/packages/flame_isolate/example/lib/terrain/grass.dart b/packages/flame_isolate/example/lib/terrain/grass.dart index dba5e5c634c..61a389784af 100755 --- a/packages/flame_isolate/example/lib/terrain/grass.dart +++ b/packages/flame_isolate/example/lib/terrain/grass.dart @@ -2,7 +2,7 @@ import 'package:flame/components.dart'; import 'package:flame_isolate_example/terrain/terrain.dart'; import 'package:material_ui/material_ui.dart'; -class Grass extends PositionComponent with Terrain { +class Grass() extends PositionComponent with Terrain { static final _color = Paint()..color = const Color(0xff567d46); static final _debugColor = Paint() ..color = Colors.black.withValues(alpha: 0.5); diff --git a/packages/flame_isolate/example/lib/units/actions/movable.dart b/packages/flame_isolate/example/lib/units/actions/movable.dart index 667002c6eea..8ad9cb014a4 100755 --- a/packages/flame_isolate/example/lib/units/actions/movable.dart +++ b/packages/flame_isolate/example/lib/units/actions/movable.dart @@ -6,7 +6,9 @@ import 'package:flame_isolate_example/colonists_game.dart'; import 'package:flame_isolate_example/standard/int_vector2.dart'; import 'package:material_ui/material_ui.dart'; -enum MoveDirection { +enum MoveDirection({ + required final bool isLeft, +}) { idle(isLeft: false), // 0 up(isLeft: false), // 1 down(isLeft: false), // 2 @@ -17,12 +19,6 @@ enum MoveDirection { left(isLeft: true), // 7 downRight(isLeft: false); // 8 - final bool isLeft; - - const MoveDirection({ - required this.isLeft, - }); - /// Returns the horizontally mirrored direction MoveDirection get mirrored { if (index >= 3 && index <= 5) { @@ -31,7 +27,6 @@ enum MoveDirection { if (index >= 6 && index <= 8) { return MoveDirection.values[index - 3]; } - // ignore: avoid_returning_this return this; } } @@ -105,10 +100,10 @@ mixin Movable on PositionComponent, HasGameRef { }; } -class PathLine extends ShapeComponent { - final Path path; +class PathLine(List path) extends ShapeComponent { + final Path path = _toPath(path); - PathLine(List path) : path = _toPath(path) { + this { paint = Paint() ..color = const Color(0x30ffffff) ..style = PaintingStyle.stroke; diff --git a/packages/flame_isolate/example/lib/units/worker.dart b/packages/flame_isolate/example/lib/units/worker.dart index 377ece131f6..9c9b1acbdb2 100755 --- a/packages/flame_isolate/example/lib/units/worker.dart +++ b/packages/flame_isolate/example/lib/units/worker.dart @@ -7,12 +7,10 @@ import 'package:flame_isolate_example/standard/int_vector2.dart'; import 'package:flame_isolate_example/standard/pair.dart'; import 'package:flame_isolate_example/units/actions/movable.dart'; -class Worker extends SpriteAnimationGroupComponent +class Worker(num x, num y, {@override final double speed = 50}) + extends SpriteAnimationGroupComponent with ColonistsObject, HasGameRef, Movable { - @override - final double speed; - - Worker(num x, num y, {this.speed = 50}) { + this { super.y = y * Constants.tileSize; super.x = x * Constants.tileSize; height = Constants.tileSize; diff --git a/packages/flame_isolate/example/pubspec.yaml b/packages/flame_isolate/example/pubspec.yaml index 371e79d59f7..1f1cc8e0763 100755 --- a/packages/flame_isolate/example/pubspec.yaml +++ b/packages/flame_isolate/example/pubspec.yaml @@ -7,8 +7,8 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.18.0 diff --git a/packages/flame_isolate/pubspec.yaml b/packages/flame_isolate/pubspec.yaml index 1a869f97517..84e93828ff3 100644 --- a/packages/flame_isolate/pubspec.yaml +++ b/packages/flame_isolate/pubspec.yaml @@ -8,8 +8,8 @@ topics: - isolate environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_isolate/test/flame_isolate_test.dart b/packages/flame_isolate/test/flame_isolate_test.dart index 99d171de4d1..d6feb140942 100644 --- a/packages/flame_isolate/test/flame_isolate_test.dart +++ b/packages/flame_isolate/test/flame_isolate_test.dart @@ -4,9 +4,9 @@ import 'package:flame_isolate/flame_isolate.dart'; import 'package:flame_test/flame_test.dart'; import 'package:test/test.dart'; -class _TestGame extends FlameGame with FlameIsolate {} +class _TestGame() extends FlameGame with FlameIsolate; -class _IsolateComponent extends Component with FlameIsolate {} +class _IsolateComponent() extends Component with FlameIsolate; void main() { testWithGame<_TestGame>( diff --git a/packages/flame_isolate/test/flame_tailored_isolate_test.dart b/packages/flame_isolate/test/flame_tailored_isolate_test.dart index 3f1cb612d7d..6e5c143a373 100644 --- a/packages/flame_isolate/test/flame_tailored_isolate_test.dart +++ b/packages/flame_isolate/test/flame_tailored_isolate_test.dart @@ -4,10 +4,11 @@ import 'package:flame_isolate/flame_tailored_isolate.dart'; import 'package:flame_test/flame_test.dart'; import 'package:test/test.dart'; -class _TestGame extends FlameGame with FlameTailoredIsolate {} +class _TestGame() extends FlameGame with FlameTailoredIsolate; -class _IsolateComponent extends Component - with FlameTailoredIsolate {} +class _IsolateComponent() + extends Component + with FlameTailoredIsolate; void main() { testWithGame<_TestGame>( diff --git a/packages/flame_jenny/jenny/lib/jenny.dart b/packages/flame_jenny/jenny/lib/jenny.dart index 3df0abb9f1b..cd848f4c06d 100644 --- a/packages/flame_jenny/jenny/lib/jenny.dart +++ b/packages/flame_jenny/jenny/lib/jenny.dart @@ -3,7 +3,7 @@ export 'src/character_storage.dart' show CharacterStorage; export 'src/command_storage.dart' show CommandStorage; export 'src/dialogue_runner.dart' show DialogueRunner; export 'src/dialogue_view.dart' show DialogueView; -export 'src/errors.dart' show SyntaxError, NameError, TypeError, DialogueError; +export 'src/errors.dart' show DialogueError, NameError, SyntaxError, TypeError; export 'src/function_storage.dart' show FunctionStorage; export 'src/localization.dart' show Localization, localizationInfo; export 'src/structure/commands/command.dart' show Command; diff --git a/packages/flame_jenny/jenny/lib/src/character.dart b/packages/flame_jenny/jenny/lib/src/character.dart index 44aeb96b7b5..9efc0bbad81 100644 --- a/packages/flame_jenny/jenny/lib/src/character.dart +++ b/packages/flame_jenny/jenny/lib/src/character.dart @@ -7,18 +7,17 @@ import 'package:jenny/jenny.dart'; /// All characters must be declared with the help of the `<>` /// command, unless [YarnProject]'s setting `strictCharacterNames` is set to /// false. -class Character { - Character(this.name, {List? aliases}) : aliases = aliases ?? []; - - Map? _data; - +class Character( /// The canonical name of the character, which was the first argument in the /// [<>] command. - final String name; + final String name, { + List? aliases, +}) { + Map? _data; /// Additional names (IDs) that may be used for this character in yarn /// scripts. - final List aliases; + final List aliases = aliases ?? []; /// Additional information associated with this character. This may include /// their short bio, portrait, affiliation, color, etc. This information diff --git a/packages/flame_jenny/jenny/lib/src/character_storage.dart b/packages/flame_jenny/jenny/lib/src/character_storage.dart index 7779a6a2045..1a6af28a91f 100644 --- a/packages/flame_jenny/jenny/lib/src/character_storage.dart +++ b/packages/flame_jenny/jenny/lib/src/character_storage.dart @@ -4,7 +4,7 @@ import 'package:meta/meta.dart'; /// The **CharacterStorage** is a cache for all [Character]s defined in your /// yarn scripts. This container is populated from the `<>` /// commands as the YarnProject parses the input scripts. -class CharacterStorage { +class CharacterStorage() { final Map _cache = {}; bool get isEmpty => _cache.isEmpty; diff --git a/packages/flame_jenny/jenny/lib/src/command_storage.dart b/packages/flame_jenny/jenny/lib/src/command_storage.dart index a1bfbbf2f15..a5661148a64 100644 --- a/packages/flame_jenny/jenny/lib/src/command_storage.dart +++ b/packages/flame_jenny/jenny/lib/src/command_storage.dart @@ -14,8 +14,8 @@ import 'package:meta/meta.dart'; /// and [addOrphanedCommand], depending on the arity of the function /// that needs to be invoked. All user-defined commands need to be declared /// before parsing any Yarn scripts. -class CommandStorage { - CommandStorage() : _commands = {}; +class CommandStorage() { + this : _commands = {}; final Map _commands; @@ -163,19 +163,19 @@ class CommandStorage { /// A wrapper around Dart function, which allows that function to be invoked /// dynamically from the Yarn runtime. -class _Cmd { - _Cmd(this.name, List types, this._wrappedFn) - : _signature = _unpackTypes(types), - _arguments = List.filled(types.length, null) { +class _Cmd( + final String name, + List types, + final FutureOr Function(List) _wrappedFn, +) { + this { numTrailingBooleans = _signature.reversed .takeWhile((type) => type == _Type.boolean) .length; } - final String name; - final List<_Type> _signature; - final FutureOr Function(List) _wrappedFn; - final List _arguments; + final List<_Type> _signature = _unpackTypes(types); + final List _arguments = List.filled(types.length, null); late final int numTrailingBooleans; FutureOr run(List arguments) { @@ -265,10 +265,7 @@ class _Cmd { } @visibleForTesting -class ArgumentsLexer { - ArgumentsLexer(this.text); - - final String text; +class ArgumentsLexer(final String text) { int position = 0; List<_ModeFn> modeStack = []; List tokens = []; @@ -386,7 +383,7 @@ class ArgumentsLexer { typedef _ModeFn = bool Function(); /// Similar to `ExpressionType`, but also allows `integer`. -enum _Type { +enum _Type() { boolean, integer, double, diff --git a/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart b/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart index 52e6af970b6..0d3e779349a 100644 --- a/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart +++ b/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart @@ -31,17 +31,15 @@ import 'package:meta/meta.dart'; /// output of a `DialogueRunner`, therefore, is a stream of dialogue statements /// that need to be presented to the player. Such presentation, is handled by /// [DialogueView]s. -class DialogueRunner { - /// Creates a `DialogueRunner` for executing the [yarnProject]. The dialogue - /// will be delivered to all the provided [_dialogueViews]. Each of these - /// dialogue views may only be assigned to a single `DialogueRunner` at a - /// time. - DialogueRunner({ - required YarnProject yarnProject, - required this._dialogueViews, - }) : project = yarnProject; - - final List _dialogueViews; +/// +/// Creates a `DialogueRunner` for executing the [project]. The dialogue +/// will be delivered to all the provided `dialogueViews`. Each of these +/// dialogue views may only be assigned to a single `DialogueRunner` at a +/// time. +class DialogueRunner({ + required YarnProject yarnProject, + required final List _dialogueViews, +}) { _LineDeliveryPipeline? _linePipeline; Node? _currentNode; NodeIterator? _currentIterator; @@ -49,7 +47,7 @@ class DialogueRunner { String? _nextNode; /// The `YarnProject` that this dialogue runner is executing. - final YarnProject project; + final YarnProject project = yarnProject; /// Starts the dialogue with the node [nodeName], and returns a future that /// completes once the dialogue finishes running. While this future is @@ -252,14 +250,17 @@ class DialogueRunner { } } -class _LineDeliveryPipeline { - _LineDeliveryPipeline(this.line, this.views) - : _completer = Completer(), - _futures = List.generate(views.length, (i) => null, growable: false); +class _LineDeliveryPipeline( + final DialogueLine line, + final List views, +) { + this : _completer = Completer(); - final DialogueLine line; - final List views; - final List> _futures; + final List> _futures = List.generate( + views.length, + (i) => null, + growable: false, + ); final Completer _completer; int _numPendingFutures = 0; bool _interrupted = false; @@ -271,7 +272,6 @@ class _LineDeliveryPipeline { for (var i = 0; i < views.length; i++) { final maybeFuture = views[i].onLineStart(line); if (maybeFuture is Future) { - // ignore: cast_nullable_to_non_nullable final future = maybeFuture as Future; _futures[i] = future.then((_) => startCompleted(i)); _numPendingFutures++; @@ -305,7 +305,6 @@ class _LineDeliveryPipeline { for (var i = 0; i < views.length; i++) { final maybeFuture = views[i].onLineFinish(line); if (maybeFuture is Future) { - // ignore: unnecessary_cast final future = maybeFuture as Future; _futures[i] = future.then((_) => finishCompleted(i)); _numPendingFutures++; diff --git a/packages/flame_jenny/jenny/lib/src/dialogue_view.dart b/packages/flame_jenny/jenny/lib/src/dialogue_view.dart index 508418f16a2..0d91d251f93 100644 --- a/packages/flame_jenny/jenny/lib/src/dialogue_view.dart +++ b/packages/flame_jenny/jenny/lib/src/dialogue_view.dart @@ -32,7 +32,7 @@ import 'package:meta/meta.dart'; /// be implemented either synchronously or asynchronously. In the latter case /// the dialogue runner will wait for the future to resolve before proceeding /// (futures from several dialogue views will be awaited simultaneously). -abstract mixin class DialogueView { +abstract mixin class DialogueView() { DialogueRunner? _dialogueRunner; /// The owner of this `DialogueView`. This property will be `null` when the diff --git a/packages/flame_jenny/jenny/lib/src/errors.dart b/packages/flame_jenny/jenny/lib/src/errors.dart index 416b6f9cb15..1e8425b92b2 100644 --- a/packages/flame_jenny/jenny/lib/src/errors.dart +++ b/packages/flame_jenny/jenny/lib/src/errors.dart @@ -1,8 +1,4 @@ -class SyntaxError implements Exception { - SyntaxError(this.message); - - final String? message; - +class SyntaxError(final String? message) implements Exception { @override String toString() => 'SyntaxError: $message'; } @@ -10,29 +6,17 @@ class SyntaxError implements Exception { /// This error is emitted when accessing an unknown name, such as: undefined /// variable name, unknown node title, unrecognized function, unspecified /// command, etc. -class NameError implements Exception { - NameError(this.message); - - final String? message; - +class NameError(final String? message) implements Exception { @override String toString() => 'NameError: $message'; } -class TypeError implements Exception { - TypeError(this.message); - - final String? message; - +class TypeError(final String? message) implements Exception { @override String toString() => 'TypeError: $message'; } -class DialogueError implements Exception { - DialogueError(this.message); - - final String? message; - +class DialogueError(final String? message) implements Exception { @override String toString() => 'DialogueError: $message'; } diff --git a/packages/flame_jenny/jenny/lib/src/function_storage.dart b/packages/flame_jenny/jenny/lib/src/function_storage.dart index b06b9f11fa2..44e8d338951 100644 --- a/packages/flame_jenny/jenny/lib/src/function_storage.dart +++ b/packages/flame_jenny/jenny/lib/src/function_storage.dart @@ -29,9 +29,7 @@ import 'package:meta/meta.dart'; /// The functions must be added to the YarnProject before parsing the yarn /// scripts, since the parser would throw an error if it sees a function which /// it does not recognize. -class FunctionStorage { - FunctionStorage(); - +class FunctionStorage() { /// The central repository of all functions registered in this /// function storage. final Map _functions = {}; @@ -142,19 +140,19 @@ class FunctionStorage { /// This wrapper encapsulates the knowledge about the function signature, and /// is capable of executing the underlying function given a plain list of @internal -class Udf { - Udf(this.name, Type returnType, List types, this._wrappedFn) - : _returnType = _convertReturnType(returnType), - _argumentTypes = _convertArgumentTypes(types), - _nOptionalArguments = _countOptionalArguments(types), - _preparedArguments = List.filled(types.length, null); - - final String name; - final ExpressionType _returnType; - final List<_Type> _argumentTypes; - final int _nOptionalArguments; - final dynamic Function(List) _wrappedFn; - final List _preparedArguments; +class Udf( + final String name, + Type returnType, + List types, + final dynamic Function(List) _wrappedFn, +) { + final ExpressionType _returnType = _convertReturnType(returnType); + final List<_Type> _argumentTypes = _convertArgumentTypes(types); + final int _nOptionalArguments = _countOptionalArguments(types); + final List _preparedArguments = List.filled( + types.length, + null, + ); ExpressionType get returnType => _returnType; @@ -192,7 +190,6 @@ class Udf { final argType = args[i].expression.type; final expectedType = _argumentTypes[i + i0]; final typesAreCompatible = - false || (argType == ExpressionType.boolean && expectedType == _Type.boolean) || (argType == ExpressionType.numeric && @@ -285,7 +282,6 @@ class Udf { var nOptionalArguments = 0; for (final type in types) { final isOptional = - false || (type == _maybeInt) || (type == _maybeBool) || (type == _maybeDouble) || @@ -306,7 +302,7 @@ class Udf { } /// Similar to `ExpressionType`, but also allows `integer` and `double`. -enum _Type { +enum _Type() { boolean, integer, double, diff --git a/packages/flame_jenny/jenny/lib/src/localization.dart b/packages/flame_jenny/jenny/lib/src/localization.dart index 115330ab5f2..290026d8426 100644 --- a/packages/flame_jenny/jenny/lib/src/localization.dart +++ b/packages/flame_jenny/jenny/lib/src/localization.dart @@ -1,12 +1,11 @@ -class Localization { - const Localization( - this.pluralFunction, - this.pluralMinWordCount, [ - int? pluralMaxWordCount, - ]) : pluralMaxWordCount = pluralMaxWordCount ?? pluralMinWordCount; +class const Localization( + final PluralFnType pluralFunction, + final int pluralMinWordCount, [ + int? pluralMaxWordCount, +]) { + // ignore: initialize_in_field_declaration + this : pluralMaxWordCount = pluralMaxWordCount ?? pluralMinWordCount; - final PluralFnType pluralFunction; - final int pluralMinWordCount; final int pluralMaxWordCount; } @@ -133,7 +132,7 @@ String _plural25(num number, List words) { /// The function requires 3 forms of the word: single-, few-, and many-. You /// can think of them as words needed for "1 X", "2 X", and "10 X". For example, /// the words for "рушниця" (rifle) would be: -/// ``` +/// ```text /// plural(n, ["рушниця", "рушниці", "рушниць"]) /// ``` String _plural29(num number, List words) { diff --git a/packages/flame_jenny/jenny/lib/src/parse/parse.dart b/packages/flame_jenny/jenny/lib/src/parse/parse.dart index f142467f6c8..ec577624130 100644 --- a/packages/flame_jenny/jenny/lib/src/parse/parse.dart +++ b/packages/flame_jenny/jenny/lib/src/parse/parse.dart @@ -27,12 +27,13 @@ void parse(String text, YarnProject project) { _Parser(project, text, tokens).parseMain(); } -class _Parser { - _Parser(this.project, this.text, this.tokens) : position = 0; +class _Parser( + final YarnProject project, + final String text, + final List tokens, +) { + this : position = 0; - final YarnProject project; - final String text; - final List tokens; VariableStorage? localVariables; /// The index of the next token to parse. @@ -976,14 +977,9 @@ class _Parser { } } -class _NodeHeader { - _NodeHeader(this.title, this.tags); +class _NodeHeader(var String? title, var Map? tags); - String? title; - Map? tags; -} - -class _Markup { +class _Markup() { bool closing = false; bool selfClosing = false; String? name; diff --git a/packages/flame_jenny/jenny/lib/src/parse/token.dart b/packages/flame_jenny/jenny/lib/src/parse/token.dart index 1d8873d27d3..1ac823ef3d5 100644 --- a/packages/flame_jenny/jenny/lib/src/parse/token.dart +++ b/packages/flame_jenny/jenny/lib/src/parse/token.dart @@ -3,9 +3,7 @@ import 'package:meta/meta.dart'; /// [Token] is a unit of output during the lexing stage. @internal @immutable -class Token { - const Token._(this.type, [this._content]); - +class const Token._(final TokenType type, [final String? _content]) { const Token.command(String text) : this._(TokenType.command, text); const Token.hashtag(String text) : this._(TokenType.hashtag, text); const Token.id(String text) : this._(TokenType.id, text); @@ -80,9 +78,6 @@ class Token { static const typeNumber = Token._(TokenType.typeNumber); static const typeString = Token._(TokenType.typeString); - final TokenType type; - final String? _content; - bool get isCommand => type == TokenType.command; bool get isHashtag => type == TokenType.hashtag; bool get isId => type == TokenType.id; @@ -109,7 +104,7 @@ class Token { } @internal -enum TokenType { +enum TokenType() { command, hashtag, id, diff --git a/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart b/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart index 5043e5884d6..7f3adebf26b 100644 --- a/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart +++ b/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart @@ -28,8 +28,8 @@ List tokenize(String input, {int addErrorTokenAtIndex = -2}) { /// newline tokens; /// - The lexer is deterministic: given the same input, it should always /// produce the same output. -class _Lexer { - _Lexer(this.text, this.addErrorTokenAtIndex) +class _Lexer(final String text, final int addErrorTokenAtIndex) { + this : position = 0, lineNumber = 1, lineStart = 0, @@ -43,11 +43,9 @@ class _Lexer { nodeTargetingCommands.length, ); - final String text; final List tokens; final List<_ModeFn> modeStack; final List indentStack; - final int addErrorTokenAtIndex; /// Current parsing position, an offset within the [text]. int position; @@ -230,8 +228,7 @@ class _Lexer { bool modeCommand() { return eatWhitespace() || (eatCommandName() && - (false || // subsequent mode will depend on the command type - (simpleCommands.contains(tokens.last)) || + ((simpleCommands.contains(tokens.last)) || (bareExpressionCommands.contains(tokens.last) && pushToken(Token.startExpression, position) && pushMode(modeCommandExpression)) || diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/character_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/character_command.dart index 72da10b3459..199465539b1 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/character_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/character_command.dart @@ -1,9 +1,7 @@ import 'package:jenny/src/dialogue_runner.dart'; import 'package:jenny/src/structure/commands/command.dart'; -class CharacterCommand extends Command { - const CharacterCommand(); - +class const CharacterCommand() extends Command { @override String get name => 'character'; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/command.dart index cf6e068edc3..3102527f795 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/command.dart @@ -3,9 +3,7 @@ import 'dart:async'; import 'package:jenny/src/dialogue_runner.dart'; import 'package:jenny/src/structure/dialogue_entry.dart'; -abstract class Command extends DialogueEntry { - const Command(); - +abstract class const Command() extends DialogueEntry { FutureOr execute(DialogueRunner dialogue); String get name; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/declare_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/declare_command.dart index 6e79d76804f..2bb157bb40c 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/declare_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/declare_command.dart @@ -13,14 +13,12 @@ import 'package:jenny/src/structure/commands/command.dart'; /// parsing, and will never be seen by a dialogue runner. /// /// The command itself can take one of the several forms: -/// ``` +/// ```yarn /// <> /// <> // initial value will be 0 /// <> /// ``` -class DeclareCommand extends Command { - const DeclareCommand(); - +class const DeclareCommand() extends Command { @override String get name => 'declare'; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/if_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/if_command.dart index 74c1c5ebb4e..097ca2bebb1 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/if_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/if_command.dart @@ -3,15 +3,13 @@ import 'package:jenny/src/structure/block.dart'; import 'package:jenny/src/structure/commands/command.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; -class IfCommand extends Command { - const IfCommand(this.ifs); - +class const IfCommand( /// First entry here is the `<>` command, subsequent entries are the /// `<>` commands, and the last entry is the `<>` block (if /// present), which is represented as an [IfBlock] with `condition = /// constTrue`. - final List ifs; - + final List ifs, +) extends Command { @override String get name => 'if'; @@ -26,9 +24,4 @@ class IfCommand extends Command { } } -class IfBlock { - const IfBlock(this.condition, this.block); - - final BoolExpression condition; - final Block block; -} +class const IfBlock(final BoolExpression condition, final Block block); diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/jump_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/jump_command.dart index df7a09dc66f..532a3756714 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/jump_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/jump_command.dart @@ -2,11 +2,7 @@ import 'package:jenny/src/dialogue_runner.dart'; import 'package:jenny/src/structure/commands/command.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; -class JumpCommand extends Command { - const JumpCommand(this.target); - - final StringExpression target; - +class const JumpCommand(final StringExpression target) extends Command { @override String get name => 'jump'; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/local_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/local_command.dart index 9f69bf2b11e..93f39fe2ace 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/local_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/local_command.dart @@ -3,13 +3,11 @@ import 'package:jenny/src/structure/commands/command.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/variable_storage.dart'; -class LocalCommand extends Command { - const LocalCommand(this.variable, this.expression, this.storage); - - final String variable; - final Expression expression; - final VariableStorage storage; - +class const LocalCommand( + final String variable, + final Expression expression, + final VariableStorage storage, +) extends Command { @override String get name => 'local'; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/set_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/set_command.dart index afd5644ccda..46cb1c067dc 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/set_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/set_command.dart @@ -3,13 +3,11 @@ import 'package:jenny/src/structure/commands/command.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/variable_storage.dart'; -class SetCommand extends Command { - const SetCommand(this.variable, this.expression, this.storage); - - final String variable; - final Expression expression; - final VariableStorage storage; - +class const SetCommand( + final String variable, + final Expression expression, + final VariableStorage storage, +) extends Command { @override String get name => 'set'; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/stop_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/stop_command.dart index c93cca23804..3dae87f36da 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/stop_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/stop_command.dart @@ -1,9 +1,7 @@ import 'package:jenny/src/dialogue_runner.dart'; import 'package:jenny/src/structure/commands/command.dart'; -class StopCommand extends Command { - const StopCommand(); - +class const StopCommand() extends Command { @override String get name => 'stop'; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/user_defined_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/user_defined_command.dart index 524bc1598ea..3b57c237953 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/user_defined_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/user_defined_command.dart @@ -5,12 +5,10 @@ import 'package:jenny/src/structure/commands/command.dart'; import 'package:jenny/src/structure/line_content.dart'; import 'package:meta/meta.dart'; -class UserDefinedCommand extends Command { - UserDefinedCommand(this.name, this._content); - - @override - final String name; - final LineContent _content; +class UserDefinedCommand( + @override final String name, + final LineContent _content, +) extends Command { late String _argumentString; late List? _arguments; diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/visit_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/visit_command.dart index e490616a083..8b5f4337c56 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/visit_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/visit_command.dart @@ -2,11 +2,7 @@ import 'package:jenny/src/dialogue_runner.dart'; import 'package:jenny/src/structure/commands/command.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; -class VisitCommand extends Command { - VisitCommand(this.target); - - final StringExpression target; - +class VisitCommand(final StringExpression target) extends Command { @override Future execute(DialogueRunner dialogue) { return dialogue.visitNode(target.value); diff --git a/packages/flame_jenny/jenny/lib/src/structure/commands/wait_command.dart b/packages/flame_jenny/jenny/lib/src/structure/commands/wait_command.dart index 9b945eb3ace..c2c8a570d2f 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/commands/wait_command.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/commands/wait_command.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/errors.dart'; import 'package:jenny/src/structure/commands/command.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; -class WaitCommand extends Command { - const WaitCommand(this.arg); - - final NumExpression arg; - +class const WaitCommand(final NumExpression arg) extends Command { @override String get name => 'wait'; diff --git a/packages/flame_jenny/jenny/lib/src/structure/dialogue_choice.dart b/packages/flame_jenny/jenny/lib/src/structure/dialogue_choice.dart index 981bc961619..895045bde9d 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/dialogue_choice.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/dialogue_choice.dart @@ -2,11 +2,8 @@ import 'package:jenny/src/dialogue_runner.dart'; import 'package:jenny/src/structure/dialogue_entry.dart'; import 'package:jenny/src/structure/dialogue_option.dart'; -class DialogueChoice extends DialogueEntry { - const DialogueChoice(this.options); - - final List options; - +class const DialogueChoice(final List options) + extends DialogueEntry { @override Future processInDialogueRunner(DialogueRunner dialogueRunner) { for (final option in options) { diff --git a/packages/flame_jenny/jenny/lib/src/structure/dialogue_entry.dart b/packages/flame_jenny/jenny/lib/src/structure/dialogue_entry.dart index d9bdc7b17dd..3264250edc5 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/dialogue_entry.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/dialogue_entry.dart @@ -12,9 +12,7 @@ import 'package:jenny/src/structure/dialogue_line.dart'; /// - [Command] /// - [DialogueChoice] /// - [DialogueLine] -abstract class DialogueEntry { - const DialogueEntry(); - +abstract class const DialogueEntry() { /// Runs the entry within the context of a dialogue runner. /// /// This method is invoked by the [dialogueRunner] itself, at the right time. diff --git a/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart b/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart index bb6701e26cd..a75eefbda1b 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart @@ -41,17 +41,12 @@ import 'package:jenny/src/structure/line_content.dart'; /// with parameter `color` around the word "vantablack". /// /// Inline expressions cannot contain markup attributes. -class DialogueLine extends DialogueEntry { - DialogueLine({ - required this._content, - this._character, - this._tags, - }) : _value = _content.isConst ? _content.text : null; - - final Character? _character; - final List? _tags; - final LineContent _content; - String? _value; +class DialogueLine({ + required final LineContent _content, + final Character? _character, + final List? _tags, +}) extends DialogueEntry { + String? _value = _content.isConst ? _content.text : null; /// The content of this Line. LineContent? get content => _content; diff --git a/packages/flame_jenny/jenny/lib/src/structure/dialogue_option.dart b/packages/flame_jenny/jenny/lib/src/structure/dialogue_option.dart index 9e949f6edeb..581f0a6bd00 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/dialogue_option.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/dialogue_option.dart @@ -2,17 +2,13 @@ import 'package:jenny/src/structure/block.dart'; import 'package:jenny/src/structure/dialogue_line.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; -class DialogueOption extends DialogueLine { - DialogueOption({ - required super.content, - super.character, - super.tags, - this._condition, - this.block = const Block([]), - }); - - final BoolExpression? _condition; - final Block block; +class DialogueOption({ + required super.content, + super.character, + super.tags, + final BoolExpression? _condition, + final Block block = const Block([]), +}) extends DialogueLine { bool _available = true; bool get isAvailable => _available; diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/expression.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/expression.dart index 3c3eae06c1e..2ceee4d33f6 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/expression.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/expression.dart @@ -1,6 +1,4 @@ -abstract class Expression { - const Expression(); - +abstract class const Expression() { dynamic get value; bool get isNumeric => type == ExpressionType.numeric; @@ -17,30 +15,24 @@ abstract class Expression { } } -enum ExpressionType { +enum ExpressionType() { unknown, boolean, numeric, string, } -abstract class NumExpression extends Expression { - const NumExpression(); - +abstract class const NumExpression() extends Expression { @override num get value; } -abstract class StringExpression extends Expression { - const StringExpression(); - +abstract class const StringExpression() extends Expression { @override String get value; } -abstract class BoolExpression extends Expression { - const BoolExpression(); - +abstract class const BoolExpression() extends Expression { @override bool get value; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart index 9d5a4fb206e..918a28eeaf6 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart @@ -22,18 +22,13 @@ import 'package:meta/meta.dart'; typedef ErrorFn = Never Function(String message, [int? position]); -class FunctionArgument { - FunctionArgument(this.expression, this.position); - final Expression expression; - final int position; -} +class FunctionArgument(final Expression expression, final int position); -typedef FunctionBuilder = - Expression Function( - List, - YarnProject, - ErrorFn, - ); +typedef FunctionBuilder = Expression Function( + List, + YarnProject, + ErrorFn, +); /// This is a complete list of all builtin functions in Jenny. /// diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/bool.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/bool.dart index d471171efe9..6f659295615 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/bool.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/bool.dart @@ -7,11 +7,7 @@ import 'package:jenny/src/yarn_project.dart'; /// /// If `x` is numeric, then the value 0 becomes `false` and all other values /// become `true`. -class BoolFn extends BoolExpression { - const BoolFn(this._arg); - - final Expression _arg; - +class const BoolFn(final Expression _arg) extends BoolExpression { /// Static constructor to be used in parse.dart. static Expression make( List args, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart index a61b428eeaf..27e9a758f81 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `ceil(x)` will round `x` up towards positive infinity. -class CeilFn extends NumExpression { - const CeilFn(this.arg); - - final NumExpression arg; - +class const CeilFn(final NumExpression arg) extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart index ed6246a0aeb..bc3eee278e1 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart @@ -4,11 +4,7 @@ import 'package:jenny/src/yarn_project.dart'; /// Function `dec(x)` decreases `x` towards previous integer. It is equal to /// `x - 1` if `x` is already integer, or `floor(x)` if `x` is not integer. -class DecFn extends NumExpression { - const DecFn(this.arg); - - final NumExpression arg; - +class const DecFn(final NumExpression arg) extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart index 56f5633579c..75551f87bc4 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart @@ -7,11 +7,7 @@ import 'package:jenny/src/yarn_project.dart'; /// For positive `x` the value is from 0 to 1, for negative `x` the value is /// between 0 and -1. For any `x` it should be true that /// `x == int(x) + decimal(x)`. -class DecimalFn extends NumExpression { - const DecimalFn(this.arg); - - final NumExpression arg; - +class const DecimalFn(final NumExpression arg) extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dice.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dice.dart index 8790ee1b936..af404e6b290 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dice.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dice.dart @@ -4,12 +4,8 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `dice(n)` returns a random integer between 1 and `n`, inclusive. -class DiceFn extends NumExpression { - const DiceFn(this._n, this._yarn); - - final NumExpression _n; - final YarnProject _yarn; - +class const DiceFn(final NumExpression _n, final YarnProject _yarn) + extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart index 497bd6fc40a..6628748a3b9 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `floor(x)` will round `x` down towards negative infinity. -class FloorFn extends NumExpression { - const FloorFn(this.arg); - - final NumExpression arg; - +class const FloorFn(final NumExpression arg) extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/if.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/if.dart index a1964d5dbf7..1ed417937c3 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/if.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/if.dart @@ -50,35 +50,29 @@ Expression makeIfFn( } } -class _IfFnBoolean extends BoolExpression { - _IfFnBoolean(this._condition, this._then, this._else); - - final BoolExpression _condition; - final BoolExpression _then; - final BoolExpression _else; - +class _IfFnBoolean( + final BoolExpression _condition, + final BoolExpression _then, + final BoolExpression _else, +) extends BoolExpression { @override bool get value => _condition.value ? _then.value : _else.value; } -class _IfFnNumeric extends NumExpression { - _IfFnNumeric(this._condition, this._then, this._else); - - final BoolExpression _condition; - final NumExpression _then; - final NumExpression _else; - +class _IfFnNumeric( + final BoolExpression _condition, + final NumExpression _then, + final NumExpression _else, +) extends NumExpression { @override num get value => _condition.value ? _then.value : _else.value; } -class _IfFnString extends StringExpression { - _IfFnString(this._condition, this._then, this._else); - - final BoolExpression _condition; - final StringExpression _then; - final StringExpression _else; - +class _IfFnString( + final BoolExpression _condition, + final StringExpression _then, + final StringExpression _else, +) extends StringExpression { @override String get value => _condition.value ? _then.value : _else.value; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart index b55ab026aea..c925d99125d 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart @@ -4,11 +4,7 @@ import 'package:jenny/src/yarn_project.dart'; /// Function `inc(x)` increases `x` towards next integer. It is equal to `x + 1` /// if `x` is already integer, or `ceil(x)` if `x` is not integer. -class IncFn extends NumExpression { - const IncFn(this.arg); - - final NumExpression arg; - +class const IncFn(final NumExpression arg) extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart index 4687810aef5..8a98badbdce 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `int(x)` truncates fractional part of `x`, rounding it towards 0. -class IntFn extends NumExpression { - const IntFn(this.arg); - - final NumExpression arg; - +class const IntFn(final NumExpression arg) extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/number.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/number.dart index 1246a33e7de..1440aeae88e 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/number.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/number.dart @@ -7,11 +7,7 @@ import 'package:jenny/src/yarn_project.dart'; /// /// If `x` is boolean, then it will be converted into numbers 0 or 1. If `x` is /// a string, then -class NumberFn extends NumExpression { - const NumberFn(this._arg); - - final Expression _arg; - +class const NumberFn(final Expression _arg) extends NumExpression { /// Static constructor to be used in parse.dart. static Expression make( List args, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/plural.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/plural.dart index 6c3f53136cd..8e02ee980dd 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/plural.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/plural.dart @@ -2,13 +2,11 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; -class PluralFn extends StringExpression { - PluralFn(this._num, this._words, this._yarn); - - final NumExpression _num; - final List _words; - final YarnProject _yarn; - +class PluralFn( + final NumExpression _num, + final List _words, + final YarnProject _yarn, +) extends StringExpression { /// Static constructor, used by parse.dart. static Expression make( List arguments, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random.dart index e05ee124363..4750445abd1 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `random()` returns a random double between 0 and 1. -class RandomFn extends NumExpression { - RandomFn(this._yarn); - - final YarnProject _yarn; - +class RandomFn(final YarnProject _yarn) extends NumExpression { static Expression make( List arguments, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random_range.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random_range.dart index 6927e92440e..006004f15ed 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random_range.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/random_range.dart @@ -5,13 +5,11 @@ import 'package:jenny/src/yarn_project.dart'; /// Function `random_range(a, b)` returns a random integer between `a` and `b`, /// inclusive. -class RandomRangeFn extends NumExpression { - const RandomRangeFn(this._a, this._b, this._yarn); - - final NumExpression _a; - final NumExpression _b; - final YarnProject _yarn; - +class const RandomRangeFn( + final NumExpression _a, + final NumExpression _b, + final YarnProject _yarn, +) extends NumExpression { /// Static constructor, used by parse.dart. static Expression make( List args, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart index e534aeb0578..e1c48fa45b4 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `round(x)` will round `x` to the nearest integer. -class RoundFn extends NumExpression { - const RoundFn(this.arg); - - final NumExpression arg; - +class const RoundFn(final NumExpression arg) extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round_places.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round_places.dart index 520a7935245..c6a6f78f7b3 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round_places.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round_places.dart @@ -5,12 +5,8 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `round_places(x, n)` will round `x` to `n` decimal places. -class RoundPlacesFn extends NumExpression { - const RoundPlacesFn(this.arg, this.places); - - final NumExpression arg; - final NumExpression places; - +class const RoundPlacesFn(final NumExpression arg, final NumExpression places) + extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/string.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/string.dart index 6b63db453dd..d0f4102581f 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/string.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/string.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; /// Function `string(x)` converts a numeric or boolean `x` into a string. -class StringFn extends StringExpression { - StringFn(this._arg); - - final Expression _arg; - +class StringFn(final Expression _arg) extends StringExpression { /// Static constructor to be used in parse.dart. static Expression make( List args, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/user_defined_function.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/user_defined_function.dart index 62b1ef9c1eb..3a4cb6487a7 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/user_defined_function.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/user_defined_function.dart @@ -2,34 +2,22 @@ import 'package:jenny/src/function_storage.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; /// Expression for a user-defined function that returns a numeric result. -class NumericUserDefinedFn extends NumExpression { - NumericUserDefinedFn(this._udf, this._arguments); - - final Udf _udf; - final List _arguments; - +class NumericUserDefinedFn(final Udf _udf, final List _arguments) + extends NumExpression { @override num get value => _udf.run(_arguments) as num; } /// Expression for a user-defined function that returns a boolean result. -class BooleanUserDefinedFn extends BoolExpression { - BooleanUserDefinedFn(this._udf, this._arguments); - - final Udf _udf; - final List _arguments; - +class BooleanUserDefinedFn(final Udf _udf, final List _arguments) + extends BoolExpression { @override bool get value => _udf.run(_arguments) as bool; } /// Expression for a user-defined function that returns a string result. -class StringUserDefinedFn extends StringExpression { - StringUserDefinedFn(this._udf, this._arguments); - - final Udf _udf; - final List _arguments; - +class StringUserDefinedFn(final Udf _udf, final List _arguments) + extends StringExpression { @override String get value => _udf.run(_arguments) as String; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visit_count.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visit_count.dart index 478b0b99db1..2d26feae480 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visit_count.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visit_count.dart @@ -3,12 +3,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; -class VisitCountFn extends NumExpression { - VisitCountFn(this._node, this._yarn); - - final StringExpression _node; - final YarnProject _yarn; - +class VisitCountFn(final StringExpression _node, final YarnProject _yarn) + extends NumExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visited.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visited.dart index fc5c165ca88..b9c72075651 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visited.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/visited.dart @@ -3,12 +3,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/functions/_common.dart'; import 'package:jenny/src/yarn_project.dart'; -class VisitedFn extends BoolExpression { - VisitedFn(this._node, this._yarn); - - final StringExpression _node; - final YarnProject _yarn; - +class VisitedFn(final StringExpression _node, final YarnProject _yarn) + extends BoolExpression { static Expression make( List args, YarnProject yarnProject, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/literal.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/literal.dart index 9f31ef89271..8be1bdd334f 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/literal.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/literal.dart @@ -1,30 +1,14 @@ import 'package:jenny/src/structure/expressions/expression.dart'; -class NumLiteral extends NumExpression { - const NumLiteral(this.value); +class const NumLiteral(@override final num value) extends NumExpression; - @override - final num value; -} - -class StringLiteral extends StringExpression { - const StringLiteral(this.value); - - @override - final String value; -} - -class BoolLiteral extends BoolExpression { - // ignore: avoid_positional_boolean_parameters - const BoolLiteral(this.value); - - @override - final bool value; -} +class const StringLiteral(@override final String value) + extends StringExpression; -class VoidLiteral extends Expression { - const VoidLiteral(); +// ignore: avoid_positional_boolean_parameters +class const BoolLiteral(@override final bool value) extends BoolExpression; +class const VoidLiteral() extends Expression { @override dynamic get value => null; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart index 4e6a7358536..fb0a541befa 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart @@ -16,13 +16,12 @@ import 'package:jenny/src/structure/expressions/operators/subtract.dart'; import 'package:jenny/src/structure/expressions/operators/xor.dart'; typedef ErrorFn = Never Function(String message, [int? position]); -typedef BinaryOperatorBuilder = - Expression Function( - Expression lhs, - Expression rhs, - int operatorPosition, - ErrorFn errorFn, - ); +typedef BinaryOperatorBuilder = Expression Function( + Expression lhs, + Expression rhs, + int operatorPosition, + ErrorFn errorFn, +); /// Static constructor of expressions involving binary operators. Used by /// parse.dart. diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/add.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/add.dart index 4f20498fe5e..8fe74c21b00 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/add.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/add.dart @@ -25,24 +25,18 @@ abstract class Add extends Expression { } /// Operator PLUS (+) for numeric arguments. -class _NumAdd extends NumExpression implements Add { - _NumAdd(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class _NumAdd(final NumExpression _lhs, final NumExpression _rhs) + extends NumExpression + implements Add { @override num get value => _lhs.value + _rhs.value; } /// Operator PLUS (+) for string arguments. This operator simply concatenates /// strings. -class _StringAdd extends StringExpression implements Add { - _StringAdd(this._lhs, this._rhs); - - final StringExpression _lhs; - final StringExpression _rhs; - +class _StringAdd(final StringExpression _lhs, final StringExpression _rhs) + extends StringExpression + implements Add { @override String get value => _lhs.value + _rhs.value; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/and.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/and.dart index 6566558bfdf..19b806b7acf 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/and.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/and.dart @@ -5,12 +5,8 @@ import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// /// The AND operator returns `true` if both of its operands are `true`, and /// `false` otherwise. -class And extends BoolExpression { - And(this._lhs, this._rhs); - - final BoolExpression _lhs; - final BoolExpression _rhs; - +class And(final BoolExpression _lhs, final BoolExpression _rhs) + extends BoolExpression { /// Static constructor, used by parse.dart. factory And.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/divide.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/divide.dart index bc54561a2f4..e5be4d038ef 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/divide.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/divide.dart @@ -3,12 +3,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// Operator DIVIDE (/), applies to numeric arguments only. -class Divide extends NumExpression { - const Divide(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const Divide(final NumExpression _lhs, final NumExpression _rhs) + extends NumExpression { /// Static constructor, used by parse.dart factory Divide.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/equal.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/equal.dart index f54a2dc6220..7e477949f09 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/equal.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/equal.dart @@ -28,34 +28,26 @@ abstract class Equal extends Expression { } /// Operator EQUAL (==) for numeric arguments. -class _NumericEqual extends BoolExpression implements Equal { - const _NumericEqual(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const _NumericEqual(final NumExpression _lhs, final NumExpression _rhs) + extends BoolExpression + implements Equal { @override bool get value => _lhs.value == _rhs.value; } /// Operator EQUAL (==) for string arguments. -class _StringEqual extends BoolExpression implements Equal { - const _StringEqual(this._lhs, this._rhs); - - final StringExpression _lhs; - final StringExpression _rhs; - +class const _StringEqual( + final StringExpression _lhs, + final StringExpression _rhs, +) extends BoolExpression implements Equal { @override bool get value => _lhs.value == _rhs.value; } /// Operator EQUAL (==) for boolean arguments. -class _BooleanEqual extends BoolExpression implements Equal { - const _BooleanEqual(this._lhs, this._rhs); - - final BoolExpression _lhs; - final BoolExpression _rhs; - +class const _BooleanEqual(final BoolExpression _lhs, final BoolExpression _rhs) + extends BoolExpression + implements Equal { @override bool get value => _lhs.value == _rhs.value; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_or_equal.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_or_equal.dart index a5525cd7d37..08524f8afc8 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_or_equal.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_or_equal.dart @@ -2,12 +2,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// Operator GREATER_OR_EQUAL (>=), applies to numeric operands only. -class GreaterOrEqual extends BoolExpression { - const GreaterOrEqual(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const GreaterOrEqual(final NumExpression _lhs, final NumExpression _rhs) + extends BoolExpression { /// Static constructor, used by parse.dart factory GreaterOrEqual.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_than.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_than.dart index a9ef50cbc8b..44f3137c728 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_than.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/greater_than.dart @@ -2,12 +2,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// Operator GREATER_THAN(>), applies to numeric operands only. -class GreaterThan extends BoolExpression { - const GreaterThan(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const GreaterThan(final NumExpression _lhs, final NumExpression _rhs) + extends BoolExpression { /// Static constructor, used by parse.dart factory GreaterThan.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_or_equal.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_or_equal.dart index 7949c691de3..819090e060e 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_or_equal.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_or_equal.dart @@ -2,12 +2,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// Operator LESS_OR_EQUAL (<=), applies to numeric operands only. -class LessOrEqual extends BoolExpression { - const LessOrEqual(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const LessOrEqual(final NumExpression _lhs, final NumExpression _rhs) + extends BoolExpression { /// Static constructor, used by parse.dart factory LessOrEqual.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_than.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_than.dart index a7b91222566..3346b98c621 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_than.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/less_than.dart @@ -2,12 +2,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// Operator LESS_THAN (<), applies to numeric operands only. -class LessThan extends BoolExpression { - const LessThan(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const LessThan(final NumExpression _lhs, final NumExpression _rhs) + extends BoolExpression { /// Static constructor, used by parse.dart factory LessThan.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/modulo.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/modulo.dart index f7434e43f00..78f1a681d17 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/modulo.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/modulo.dart @@ -6,12 +6,8 @@ import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// /// The divisor of a modulo must be a positive number. The result of `x % y` is /// always a number between 0 and `y`, regardless of the sign of `x`. -class Modulo extends NumExpression { - const Modulo(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const Modulo(final NumExpression _lhs, final NumExpression _rhs) + extends NumExpression { /// Static constructor, used by parse.dart factory Modulo.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/multiply.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/multiply.dart index 72b5faa8ff5..e18b26a5ab0 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/multiply.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/multiply.dart @@ -2,12 +2,8 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// Operator MULTIPLY (*), applies to numeric arguments only. -class Multiply extends NumExpression { - const Multiply(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const Multiply(final NumExpression _lhs, final NumExpression _rhs) + extends NumExpression { /// Static constructor, used by parse.dart factory Multiply.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/negate.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/negate.dart index c1acee779dd..966877b1456 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/negate.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/negate.dart @@ -1,11 +1,7 @@ import 'package:jenny/src/structure/expressions/expression.dart'; /// Operator UNARY MINUS (-). -class Negate extends NumExpression { - const Negate(this._arg); - - final NumExpression _arg; - +class const Negate(final NumExpression _arg) extends NumExpression { @override num get value => -_arg.value; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not.dart index d3fd76e2942..38012dfae09 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not.dart @@ -3,11 +3,7 @@ import 'package:jenny/src/structure/expressions/expression.dart'; /// Logical NOT applied to a boolean expression. /// /// In a Yarn script this can be written as `!x` or `not x`. -class Not extends BoolExpression { - Not(this._arg); - - final BoolExpression _arg; - +class Not(final BoolExpression _arg) extends BoolExpression { @override bool get value => !_arg.value; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not_equal.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not_equal.dart index a4d0c62c9f5..8ccf7a4b6dc 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not_equal.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/not_equal.dart @@ -28,34 +28,27 @@ abstract class NotEqual extends Expression { } /// Operator NOT_EQUAL (!=) for numeric arguments. -class _NumericNotEqual extends BoolExpression implements NotEqual { - const _NumericNotEqual(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class const _NumericNotEqual(final NumExpression _lhs, final NumExpression _rhs) + extends BoolExpression + implements NotEqual { @override bool get value => _lhs.value != _rhs.value; } /// Operator NOT_EQUAL (!=) for string arguments. -class _StringNotEqual extends BoolExpression implements NotEqual { - const _StringNotEqual(this._lhs, this._rhs); - - final StringExpression _lhs; - final StringExpression _rhs; - +class const _StringNotEqual( + final StringExpression _lhs, + final StringExpression _rhs, +) extends BoolExpression implements NotEqual { @override bool get value => _lhs.value != _rhs.value; } /// Operator NOT_EQUAL (!=) for boolean arguments. -class _BooleanNotEqual extends BoolExpression implements NotEqual { - const _BooleanNotEqual(this._lhs, this._rhs); - - final BoolExpression _lhs; - final BoolExpression _rhs; - +class const _BooleanNotEqual( + final BoolExpression _lhs, + final BoolExpression _rhs, +) extends BoolExpression implements NotEqual { @override bool get value => _lhs.value != _rhs.value; } diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/or.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/or.dart index beac74802f9..b76e85caee1 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/or.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/or.dart @@ -5,12 +5,8 @@ import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// /// The OR operator returns `false` if both of its operands are `false`, and /// `true` otherwise. -class Or extends BoolExpression { - const Or(this._lhs, this._rhs); - - final BoolExpression _lhs; - final BoolExpression _rhs; - +class const Or(final BoolExpression _lhs, final BoolExpression _rhs) + extends BoolExpression { factory Or.make( Expression lhs, Expression rhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/subtract.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/subtract.dart index 00c080618b2..fc0893585b0 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/subtract.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/subtract.dart @@ -25,12 +25,9 @@ abstract class Subtract extends Expression { } /// Operator MINUS (-) for numeric arguments. -class _NumSubtract extends NumExpression implements Subtract { - _NumSubtract(this._lhs, this._rhs); - - final NumExpression _lhs; - final NumExpression _rhs; - +class _NumSubtract(final NumExpression _lhs, final NumExpression _rhs) + extends NumExpression + implements Subtract { @override num get value => _lhs.value - _rhs.value; } @@ -40,12 +37,9 @@ class _NumSubtract extends NumExpression implements Subtract { /// In the expression `x - y`, the first occurrence of string `y` is removed /// from `x`. For example, `"YarnSpinner" - "n" == "YarSpinner"`. If there is /// no string `y` in `x`, then `x` is returned unmodified. -class _StringSubtract extends StringExpression implements Subtract { - _StringSubtract(this._lhs, this._rhs); - - final StringExpression _lhs; - final StringExpression _rhs; - +class _StringSubtract(final StringExpression _lhs, final StringExpression _rhs) + extends StringExpression + implements Subtract { @override String get value { final lhsValue = _lhs.value; diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/xor.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/xor.dart index f63ac6dd87a..8a8197d10aa 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/xor.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/xor.dart @@ -5,12 +5,8 @@ import 'package:jenny/src/structure/expressions/operators/_common.dart'; /// /// The XOR operator returns `false` when both of its operands are the same, /// and `true` when they are different. -class Xor extends BoolExpression { - Xor(this._lhs, this._rhs); - - final BoolExpression _lhs; - final BoolExpression _rhs; - +class Xor(final BoolExpression _lhs, final BoolExpression _rhs) + extends BoolExpression { /// Static constructor, used by parse.dart. factory Xor.make( Expression lhs, diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/variables.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/variables.dart index d28d6726972..c67157e16bc 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/variables.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/variables.dart @@ -1,32 +1,20 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/variable_storage.dart'; -class NumericVariable extends NumExpression { - const NumericVariable(this.name, this.storage); - - final String name; - final VariableStorage storage; - +class const NumericVariable(final String name, final VariableStorage storage) + extends NumExpression { @override num get value => storage.getNumericValue(name); } -class StringVariable extends StringExpression { - const StringVariable(this.name, this.storage); - - final String name; - final VariableStorage storage; - +class const StringVariable(final String name, final VariableStorage storage) + extends StringExpression { @override String get value => storage.getStringValue(name); } -class BooleanVariable extends BoolExpression { - const BooleanVariable(this.name, this.storage); - - final String name; - final VariableStorage storage; - +class const BooleanVariable(final String name, final VariableStorage storage) + extends BoolExpression { @override bool get value => storage.getBooleanValue(name); } diff --git a/packages/flame_jenny/jenny/lib/src/structure/line_content.dart b/packages/flame_jenny/jenny/lib/src/structure/line_content.dart index a8048eac1b6..c47d4c16428 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/line_content.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/line_content.dart @@ -5,13 +5,11 @@ import 'package:meta/meta.dart'; /// The content of a single line in a dialogue. This contains both regular text, /// inline expressions, and markup attributes. @internal -class LineContent { - LineContent(this.text, [this.expressions, this.attributes]); - - final String text; - final List? expressions; - final List? attributes; - +class LineContent( + final String text, [ + final List? expressions, + final List? attributes, +]) { bool get isConst => expressions == null; /// Evaluates the line, substituting all inline expressions, and updating the @@ -43,8 +41,4 @@ class LineContent { } @internal -class InlineExpression { - InlineExpression(this.position, this.expression); - final int position; - final StringExpression expression; -} +class InlineExpression(final int position, final StringExpression expression); diff --git a/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart b/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart index 00a5587502c..8806b3b4026 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart @@ -1,28 +1,25 @@ import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:meta/meta.dart'; -class MarkupAttribute { - MarkupAttribute( - this._name, - int startTextPosition, - int endTextPosition, [ - int startSubIndex = 0, - int endSubIndex = 1, - Map? parameters, - ]) : _startTextPosition = startTextPosition + startSubIndex * _subFactor, - _endTextPosition = endTextPosition + endSubIndex * _subFactor, - _start = 0, - _end = 0, - _parameterExpressions = parameters, - _parameterValues = parameters == null ? null : {} { +class MarkupAttribute( + final String _name, + int startTextPosition, + int endTextPosition, [ + int startSubIndex = 0, + int endSubIndex = 1, + Map? parameters, +]) { + this : _start = 0, _end = 0 { reset(); } - final String _name; - final double _startTextPosition; - final double _endTextPosition; - final Map? _parameterExpressions; - final Map? _parameterValues; + final double _startTextPosition = + startTextPosition + startSubIndex * _subFactor; + final double _endTextPosition = endTextPosition + endSubIndex * _subFactor; + final Map? _parameterExpressions = parameters; + final Map? _parameterValues = parameters == null + ? null + : {}; int _start; int _end; diff --git a/packages/flame_jenny/jenny/lib/src/structure/node.dart b/packages/flame_jenny/jenny/lib/src/structure/node.dart index fc35af48aae..b59b8aa79a4 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/node.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/node.dart @@ -3,19 +3,12 @@ import 'package:jenny/src/structure/block.dart'; import 'package:jenny/src/structure/dialogue_entry.dart'; import 'package:meta/meta.dart'; -class Node extends Iterable { - const Node({ - required this.title, - required this._content, - this._tags, - this._variables, - }); - - final String title; - final Map? _tags; - final Block _content; - final VariableStorage? _variables; - +class const Node({ + required final String title, + required final Block _content, + final Map? _tags, + final VariableStorage? _variables, +}) extends Iterable { /// The list of extra tags specified in the node header. Map get tags => _tags ?? const {}; @@ -34,12 +27,11 @@ class Node extends Iterable { String toString() => 'Node($title)'; } -class NodeIterator implements Iterator { - NodeIterator(this.node) { +class NodeIterator(final Node node) implements Iterator { + this { diveInto(node._content); } - final Node node; final List blocks = []; final List multiIndex = []; diff --git a/packages/flame_jenny/jenny/lib/src/variable_storage.dart b/packages/flame_jenny/jenny/lib/src/variable_storage.dart index 0a8de9fe242..a551a35a236 100644 --- a/packages/flame_jenny/jenny/lib/src/variable_storage.dart +++ b/packages/flame_jenny/jenny/lib/src/variable_storage.dart @@ -2,7 +2,7 @@ import 'package:jenny/src/errors.dart'; import 'package:jenny/src/structure/expressions/expression.dart'; import 'package:jenny/src/structure/expressions/variables.dart'; -class VariableStorage { +class VariableStorage() { final Map variables = {}; int get length => variables.length; diff --git a/packages/flame_jenny/jenny/lib/src/yarn_project.dart b/packages/flame_jenny/jenny/lib/src/yarn_project.dart index 8eaea1e5bd0..109de65d87f 100644 --- a/packages/flame_jenny/jenny/lib/src/yarn_project.dart +++ b/packages/flame_jenny/jenny/lib/src/yarn_project.dart @@ -18,8 +18,8 @@ import 'package:meta/meta.dart'; /// - [functions]: user-defined functions; /// - [commands]: user-defined commands; /// -class YarnProject { - YarnProject() +class YarnProject() { + this : nodes = {}, variables = VariableStorage(), functions = FunctionStorage(), diff --git a/packages/flame_jenny/jenny/pubspec.yaml b/packages/flame_jenny/jenny/pubspec.yaml index b8d270306bc..580c6762aae 100644 --- a/packages/flame_jenny/jenny/pubspec.yaml +++ b/packages/flame_jenny/jenny/pubspec.yaml @@ -13,7 +13,7 @@ topics: - text environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: meta: ^1.12.0 diff --git a/packages/flame_jenny/jenny/test/dialogue_runner_test.dart b/packages/flame_jenny/jenny/test/dialogue_runner_test.dart index 218105eac6a..70be0d28847 100644 --- a/packages/flame_jenny/jenny/test/dialogue_runner_test.dart +++ b/packages/flame_jenny/jenny/test/dialogue_runner_test.dart @@ -358,20 +358,16 @@ void main() { }); } -class _SimpleDialogueView extends DialogueView {} +class _SimpleDialogueView() extends DialogueView; -class _RecordingDialogueView extends DialogueView { - _RecordingDialogueView({ - List? target, - String? name, - List? choices, - }) : events = target ?? [], - name = name ?? '*', - choices = choices ?? []; - - final List events; - final String name; - final List choices; +class _RecordingDialogueView({ + List? target, + String? name, + List? choices, +}) extends DialogueView { + final List events = target ?? []; + final String name = name ?? '*'; + final List choices = choices ?? []; @override void onDialogueStart() => _record('onDialogueStart()'); @@ -406,19 +402,13 @@ class _RecordingDialogueView extends DialogueView { } } -class _DelayedDialogueView extends _RecordingDialogueView { - _DelayedDialogueView({ - super.target, - super.name, - this.dialogueStartDelay = 0, - this.lineStartDelay = 0, - this.lineFinishDelay = 0, - }); - - final double dialogueStartDelay; - final double lineStartDelay; - final double lineFinishDelay; - +class _DelayedDialogueView({ + super.target, + super.name, + final double dialogueStartDelay = 0, + final double lineStartDelay = 0, + final double lineFinishDelay = 0, +}) extends _RecordingDialogueView { @override FutureOr onDialogueStart() { super.onDialogueStart(); @@ -443,7 +433,7 @@ class _DelayedDialogueView extends _RecordingDialogueView { } } -class _ImmediateChoiceDialogueView extends DialogueView { +class _ImmediateChoiceDialogueView() extends DialogueView { bool finished = false; @override diff --git a/packages/flame_jenny/jenny/test/dialogue_view_test.dart b/packages/flame_jenny/jenny/test/dialogue_view_test.dart index 8e03d064b53..70dee4ba850 100644 --- a/packages/flame_jenny/jenny/test/dialogue_view_test.dart +++ b/packages/flame_jenny/jenny/test/dialogue_view_test.dart @@ -207,13 +207,11 @@ void main() { }); } -class _DefaultDialogueView extends DialogueView {} +class _DefaultDialogueView() extends DialogueView; -class _RecordingDialogueView extends DialogueView { - _RecordingDialogueView([this.waitDuration = Duration.zero]); +class _RecordingDialogueView([final Duration waitDuration = Duration.zero]) + extends DialogueView { final List events = []; - final Duration waitDuration; - @override FutureOr onDialogueStart() { events.add('onDialogueStart'); @@ -285,11 +283,11 @@ class _RecordingDialogueView extends DialogueView { } } -class _SomeOtherBaseClass {} +class _SomeOtherBaseClass(); -class _RecordingDialogueViewAsMixin extends _SomeOtherBaseClass +class _RecordingDialogueViewAsMixin() + extends _SomeOtherBaseClass with DialogueView { - _RecordingDialogueViewAsMixin(); final List events = []; @override @@ -360,7 +358,7 @@ class _RecordingDialogueViewAsMixin extends _SomeOtherBaseClass } } -class _InterruptingCow extends DialogueView { +class _InterruptingCow() extends DialogueView { @override FutureOr onLineStart(DialogueLine line) async { dialogueRunner!.sendSignal("I'm a banana!"); diff --git a/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart b/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart index 1a2ee6225b0..feffdd5d843 100644 --- a/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart +++ b/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart @@ -218,7 +218,7 @@ void main() { }); } -class _CommandDialogueView extends DialogueView { +class _CommandDialogueView() extends DialogueView { int numCalled = 0; String argumentString = ''; List arguments = []; diff --git a/packages/flame_jenny/jenny/test/test_scenario.dart b/packages/flame_jenny/jenny/test/test_scenario.dart index cc0a012af0b..cdbd98374e2 100644 --- a/packages/flame_jenny/jenny/test/test_scenario.dart +++ b/packages/flame_jenny/jenny/test/test_scenario.dart @@ -39,7 +39,7 @@ Future testScenario({ } if (testName == null) { - return testBody(); + return await testBody(); } else { test(testName, testBody, skip: skip); } @@ -76,8 +76,8 @@ int _calculateIndent(String line) { return line.length; } -class _TestPlan extends DialogueView { - _TestPlan(String input) { +class _TestPlan(String input) extends DialogueView { + this { _parse(input); } @@ -234,38 +234,26 @@ class _TestPlan extends DialogueView { } } -class _Line { - const _Line(this.character, this.text); - final String? character; - final String text; - +class const _Line(final String? character, final String text) { @override String toString() => 'Line($character: $text)'; } -class _Choice { - const _Choice(this.options, this.selectionIndex); - final List<_Option> options; - final int selectionIndex; - +class const _Choice(final List<_Option> options, final int selectionIndex) { @override String toString() => 'Choice($options)'; } -class _Option { - const _Option(this.character, this.text, {required this.enabled}); - final String? character; - final String text; - final bool enabled; - +class const _Option( + final String? character, + final String text, { + required final bool enabled, +}) { @override String toString() => 'Option($character: $text [$enabled])'; } -class _Command { - const _Command(this.name, this.content); - final String name; - final String content; +class const _Command(final String name, final String content) { @override String toString() => 'Command($name, "$content")'; } diff --git a/packages/flame_jenny/jenny/test/variable_storage_test.dart b/packages/flame_jenny/jenny/test/variable_storage_test.dart index c704991cbe2..8789d2911e2 100644 --- a/packages/flame_jenny/jenny/test/variable_storage_test.dart +++ b/packages/flame_jenny/jenny/test/variable_storage_test.dart @@ -101,8 +101,8 @@ void main() { }); } -class _BadVariableStorage extends VariableStorage { - _BadVariableStorage() { +class _BadVariableStorage() extends VariableStorage { + this { variables['x'] = null; } } diff --git a/packages/flame_jenny/pubspec.yaml b/packages/flame_jenny/pubspec.yaml index e15d137059a..841dff1623a 100644 --- a/packages/flame_jenny/pubspec.yaml +++ b/packages/flame_jenny/pubspec.yaml @@ -12,8 +12,8 @@ topics: - flame environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.17.1 diff --git a/packages/flame_kenney_xml/example/lib/main.dart b/packages/flame_kenney_xml/example/lib/main.dart index 15ddb35e1e5..8745f3ef95f 100644 --- a/packages/flame_kenney_xml/example/lib/main.dart +++ b/packages/flame_kenney_xml/example/lib/main.dart @@ -17,7 +17,7 @@ void main() { ); } -class KenneyWorld extends World with TapCallbacks { +class KenneyWorld() extends World with TapCallbacks { late final XmlSpriteSheet spritesheet; @override diff --git a/packages/flame_kenney_xml/example/pubspec.yaml b/packages/flame_kenney_xml/example/pubspec.yaml index 7d68e9d0846..c299245f099 100644 --- a/packages/flame_kenney_xml/example/pubspec.yaml +++ b/packages/flame_kenney_xml/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: "none" version: 1.0.0 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_kenney_xml/lib/flame_kenney_xml.dart b/packages/flame_kenney_xml/lib/flame_kenney_xml.dart index c8713cbf65b..394d70929b9 100644 --- a/packages/flame_kenney_xml/lib/flame_kenney_xml.dart +++ b/packages/flame_kenney_xml/lib/flame_kenney_xml.dart @@ -10,11 +10,11 @@ import 'package:xml/xpath.dart'; /// The XML file must be in the format of a ShoeBox XML file, formatted in the /// same way as the Kenney.nl sprite sheets. /// https://twitter.com/KenneyNL/status/1777429120936202344 -class XmlSpriteSheet { - XmlSpriteSheet({ - required this.image, - required String xml, - }) { +class XmlSpriteSheet({ + required final Image image, + required String xml, +}) { + this { final document = XmlDocument.parse(xml); // ignore: experimental_member_use for (final node in document.xpath('//TextureAtlas/SubTexture')) { @@ -50,7 +50,6 @@ class XmlSpriteSheet { return XmlSpriteSheet(image: image, xml: xml); } - final Image image; final _spriteBoundaries = {}; late final List spriteNames = _spriteBoundaries.keys.toList(); diff --git a/packages/flame_kenney_xml/pubspec.yaml b/packages/flame_kenney_xml/pubspec.yaml index 9122c1808cb..fb1c85e43be 100644 --- a/packages/flame_kenney_xml/pubspec.yaml +++ b/packages/flame_kenney_xml/pubspec.yaml @@ -14,8 +14,8 @@ topics: - tilemap environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_kenney_xml/test/flame_kenney_xml_test.dart b/packages/flame_kenney_xml/test/flame_kenney_xml_test.dart index eba5e4b0a5b..6fd8ee59385 100644 --- a/packages/flame_kenney_xml/test/flame_kenney_xml_test.dart +++ b/packages/flame_kenney_xml/test/flame_kenney_xml_test.dart @@ -5,7 +5,7 @@ import 'package:flame_kenney_xml/flame_kenney_xml.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; -class _MockImage extends Mock implements Image { +class _MockImage() extends Mock implements Image { @override int get width => 100; @@ -13,14 +13,14 @@ class _MockImage extends Mock implements Image { int get height => 100; } -class _MockImages extends Mock implements Images { +class _MockImages() extends Mock implements Images { @override Future load(String fileName, {String? key, String? package}) async { return _MockImage(); } } -class _MockAssetsCache extends Mock implements AssetsCache { +class _MockAssetsCache() extends Mock implements AssetsCache { @override Future readFile(String fileName, {String? package}) async { return ''' diff --git a/packages/flame_lint/lib/analysis_options.yaml b/packages/flame_lint/lib/analysis_options.yaml index f140ca12260..d4ba323b9ef 100644 --- a/packages/flame_lint/lib/analysis_options.yaml +++ b/packages/flame_lint/lib/analysis_options.yaml @@ -10,7 +10,6 @@ analyzer: exclude: - "**/*.g.dart" language: - strict-casts: true strict-raw-types: false linter: @@ -20,21 +19,20 @@ linter: - always_put_required_named_parameters_first - always_use_package_imports - annotate_overrides + - async_return_with_no_await - avoid_bool_literals_in_conditional_expressions - - avoid_double_and_int_checks - avoid_catches_without_on_clauses + - avoid_double_and_int_checks - avoid_dynamic_calls - avoid_empty_else - avoid_equals_and_hash_code_on_mutable_classes - avoid_escaping_inner_quotes - - avoid_field_initializers_in_const_classes - avoid_final_parameters - avoid_init_to_null - avoid_js_rounded_ints - avoid_multiple_declarations_per_line - avoid_positional_boolean_parameters - avoid_print - - avoid_private_typedef_functions - avoid_redundant_argument_values - avoid_relative_lib_imports - avoid_return_types_on_setters @@ -55,6 +53,7 @@ linter: - cast_nullable_to_non_nullable - close_sinks - collection_methods_unrelated_type + - combinators_ordering - comment_references - constant_identifier_names - control_flow_in_finally @@ -62,28 +61,36 @@ linter: - dangling_library_doc_comments - depend_on_referenced_packages - deprecated_consistency + - deprecated_member_use_from_same_package - directives_ordering - do_not_use_environment - empty_catches - empty_constructor_bodies + - empty_container_bodies - empty_statements - exhaustive_cases - file_names - flutter_style_todos - hash_and_equals - implementation_imports + - initialize_in_field_declaration + - invalid_runtime_check_with_js_interop_types - join_return_with_assignment - library_names - library_prefixes - library_private_types_in_public_api - lines_longer_than_80_chars - literal_only_boolean_expressions + - missing_code_block_language_in_doc_comment - missing_whitespace_between_adjacent_strings - no_adjacent_strings_in_list - no_duplicate_case_values + - no_dynamic_casts - no_leading_underscores_for_library_prefixes - no_leading_underscores_for_local_identifiers - - no_runtimeType_toString + - no_literal_bool_comparisons + - no_runtimetype_tostring + - no_self_assignments - non_constant_identifier_names - noop_primitive_operations - null_closures @@ -104,7 +111,7 @@ linter: - prefer_final_fields - prefer_final_in_for_each - prefer_final_locals - - prefer_for_elements_to_map_fromIterable + - prefer_for_elements_to_map_fromiterable - prefer_function_declarations_over_variables - prefer_generic_function_type_aliases - prefer_if_elements_to_conditional_expressions @@ -115,7 +122,7 @@ linter: - prefer_is_empty - prefer_is_not_empty - prefer_is_not_operator - - prefer_iterable_whereType + - prefer_iterable_wheretype - prefer_null_aware_method_calls - prefer_null_aware_operators - prefer_single_quotes @@ -125,6 +132,8 @@ linter: - provide_deprecation_message - recursive_getters - require_trailing_commas + - simple_directive_paths + - simplify_variable_pattern - slash_for_doc_comments - sort_child_properties_last - sort_pub_dependencies @@ -134,39 +143,48 @@ linter: - tighten_type_of_initializing_formals - type_annotate_public_apis - type_init_formals - - unnecessary_await_in_return - unnecessary_brace_in_string_interps - unnecessary_breaks - unnecessary_const + - unnecessary_const_in_enum_constructor - unnecessary_constructor_name - unnecessary_getters_setters + - unnecessary_ignore - unnecessary_lambdas - unnecessary_late + - unnecessary_library_directive + - unnecessary_library_name - unnecessary_new - unnecessary_null_aware_assignments + - unnecessary_null_aware_operator_on_extension_on_nullable - unnecessary_null_checks - unnecessary_null_in_if_null_operators - unnecessary_nullable_for_final_variable_declarations - unnecessary_overrides - unnecessary_parenthesis + - unnecessary_primary_constructor_body - unnecessary_raw_strings - unnecessary_statements - unnecessary_string_escapes - unnecessary_string_interpolations - unnecessary_this - unnecessary_to_list_in_spreads + - unnecessary_unawaited + - unnecessary_underscores - unrelated_type_equality_checks - use_enums - use_full_hex_values_for_flutter_colors - use_function_type_syntax_for_parameters - use_is_even_rather_than_modulo - use_key_in_widget_constructors - - use_late_for_private_fields_and_variables - use_named_constants + - use_null_aware_elements + - use_primary_constructors - use_raw_strings - use_rethrow_when_possible - use_setters_to_change_properties - use_super_parameters - use_test_throws_matchers + - use_truncating_division - valid_regexps - void_checks diff --git a/packages/flame_lint/lib/flame_lint.dart b/packages/flame_lint/lib/flame_lint.dart index 4b520e64424..7c89137bc16 100644 --- a/packages/flame_lint/lib/flame_lint.dart +++ b/packages/flame_lint/lib/flame_lint.dart @@ -11,4 +11,4 @@ /// ```yaml /// include: package:flame_lint/analysis_options.yaml /// ``` -library flame_lint; +library; diff --git a/packages/flame_lint/pubspec.yaml b/packages/flame_lint/pubspec.yaml index a71a0c5b50b..0f90dce07f2 100644 --- a/packages/flame_lint/pubspec.yaml +++ b/packages/flame_lint/pubspec.yaml @@ -12,10 +12,10 @@ topics: - lints environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: - lints: ^6.0.0 + lints: ^6.1.0 dev_dependencies: dartdoc: ^9.0.0 diff --git a/packages/flame_lottie/example/lib/main.dart b/packages/flame_lottie/example/lib/main.dart index 3216eb47406..88fa5a95b30 100644 --- a/packages/flame_lottie/example/lib/main.dart +++ b/packages/flame_lottie/example/lib/main.dart @@ -6,7 +6,7 @@ void main() { runApp(GameWidget(game: LottieExampleGame())); } -class LottieExampleGame extends FlameGame { +class LottieExampleGame() extends FlameGame { @override Future onLoad() async { final asset = await loadLottie(Lottie.asset('assets/LottieLogo1.json')); diff --git a/packages/flame_lottie/example/pubspec.yaml b/packages/flame_lottie/example/pubspec.yaml index 76e333db087..876eb80f611 100644 --- a/packages/flame_lottie/example/pubspec.yaml +++ b/packages/flame_lottie/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 0.0.1+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_lottie/lib/flame_lottie.dart b/packages/flame_lottie/lib/flame_lottie.dart index 9f7b9d7bf73..f5edabb4464 100644 --- a/packages/flame_lottie/lib/flame_lottie.dart +++ b/packages/flame_lottie/lib/flame_lottie.dart @@ -1,5 +1,4 @@ -library flame_lottie; - export 'package:lottie/lottie.dart'; + export 'src/lottie_component.dart'; export 'src/lottie_renderer.dart'; diff --git a/packages/flame_lottie/lib/src/lottie_component.dart b/packages/flame_lottie/lib/src/lottie_component.dart index ecfe686abce..b7d97ef23d5 100644 --- a/packages/flame_lottie/lib/src/lottie_component.dart +++ b/packages/flame_lottie/lib/src/lottie_component.dart @@ -8,31 +8,31 @@ import 'package:lottie/lottie.dart'; /// A Flame [Component] which renders a [Lottie] animation using the already /// existing Flutter library [lottie](https://pub.dev/packages/lottie). -class LottieComponent extends PositionComponent with HasPaint { +class LottieComponent( + LottieComposition composition, { + EffectController? controller, + double? progress, + LottieDelegates? delegates, + bool? enableMergePaths, + FrameRate? frameRate, + double? duration, + bool? repeating, + Alignment alignment = Alignment.center, + BoxFit? fit = BoxFit.contain, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent with HasPaint { late final LottieRenderer _renderer; /// The [controller] drives the [Lottie] animation. In case none is specified /// it will be created implicitly in the [LottieRenderer]. - LottieComponent( - LottieComposition composition, { - EffectController? controller, - double? progress, - LottieDelegates? delegates, - bool? enableMergePaths, - FrameRate? frameRate, - double? duration, - bool? repeating, - Alignment alignment = Alignment.center, - BoxFit? fit = BoxFit.contain, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - super.key, - }) { + this { _renderer = LottieRenderer( composition: composition, progress: progress ?? 0.0, diff --git a/packages/flame_lottie/lib/src/lottie_renderer.dart b/packages/flame_lottie/lib/src/lottie_renderer.dart index e042bef4916..65a86a1caff 100644 --- a/packages/flame_lottie/lib/src/lottie_renderer.dart +++ b/packages/flame_lottie/lib/src/lottie_renderer.dart @@ -3,39 +3,34 @@ import 'package:flame/game.dart'; import 'package:flutter/rendering.dart'; import 'package:lottie/lottie.dart'; -class LottieRenderer { - final LottieDrawable drawable; - final EffectController _controller; +class LottieRenderer({ + required LottieComposition composition, + required double progress, + required NotifyingVector2 size, + EffectController? controller, + double? duration, + bool? repeating, + final Alignment? alignment, + final BoxFit? fit, + LottieDelegates? delegates, + bool? enableMergePaths, + FrameRate? frameRate, +}) { + final LottieDrawable drawable = + LottieDrawable(composition, frameRate: frameRate) + ..setProgress(progress) + ..delegates = delegates + ..enableMergePaths = enableMergePaths ?? false; + final EffectController _controller = + controller ?? + EffectController( + duration: duration ?? composition.duration.inMilliseconds / 1000, + infinite: repeating ?? false, + ); - final BoxFit? fit; - final Alignment? alignment; + Rect boundingRect = size.toRect(); - Rect boundingRect; - - LottieRenderer({ - required LottieComposition composition, - required double progress, - required NotifyingVector2 size, - EffectController? controller, - double? duration, - bool? repeating, - this.alignment, - this.fit, - LottieDelegates? delegates, - bool? enableMergePaths, - FrameRate? frameRate, - }) : assert(progress >= 0.0 && progress <= 1.0), - boundingRect = size.toRect(), - drawable = LottieDrawable(composition, frameRate: frameRate) - ..setProgress(progress) - ..delegates = delegates - ..enableMergePaths = enableMergePaths ?? false, - _controller = - controller ?? - EffectController( - duration: duration ?? composition.duration.inMilliseconds / 1000, - infinite: repeating ?? false, - ) { + this : assert(progress >= 0.0 && progress <= 1.0) { size.addListener(() { boundingRect = size.toRect(); }); diff --git a/packages/flame_lottie/pubspec.yaml b/packages/flame_lottie/pubspec.yaml index 941c9e71ace..6d97eda1ece 100644 --- a/packages/flame_lottie/pubspec.yaml +++ b/packages/flame_lottie/pubspec.yaml @@ -13,8 +13,8 @@ topics: - animations environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_lottie/test/flame_lottie_test.dart b/packages/flame_lottie/test/flame_lottie_test.dart index b6c2f73e6ff..e4b3584ad2e 100644 --- a/packages/flame_lottie/test/flame_lottie_test.dart +++ b/packages/flame_lottie/test/flame_lottie_test.dart @@ -53,11 +53,9 @@ void main() { ByteData _bytesForFile(String path) => File(path).readAsBytesSync().buffer.asByteData(); -class _FakeAssetBundle extends Fake implements AssetBundle { - final Map> data; - - _FakeAssetBundle(this.data); - +class _FakeAssetBundle(final Map> data) + extends Fake + implements AssetBundle { @override Future load(String key) { return data[key] ?? (Future.error('Asset $key not found')); diff --git a/packages/flame_markdown/example/lib/main.dart b/packages/flame_markdown/example/lib/main.dart index cf4ca158351..fc3d4727e2b 100644 --- a/packages/flame_markdown/example/lib/main.dart +++ b/packages/flame_markdown/example/lib/main.dart @@ -15,7 +15,7 @@ void main() { /// This example game showcases the use of the FlameMarkdown package /// to render rich-text components using a simple markdown syntax. -class MarkdownGame extends FlameGame { +class MarkdownGame() extends FlameGame { @override Future onLoad() async { final markdown = await Flame.assets.readFile('assets/fire_and_ice.md'); diff --git a/packages/flame_markdown/example/pubspec.yaml b/packages/flame_markdown/example/pubspec.yaml index d7efe738edd..b4f25659476 100644 --- a/packages/flame_markdown/example/pubspec.yaml +++ b/packages/flame_markdown/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_markdown/lib/custom_attribute_syntax.dart b/packages/flame_markdown/lib/custom_attribute_syntax.dart index df1cd3b333e..acbc555f1b5 100644 --- a/packages/flame_markdown/lib/custom_attribute_syntax.dart +++ b/packages/flame_markdown/lib/custom_attribute_syntax.dart @@ -2,7 +2,7 @@ import 'package:markdown/markdown.dart'; // cSpell:ignore charcode.dart (file name from another package) // NOTE: values obtained from file `charcode.dart` from the markdown package -class _Chars { +class _Chars() { /// Character `[`. static const int leftBracket = 0x5B; @@ -25,9 +25,9 @@ class _Chars { /// /// This is based on the standard Link markdown parser (which matches the /// `[text](url)` and `[text][ref]` syntaxes). -class CustomAttributeSyntax extends LinkSyntax { +class CustomAttributeSyntax() extends LinkSyntax { /// Creates a new custom attribute syntax. - CustomAttributeSyntax() + this : super( pattern: r'\[', startCharacter: _Chars.leftBracket, diff --git a/packages/flame_markdown/lib/flame_markdown.dart b/packages/flame_markdown/lib/flame_markdown.dart index 798edda9e6f..7b27af40eff 100644 --- a/packages/flame_markdown/lib/flame_markdown.dart +++ b/packages/flame_markdown/lib/flame_markdown.dart @@ -12,7 +12,10 @@ import 'package:markdown/markdown.dart'; /// code blocks, images, and inline HTML. /// It is also possible that some otherwise valid markdown nestings of /// block and inline-type elements are not currently supported. -class FlameMarkdown { +class FlameMarkdown() { + /// Creates a [FlameMarkdown] instance. + this; + /// Converts a markdown string to a [DocumentRoot] from Flame. /// /// This uses the `markdown` package to parse the markdown string @@ -64,21 +67,20 @@ class FlameMarkdown { } return switch (element.tag) { - 'span' => child, - 'h1' => HeaderNode(child, level: 1), - 'h2' => HeaderNode(child, level: 2), - 'h3' => HeaderNode(child, level: 3), - 'h4' => HeaderNode(child, level: 4), - 'h5' => HeaderNode(child, level: 5), - 'h6' => HeaderNode(child, level: 6), - 'p' => ParagraphNode(child), - 'em' || 'i' => ItalicTextNode(child), - 'strong' || 'b' => BoldTextNode(child), - 'code' => CodeTextNode(child), - 'del' => StrikethroughTextNode(child), - _ => throw Exception('Unknown element tag: ${element.tag}'), - } - as TextNode; + 'span' => child, + 'h1' => HeaderNode(child, level: 1), + 'h2' => HeaderNode(child, level: 2), + 'h3' => HeaderNode(child, level: 3), + 'h4' => HeaderNode(child, level: 4), + 'h5' => HeaderNode(child, level: 5), + 'h6' => HeaderNode(child, level: 6), + 'p' => ParagraphNode(child), + 'em' || 'i' => ItalicTextNode(child), + 'strong' || 'b' => BoldTextNode(child), + 'code' => CodeTextNode(child), + 'del' => StrikethroughTextNode(child), + _ => throw Exception('Unknown element tag: ${element.tag}'), + } as TextNode; } static PlainTextNode _convertText(Text text) { diff --git a/packages/flame_markdown/pubspec.yaml b/packages/flame_markdown/pubspec.yaml index 533a81ce330..3322f22e484 100644 --- a/packages/flame_markdown/pubspec.yaml +++ b/packages/flame_markdown/pubspec.yaml @@ -13,8 +13,8 @@ topics: - markdown environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_network_assets/example/lib/main.dart b/packages/flame_network_assets/example/lib/main.dart index e35bf3b81b4..5aacf684feb 100644 --- a/packages/flame_network_assets/example/lib/main.dart +++ b/packages/flame_network_assets/example/lib/main.dart @@ -11,7 +11,7 @@ void main() { runApp(const GameWidget.managed(gameFactory: MyGame.new)); } -class MyGame extends FlameGame with TapCallbacks { +class MyGame() extends FlameGame with TapCallbacks { final networkImages = FlameNetworkImages(); late Image playerSprite; diff --git a/packages/flame_network_assets/example/pubspec.yaml b/packages/flame_network_assets/example/pubspec.yaml index 2fd1ed04874..b4fc5927e81 100644 --- a/packages/flame_network_assets/example/pubspec.yaml +++ b/packages/flame_network_assets/example/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_network_assets/lib/flame_network_assets.dart b/packages/flame_network_assets/lib/flame_network_assets.dart index 97162792f00..45c76a0cb6f 100644 --- a/packages/flame_network_assets/lib/flame_network_assets.dart +++ b/packages/flame_network_assets/lib/flame_network_assets.dart @@ -1,5 +1,3 @@ -library flame_network_assets; - export 'src/flame_asset_response.dart'; export 'src/flame_network_assets.dart'; export 'src/flame_network_images.dart'; diff --git a/packages/flame_network_assets/lib/src/flame_asset_response.dart b/packages/flame_network_assets/lib/src/flame_asset_response.dart index 319b7e8cf57..b9d82331c40 100644 --- a/packages/flame_network_assets/lib/src/flame_asset_response.dart +++ b/packages/flame_network_assets/lib/src/flame_asset_response.dart @@ -4,16 +4,13 @@ import 'dart:typed_data'; /// A class containing the relevant http attributes to /// Flame Assets Network package. /// {@endtemplate} -class FlameAssetResponse { - /// {@macro flame_assets_response} - const FlameAssetResponse({ - required this.statusCode, - required this.bytes, - }); - +class const FlameAssetResponse({ /// Http status code. - final int statusCode; + required final int statusCode, /// response bytes. - final Uint8List bytes; + required final Uint8List bytes, +}) { + /// {@macro flame_assets_response} + this; } diff --git a/packages/flame_network_assets/lib/src/flame_network_assets.dart b/packages/flame_network_assets/lib/src/flame_network_assets.dart index a387de6b2ad..8c7514e9c79 100644 --- a/packages/flame_network_assets/lib/src/flame_network_assets.dart +++ b/packages/flame_network_assets/lib/src/flame_network_assets.dart @@ -10,11 +10,10 @@ import 'package:path/path.dart' as path; import 'package:path_provider/path_provider.dart'; /// Function signature used by Flame Network Assets to fetch assets. -typedef GetAssetFunction = - Future Function( - String url, { - Map? headers, - }); +typedef GetAssetFunction = Future Function( + String url, { + Map? headers, +}); /// Function signature used by Flame Network Assets to decode assets from a /// raw format. @@ -67,7 +66,18 @@ typedef GetAppDirectoryFunction = Future Function(); /// argument on the constructor. /// /// {@endtemplate} -abstract class FlameNetworkAssets { +abstract class FlameNetworkAssets({ + required DecodeAssetFunction decodeAsset, + EncodeAssetFunction? encodeAsset, + GetAssetFunction? get, + GetAppDirectoryFunction? getAppDirectory, + + /// Flag indicating if files will be cached in memory. + final bool cacheInMemory = true, + + /// Flag indicating if files will be cached in the local storage. + final bool cacheInStorage = true, +}) { /// {@macro flame_network_assets} /// /// - [decodeAsset] a [DecodeAssetFunction] responsible for decoding the asset @@ -83,16 +93,7 @@ abstract class FlameNetworkAssets { /// (true by default). /// - [cacheInStorage] will not cache assets in the file system when false, /// (true by default). - FlameNetworkAssets({ - required DecodeAssetFunction decodeAsset, - EncodeAssetFunction? encodeAsset, - GetAssetFunction? get, - GetAppDirectoryFunction? getAppDirectory, - this.cacheInMemory = true, - this.cacheInStorage = true, - }) : _isWeb = kIsWeb, - _decode = decodeAsset, - _encode = encodeAsset { + this : _isWeb = kIsWeb { _get = get ?? ( @@ -110,14 +111,8 @@ abstract class FlameNetworkAssets { late final GetAssetFunction _get; late final GetAppDirectoryFunction _getAppDirectory; - final DecodeAssetFunction _decode; - final EncodeAssetFunction? _encode; - - /// Flag indicating if files will be cached in memory. - final bool cacheInMemory; - - /// Flag indicating if files will be cached in the local storage. - final bool cacheInStorage; + final DecodeAssetFunction _decode = decodeAsset; + final EncodeAssetFunction? _encode = encodeAsset; final bool _isWeb; diff --git a/packages/flame_network_assets/lib/src/flame_network_images.dart b/packages/flame_network_assets/lib/src/flame_network_images.dart index c3a5a913d16..c78c63a6db0 100644 --- a/packages/flame_network_assets/lib/src/flame_network_images.dart +++ b/packages/flame_network_assets/lib/src/flame_network_images.dart @@ -9,12 +9,12 @@ import 'package:flutter/rendering.dart'; /// {@macro flame_network_assets} /// /// {@endtemplate} -class FlameNetworkImages extends FlameNetworkAssets { +class FlameNetworkImages({ + super.get, + super.getAppDirectory, + super.cacheInMemory, + super.cacheInStorage, +}) extends FlameNetworkAssets { /// {@macro flame_network_images} - FlameNetworkImages({ - super.get, - super.getAppDirectory, - super.cacheInMemory, - super.cacheInStorage, - }) : super(decodeAsset: decodeImageFromList); + this : super(decodeAsset: decodeImageFromList); } diff --git a/packages/flame_network_assets/pubspec.yaml b/packages/flame_network_assets/pubspec.yaml index 286527ec80c..81a6a039aa8 100644 --- a/packages/flame_network_assets/pubspec.yaml +++ b/packages/flame_network_assets/pubspec.yaml @@ -13,8 +13,8 @@ topics: - network-assets environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: dev: ^1.0.0 diff --git a/packages/flame_network_assets/test/flame_network_image_test.dart b/packages/flame_network_assets/test/flame_network_image_test.dart index 7fee2bda976..221b2ec798b 100644 --- a/packages/flame_network_assets/test/flame_network_image_test.dart +++ b/packages/flame_network_assets/test/flame_network_image_test.dart @@ -7,20 +7,20 @@ import 'package:material_ui/material_ui.dart' hide Image; import 'package:mocktail/mocktail.dart'; import 'package:path/path.dart' as path; -abstract class __MockHttpClient { +abstract class __MockHttpClient() { Future get( String url, { Map? headers, }); } -class _MockHttpClient extends Mock implements __MockHttpClient {} +class _MockHttpClient() extends Mock implements __MockHttpClient; -abstract class __MockPathProvider { +abstract class __MockPathProvider() { Future getAppDirectory(); } -class _MockPathProvider extends Mock implements __MockPathProvider {} +class _MockPathProvider() extends Mock implements __MockPathProvider; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame_noise/lib/src/effects/noise_effect_controller.dart b/packages/flame_noise/lib/src/effects/noise_effect_controller.dart index 1015c466a9d..c42c3e6ce19 100644 --- a/packages/flame_noise/lib/src/effects/noise_effect_controller.dart +++ b/packages/flame_noise/lib/src/effects/noise_effect_controller.dart @@ -14,20 +14,18 @@ import 'package:flutter/animation.dart' show Curve, Curves; /// example, putting into a `MoveEffect.by` will create a shake motion, where /// the magnitude and the direction of shaking is controlled by the effect's /// `offset`. -class NoiseEffectController extends DurationEffectController { +class NoiseEffectController({ + required double duration, + final Curve taperingCurve = Curves.easeInOutCubic, + Noise2? noise, +}) extends DurationEffectController { /// Square root of 2 is used as the y-offset for noise sampling to avoid /// landing on integer lattice points where Perlin noise returns 0. static const _noiseYOffset = sqrt2; - final Curve taperingCurve; - final Noise2 noise; + final Noise2 noise = noise ?? PerlinNoise(); - NoiseEffectController({ - required double duration, - this.taperingCurve = Curves.easeInOutCubic, - Noise2? noise, - }) : noise = noise ?? PerlinNoise(), - super(duration); + this : super(duration); @override double get progress { diff --git a/packages/flame_noise/pubspec.yaml b/packages/flame_noise/pubspec.yaml index 39e272a3cf7..07275456953 100644 --- a/packages/flame_noise/pubspec.yaml +++ b/packages/flame_noise/pubspec.yaml @@ -12,8 +12,8 @@ topics: - noise environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: fast_noise: ^2.0.0 diff --git a/packages/flame_rive/example/lib/main.dart b/packages/flame_rive/example/lib/main.dart index 4f0e3d2015f..2e1f7a4d80f 100644 --- a/packages/flame_rive/example/lib/main.dart +++ b/packages/flame_rive/example/lib/main.dart @@ -11,7 +11,7 @@ void main() async { runApp(const GameWidget.managed(gameFactory: RiveExampleGame.new)); } -class RiveExampleGame extends FlameGame { +class RiveExampleGame() extends FlameGame { @override Color backgroundColor() => const Color(0xFF444444); @@ -39,8 +39,9 @@ class RiveExampleGame extends FlameGame { } } -class RewardsComponent extends RiveComponent { - RewardsComponent(Artboard artboard, StateMachine? stateMachine) +class RewardsComponent(Artboard artboard, StateMachine? stateMachine) + extends RiveComponent { + this : super( artboard: artboard, stateMachine: stateMachine, @@ -118,13 +119,9 @@ class RewardsComponent extends RiveComponent { } } -class RewardsArea extends PositionComponent with TapCallbacks, GestureHitboxes { - RewardsArea({ - required this.onTap, - }); - - final VoidCallback onTap; - +class RewardsArea({ + required final VoidCallback onTap, +}) extends PositionComponent with TapCallbacks, GestureHitboxes { @override Future onLoad() async { await super.onLoad(); diff --git a/packages/flame_rive/example/pubspec.yaml b/packages/flame_rive/example/pubspec.yaml index 886ac9315e6..6399697be97 100644 --- a/packages/flame_rive/example/pubspec.yaml +++ b/packages/flame_rive/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_rive/lib/src/rive_component.dart b/packages/flame_rive/lib/src/rive_component.dart index 6426e8b6656..10a5f2dbd3f 100644 --- a/packages/flame_rive/lib/src/rive_component.dart +++ b/packages/flame_rive/lib/src/rive_component.dart @@ -4,39 +4,35 @@ import 'package:flame/components.dart'; import 'package:flutter/rendering.dart'; import 'package:rive/rive.dart'; -class RiveComponent extends PositionComponent { - final Artboard artboard; - final StateMachine? stateMachine; - final Alignment _alignment; - final bool _clipToBounds; - final Fit _riveFit; - final Paint? _layerPaint; +class RiveComponent({ + required final Artboard artboard, + final StateMachine? stateMachine, + bool antialiasing = true, + BoxFit fit = BoxFit.contain, + final Alignment _alignment = Alignment.center, + final bool _clipToBounds = false, + super.position, + + /// The logical size of the component. + /// Default value is ArtboardSize + Vector2? size, + super.scale, + super.angle = 0.0, + super.anchor = Anchor.topLeft, + super.children, + super.priority, + super.key, +}) extends PositionComponent { + final Fit _riveFit = _toRiveFit(fit); + final Paint? _layerPaint = antialiasing + ? null + : (Paint()..isAntiAlias = false); late Size _renderSize; AABB _frame = AABB(); Size _frameSize = Size.zero; - RiveComponent({ - required this.artboard, - this.stateMachine, - bool antialiasing = true, - BoxFit fit = BoxFit.contain, - this._alignment = Alignment.center, - this._clipToBounds = false, - super.position, - - /// The logical size of the component. - /// Default value is ArtboardSize - Vector2? size, - super.scale, - super.angle = 0.0, - super.anchor = Anchor.topLeft, - super.children, - super.priority, - super.key, - }) : _riveFit = _toRiveFit(fit), - _layerPaint = antialiasing ? null : (Paint()..isAntiAlias = false), - super(size: size ?? Vector2(artboard.width, artboard.height)) { + this : super(size: size ?? Vector2(artboard.width, artboard.height)) { void updateRenderSize() { _renderSize = this.size.toSize(); } diff --git a/packages/flame_rive/pubspec.yaml b/packages/flame_rive/pubspec.yaml index 98260bf9741..68d0d338ef4 100644 --- a/packages/flame_rive/pubspec.yaml +++ b/packages/flame_rive/pubspec.yaml @@ -13,8 +13,8 @@ topics: - animations environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_rive/test/flame_rive_test.dart b/packages/flame_rive/test/flame_rive_test.dart index 720b50b5fbc..b1016853920 100644 --- a/packages/flame_rive/test/flame_rive_test.dart +++ b/packages/flame_rive/test/flame_rive_test.dart @@ -121,14 +121,11 @@ void main() { ); } -class _RiveComponent extends RiveComponent { - _RiveComponent({required super.artboard}); -} +class _RiveComponent({required super.artboard}) extends RiveComponent; -class _RiveComponentWithAnimation extends RiveComponent { - _RiveComponentWithAnimation({required super.artboard}); -} +class _RiveComponentWithAnimation({required super.artboard}) + extends RiveComponent; -class _RiveComponentWithTappable extends RiveComponent with TapCallbacks { - _RiveComponentWithTappable({required super.artboard}); -} +class _RiveComponentWithTappable({required super.artboard}) + extends RiveComponent + with TapCallbacks; diff --git a/packages/flame_riverpod/example/lib/main.dart b/packages/flame_riverpod/example/lib/main.dart index b3281bb6c3d..0d14b6ad54a 100644 --- a/packages/flame_riverpod/example/lib/main.dart +++ b/packages/flame_riverpod/example/lib/main.dart @@ -18,9 +18,7 @@ final gameInstance = RefExampleGame(); final GlobalKey gameWidgetKey = GlobalKey(); -class MyApp extends StatelessWidget { - const MyApp({super.key}); - +class const MyApp({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( @@ -41,9 +39,7 @@ class MyApp extends StatelessWidget { } } -class FlutterCountingComponent extends ConsumerWidget { - const FlutterCountingComponent({super.key}); - +class const FlutterCountingComponent({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final textStyle = Theme.of( @@ -67,7 +63,7 @@ class FlutterCountingComponent extends ConsumerWidget { } } -class RefExampleGame extends FlameGame with RiverpodGameMixin { +class RefExampleGame() extends FlameGame with RiverpodGameMixin { @override Future onLoad() async { await super.onLoad(); @@ -76,7 +72,8 @@ class RefExampleGame extends FlameGame with RiverpodGameMixin { } } -class RiverpodAwareTextComponent extends PositionComponent +class RiverpodAwareTextComponent() + extends PositionComponent with RiverpodComponentMixin { late TextComponent textComponent; int currentValue = 0; diff --git a/packages/flame_riverpod/example/pubspec.yaml b/packages/flame_riverpod/example/pubspec.yaml index 94c3e898a8b..727bc0e6fd8 100644 --- a/packages/flame_riverpod/example/pubspec.yaml +++ b/packages/flame_riverpod/example/pubspec.yaml @@ -4,7 +4,7 @@ description: Showcasing the flame_riverpod functionality. publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 flame_riverpod: ^5.5.6-dev.0 diff --git a/packages/flame_riverpod/example/test/widget_test.dart b/packages/flame_riverpod/example/test/widget_test.dart index 6ce15e9249d..98b55183d2e 100644 --- a/packages/flame_riverpod/example/test/widget_test.dart +++ b/packages/flame_riverpod/example/test/widget_test.dart @@ -35,9 +35,9 @@ void main() { final riverpodGameWidgetFinder = find.byType(RiverpodAwareGameWidget); expect(riverpodGameWidgetFinder, findsOneWidget); - final gameWidget = - widgetTester.widget(riverpodGameWidgetFinder) - as RiverpodAwareGameWidget; + final gameWidget = widgetTester.widget( + riverpodGameWidgetFinder, + ) as RiverpodAwareGameWidget; // GameWidget contains a FutureBuilder, which calls setState when a Future // completes. We therefore need to pump / re-render the widget to ensure diff --git a/packages/flame_riverpod/lib/flame_riverpod.dart b/packages/flame_riverpod/lib/flame_riverpod.dart index b29aa2b82e3..7265adf4b01 100644 --- a/packages/flame_riverpod/lib/flame_riverpod.dart +++ b/packages/flame_riverpod/lib/flame_riverpod.dart @@ -1,7 +1,7 @@ /// Helpers for using Riverpod in conjunction with Flame, to share state from /// the game into other parts of your application, or from other parts of your /// application into your game. -library flame_riverpod; +library; export 'src/consumer.dart'; export 'src/widget.dart'; diff --git a/packages/flame_riverpod/lib/src/consumer.dart b/packages/flame_riverpod/lib/src/consumer.dart index 4930446786f..6a1b1a4e190 100644 --- a/packages/flame_riverpod/lib/src/consumer.dart +++ b/packages/flame_riverpod/lib/src/consumer.dart @@ -7,11 +7,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/misc.dart'; -class ComponentRef { - ComponentRef({required this.game}); - - RiverpodGameMixin? game; - +class ComponentRef({required var RiverpodGameMixin? game}) { BuildContext get context => game!.buildContext!; RiverpodAwareGameWidgetState? get _container { @@ -86,7 +82,7 @@ mixin RiverpodComponentMixin on Component { ref.game = findGame()! as RiverpodGameMixin; ref.game!._onBuildCallbacks.addAll(_onBuildCallbacks); - if (rebuildOnMountWhen(ref) == true) { + if (rebuildOnMountWhen(ref)) { rebuildGameWidget(); } } @@ -102,7 +98,7 @@ mixin RiverpodComponentMixin on Component { _onBuildCallbacks.clear(); // Force build to flush dependencies - if (rebuildOnRemoveWhen(ref) == true) { + if (rebuildOnRemoveWhen(ref)) { rebuildGameWidget(); } @@ -113,7 +109,7 @@ mixin RiverpodComponentMixin on Component { } void rebuildGameWidget() { - assert(ref.game!.isMounted == true); + assert(ref.game!.isMounted); if (ref.game!.isMounted) { ref.game!.widgetKey!.currentState!.forceBuild(); } diff --git a/packages/flame_riverpod/lib/src/widget.dart b/packages/flame_riverpod/lib/src/widget.dart index c109975241c..e8c8e80fc91 100644 --- a/packages/flame_riverpod/lib/src/widget.dart +++ b/packages/flame_riverpod/lib/src/widget.dart @@ -3,7 +3,7 @@ import 'package:flame/game.dart'; import 'package:flame_riverpod/flame_riverpod.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -// ignore: depend_on_referenced_packages, implementation_imports +// ignore: implementation_imports import 'package:riverpod/src/framework.dart'; /// A [GameWidget] that provides access to [Component]s using @@ -13,30 +13,28 @@ import 'package:riverpod/src/framework.dart'; /// The corresponding [State] object ([RiverpodAwareGameWidgetState]) assumes /// responsibilities associated with ConsumerStatefulElement in /// `flutter_riverpod`. -class RiverpodAwareGameWidget extends GameWidget { - RiverpodAwareGameWidget({ - required super.game, - required this.key, - super.textDirection, - super.loadingBuilder, - super.errorBuilder, - super.backgroundBuilder, - super.overlayBuilderMap, - super.initialActiveOverlays, - super.focusNode, - super.autofocus, - super.mouseCursor, - super.addRepaintBoundary, - }) : super(key: key); - - @override - final GlobalKey> key; +class RiverpodAwareGameWidget({ + required super.game, + @override required final GlobalKey> key, + super.textDirection, + super.loadingBuilder, + super.errorBuilder, + super.backgroundBuilder, + super.overlayBuilderMap, + super.initialActiveOverlays, + super.focusNode, + super.autofocus, + super.mouseCursor, + super.addRepaintBoundary, +}) extends GameWidget { + this : super(key: key); @override GameWidgetState createState() => RiverpodAwareGameWidgetState(); } -class RiverpodAwareGameWidgetState extends GameWidgetState { +class RiverpodAwareGameWidgetState() + extends GameWidgetState { RiverpodGameMixin get game => widget.game! as RiverpodGameMixin; bool _isForceBuilding = false; @@ -159,7 +157,7 @@ class RiverpodAwareGameWidgetState extends GameWidgetState { // setState call has been replaced with forceBuild, // to prevent setState calls while the widget is // building, which throws a framework error. - (_, __) => forceBuild(), + (_, _) => forceBuild(), ); }).read() as Res; @@ -221,7 +219,7 @@ class RiverpodAwareGameWidgetState extends GameWidgetState { listener, onError: onError, fireImmediately: fireImmediately, - // ignore: invalid_use_of_internal_member, from riverpod + // ignore: from riverpod ); // Hook-up on onClose to avoid memory leaks. diff --git a/packages/flame_riverpod/pubspec.yaml b/packages/flame_riverpod/pubspec.yaml index 47605740a5b..85bebf75362 100644 --- a/packages/flame_riverpod/pubspec.yaml +++ b/packages/flame_riverpod/pubspec.yaml @@ -12,8 +12,8 @@ topics: - state-management environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_riverpod/test/widget_test.dart b/packages/flame_riverpod/test/widget_test.dart index 014653fe345..0c26cca06c7 100644 --- a/packages/flame_riverpod/test/widget_test.dart +++ b/packages/flame_riverpod/test/widget_test.dart @@ -9,9 +9,9 @@ final numberProvider = Provider.autoDispose((ref) { return 1; }); -class MyGame extends FlameGame with RiverpodGameMixin {} +class MyGame() extends FlameGame with RiverpodGameMixin; -class MyGameWithRefAccess extends FlameGame with RiverpodGameMixin { +class MyGameWithRefAccess() extends FlameGame with RiverpodGameMixin { @override void onMount() { addToGameWidgetBuild(() { @@ -21,7 +21,7 @@ class MyGameWithRefAccess extends FlameGame with RiverpodGameMixin { } } -class EmptyComponent extends Component with RiverpodComponentMixin { +class EmptyComponent() extends Component with RiverpodComponentMixin { @override void onLoad() { super.onLoad(); @@ -31,7 +31,7 @@ class EmptyComponent extends Component with RiverpodComponentMixin { } } -class WatchingComponent extends Component with RiverpodComponentMixin { +class WatchingComponent() extends Component with RiverpodComponentMixin { @override void onLoad() { super.onLoad(); diff --git a/packages/flame_spine/example/lib/main.dart b/packages/flame_spine/example/lib/main.dart index 59910343194..4332847bf10 100644 --- a/packages/flame_spine/example/lib/main.dart +++ b/packages/flame_spine/example/lib/main.dart @@ -10,7 +10,7 @@ void main() async { runApp(const GameWidget.managed(gameFactory: SpineExample.new)); } -class SpineExample extends FlameGame with TapCallbacks { +class SpineExample() extends FlameGame with TapCallbacks { late final SpineComponent spineboy; final states = [ diff --git a/packages/flame_spine/example/pubspec.yaml b/packages/flame_spine/example/pubspec.yaml index 780315f0810..e3108afb37e 100644 --- a/packages/flame_spine/example/pubspec.yaml +++ b/packages/flame_spine/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_spine/lib/flame_spine.dart b/packages/flame_spine/lib/flame_spine.dart index 0822ed8ef9a..02c5a02ce9e 100644 --- a/packages/flame_spine/lib/flame_spine.dart +++ b/packages/flame_spine/lib/flame_spine.dart @@ -1,2 +1,3 @@ export 'package:spine_flutter/spine_flutter.dart'; + export 'src/spine_component.dart'; diff --git a/packages/flame_spine/lib/src/spine_component.dart b/packages/flame_spine/lib/src/spine_component.dart index c14f1e354e8..781076cd387 100644 --- a/packages/flame_spine/lib/src/spine_component.dart +++ b/packages/flame_spine/lib/src/spine_component.dart @@ -4,24 +4,20 @@ import 'package:flame/components.dart'; import 'package:flutter/services.dart'; import 'package:spine_flutter/spine_flutter.dart'; -class SpineComponent extends PositionComponent { - final BoundsProvider _boundsProvider; - final SkeletonDrawableFlutter _drawable; +class SpineComponent( + final SkeletonDrawableFlutter _drawable, { + final bool _ownsDrawable = true, + final BoundsProvider _boundsProvider = const SetupPoseBounds(), + super.position, + super.scale, + double super.angle = 0.0, + Anchor super.anchor = Anchor.topLeft, + super.children, + super.priority, + super.key, +}) extends PositionComponent { late final Bounds _bounds; - final bool _ownsDrawable; - - SpineComponent( - this._drawable, { - this._ownsDrawable = true, - this._boundsProvider = const SetupPoseBounds(), - super.position, - super.scale, - double super.angle = 0.0, - Anchor super.anchor = Anchor.topLeft, - super.children, - super.priority, - super.key, - }) { + this { _drawable.update(0); _bounds = _boundsProvider.computeBounds(_drawable); size = Vector2(_bounds.width, _bounds.height); diff --git a/packages/flame_spine/pubspec.yaml b/packages/flame_spine/pubspec.yaml index 8cd7684433e..abf7ff35e9b 100644 --- a/packages/flame_spine/pubspec.yaml +++ b/packages/flame_spine/pubspec.yaml @@ -12,8 +12,8 @@ topics: - animations environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.17.1 diff --git a/packages/flame_splash_screen/example/lib/main.dart b/packages/flame_splash_screen/example/lib/main.dart index b22ecadb00c..037a5e1d5f0 100644 --- a/packages/flame_splash_screen/example/lib/main.dart +++ b/packages/flame_splash_screen/example/lib/main.dart @@ -5,9 +5,7 @@ void main() { runApp(const MyApp()); } -class MyApp extends StatelessWidget { - const MyApp({super.key}); - +class const MyApp({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( @@ -18,9 +16,7 @@ class MyApp extends StatelessWidget { } } -class OtherScreen extends StatelessWidget { - const OtherScreen({super.key}); - +class const OtherScreen({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( @@ -39,14 +35,12 @@ class OtherScreen extends StatelessWidget { } } -class SplashScreenGame extends StatefulWidget { - const SplashScreenGame({super.key}); - +class const SplashScreenGame({super.key}) extends StatefulWidget { @override SplashScreenGameState createState() => SplashScreenGameState(); } -class SplashScreenGameState extends State { +class SplashScreenGameState() extends State { @override Widget build(BuildContext context) { return Scaffold( diff --git a/packages/flame_splash_screen/example/pubspec.yaml b/packages/flame_splash_screen/example/pubspec.yaml index 0ceb90ce12b..7e4d88061ed 100644 --- a/packages/flame_splash_screen/example/pubspec.yaml +++ b/packages/flame_splash_screen/example/pubspec.yaml @@ -6,8 +6,8 @@ publish_to: none version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame_splash_screen: ^0.3.2-dev.0+4 diff --git a/packages/flame_splash_screen/lib/src/controller.dart b/packages/flame_splash_screen/lib/src/controller.dart index c5a61b9ca99..4a9441c137e 100644 --- a/packages/flame_splash_screen/lib/src/controller.dart +++ b/packages/flame_splash_screen/lib/src/controller.dart @@ -3,24 +3,22 @@ import 'package:meta/meta.dart'; /// Controller enables you to start the animation whenever you want with /// [autoStart] option and customize animation duration as well. -class FlameSplashController { - FlameSplashController({ - Duration fadeInDuration = const Duration(milliseconds: 750), - Duration waitDuration = const Duration(seconds: 2), - Duration fadeOutDuration = const Duration(milliseconds: 450), - this.autoStart = true, - }) : stepController = FlameSplashControllerStep(0), - durations = FlameSplashDurations( - fadeInDuration, - waitDuration, - fadeOutDuration, - ); +class FlameSplashController({ + Duration fadeInDuration = const Duration(milliseconds: 750), + Duration waitDuration = const Duration(seconds: 2), + Duration fadeOutDuration = const Duration(milliseconds: 450), /// Defines if you want to start the animations right after widget mount. - final bool autoStart; + final bool autoStart = true, +}) { + this : stepController = FlameSplashControllerStep(0); @internal - final FlameSplashDurations durations; + final FlameSplashDurations durations = FlameSplashDurations( + fadeInDuration, + waitDuration, + fadeOutDuration, + ); @internal final FlameSplashControllerStep stepController; @@ -87,7 +85,7 @@ class FlameSplashController { } /// Represents the state of the splash screen. -enum FlameSplashControllerState { +enum FlameSplashControllerState() { /// Not started yet, but ready to start. /// Note that if autoStart is set, this stage will be skipped. idle, @@ -99,21 +97,13 @@ enum FlameSplashControllerState { finished, } -class FlameSplashControllerStep extends ValueNotifier { - FlameSplashControllerStep(super.value); -} - -class FlameSplashDurations { - const FlameSplashDurations( - this.fadeInDuration, - this.waitDuration, - this.fadeOutDuration, - ); - - final Duration fadeInDuration; - final Duration waitDuration; - final Duration fadeOutDuration; +class FlameSplashControllerStep(super.value) extends ValueNotifier; +class const FlameSplashDurations( + final Duration fadeInDuration, + final Duration waitDuration, + final Duration fadeOutDuration, +) { Duration get total { return fadeInDuration + fadeOutDuration + waitDuration; } diff --git a/packages/flame_splash_screen/lib/src/splash.dart b/packages/flame_splash_screen/lib/src/splash.dart index 9e74887c8ac..ebdbd48e491 100644 --- a/packages/flame_splash_screen/lib/src/splash.dart +++ b/packages/flame_splash_screen/lib/src/splash.dart @@ -2,36 +2,27 @@ import 'package:flame_splash_screen/flame_splash_screen.dart'; import 'package:flutter/widgets.dart'; /// A stateful widget to show a splash screen animation for flame games -class FlameSplashScreen extends StatefulWidget { - /// Creates a [FlameSplashScreen]. - const FlameSplashScreen({ - required this.onFinish, - required this.theme, - this.showBefore, - this.showAfter, - this.controller, - super.key, - }); - - /// Gives extra controller over the splash animation. - final FlameSplashController? controller; +class const FlameSplashScreen({ + /// The only required option, callback to be invoked when animation finished + required final ValueChanged onFinish, /// Enables to set a different theme other than the default. - final FlameSplashTheme theme; - - /// The only required option, callback to be invoked when animation finished - final ValueChanged onFinish; + required final FlameSplashTheme theme, /// Adds an extra step to the animation showing a widget, can be other logo. /// /// Shown before flame logo. - final WidgetBuilder? showBefore; + final WidgetBuilder? showBefore, /// Adds an extra step to the animation showing a widget, can be other logo. /// /// Shown after flame logo. - final WidgetBuilder? showAfter; + final WidgetBuilder? showAfter, + /// Gives extra controller over the splash animation. + final FlameSplashController? controller, + super.key, +}) extends StatefulWidget { @override FlameSplashScreenState createState() => FlameSplashScreenState(); } @@ -39,7 +30,7 @@ class FlameSplashScreen extends StatefulWidget { /// The state for the [FlameSplashScreen] that holds the [controller] for /// controlling the animation durations and whether it should automatically /// start. Also contains the list of steps that it should animate through. -class FlameSplashScreenState extends State { +class FlameSplashScreenState() extends State { /// The [controller] for controlling the animation durations and whether it /// should automatically start. late FlameSplashController controller; @@ -112,21 +103,17 @@ class FlameSplashScreenState extends State { } } -class _SplashScreenStep extends StatefulWidget { - const _SplashScreenStep({ - required this.builder, - required this.durations, - super.key, - }); - - final WidgetBuilder builder; - final FlameSplashDurations durations; - +class const _SplashScreenStep({ + required final WidgetBuilder builder, + required final FlameSplashDurations durations, + super.key, +}) extends StatefulWidget { @override __SplashScreenStepState createState() => __SplashScreenStepState(); } -class __SplashScreenStepState extends State<_SplashScreenStep> +class __SplashScreenStepState() + extends State<_SplashScreenStep> with TickerProviderStateMixin { late AnimationController controller; late Animation opacityAnimation; diff --git a/packages/flame_splash_screen/lib/src/theme.dart b/packages/flame_splash_screen/lib/src/theme.dart index c443d72432f..cf845dec009 100644 --- a/packages/flame_splash_screen/lib/src/theme.dart +++ b/packages/flame_splash_screen/lib/src/theme.dart @@ -2,13 +2,13 @@ import 'package:flutter/widgets.dart'; /// This widget builds up the Flame logo composed of 3 layers, /// that are rendered via separate PNG files under the assets directory. -class AnimatedLogo extends AnimatedWidget { +class const AnimatedLogo({ + required Animation animation, + super.key, +}) extends AnimatedWidget { /// Create this widget providing the animation parameter to control /// the opacity of the flame. - const AnimatedLogo({ - required Animation animation, - super.key, - }) : super(listenable: animation); + this : super(listenable: animation); @override Widget build(BuildContext context) { @@ -39,16 +39,14 @@ class AnimatedLogo extends AnimatedWidget { /// Creates and controls an [AnimatedLogo], making sure to provide the required /// animation and to properly dispose of itself after usage. -class LogoComposite extends StatefulWidget { - /// Creates a [LogoComposite]. - const LogoComposite({super.key}); - +class const LogoComposite({super.key}) extends StatefulWidget { @override LogoCompositeState createState() => LogoCompositeState(); } /// The state holding the state of the animated logo and its controller. -class LogoCompositeState extends State +class LogoCompositeState() + extends State with SingleTickerProviderStateMixin { /// The state of the animated logo. late Animation animation; @@ -103,26 +101,21 @@ Widget _logoBuilder(BuildContext context) { /// Wraps the splash screen layout options. /// There is two predefined themes [FlameSplashTheme.dark] and /// [FlameSplashTheme.white]. -class FlameSplashTheme { - /// Creates a customized theme. [logoBuilder] returns the widget that will be - /// rendered in place of main step of the animation. - const FlameSplashTheme({ - required this.backgroundDecoration, - required this.logoBuilder, - this.constraints = const BoxConstraints.expand(), - }); - +/// +/// Creates a customized theme. [logoBuilder] returns the widget that will be +/// rendered in place of main step of the animation. +class const FlameSplashTheme({ /// Decoration to be applied to the widget underneath the Flame logo. /// It can be used to set the background color, among other parameters. - final BoxDecoration backgroundDecoration; + required final BoxDecoration backgroundDecoration, /// A lambda to build the widget representing the logo itself. /// By default this will be wired to use the [LogoComposite] widget. - final WidgetBuilder logoBuilder; + required final WidgetBuilder logoBuilder, /// Th constraints of the outside box, defaults to [BoxConstraints.expand]. - final BoxConstraints constraints; - + final BoxConstraints constraints = const BoxConstraints.expand(), +}) { /// One of the two default themes provided; this is optimal of light mode /// apps. static FlameSplashTheme white = const FlameSplashTheme( diff --git a/packages/flame_splash_screen/pubspec.yaml b/packages/flame_splash_screen/pubspec.yaml index c1e1a12f6fc..9bef3ec9225 100644 --- a/packages/flame_splash_screen/pubspec.yaml +++ b/packages/flame_splash_screen/pubspec.yaml @@ -11,8 +11,8 @@ topics: - flame environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flutter: diff --git a/packages/flame_splash_screen/test/controller_test.dart b/packages/flame_splash_screen/test/controller_test.dart index 4aa158e1b4d..41e9bc86c84 100644 --- a/packages/flame_splash_screen/test/controller_test.dart +++ b/packages/flame_splash_screen/test/controller_test.dart @@ -2,11 +2,11 @@ import 'package:flame_splash_screen/flame_splash_screen.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; -class OnFinishContainer { +class OnFinishContainer() { void onFinish() {} } -class MockOnFinish extends Mock implements OnFinishContainer {} +class MockOnFinish() extends Mock implements OnFinishContainer; void main() { group('Without autostart', () { diff --git a/packages/flame_sprite_fusion/example/lib/main.dart b/packages/flame_sprite_fusion/example/lib/main.dart index 763f08d1d7a..caeb7fe14c0 100644 --- a/packages/flame_sprite_fusion/example/lib/main.dart +++ b/packages/flame_sprite_fusion/example/lib/main.dart @@ -9,9 +9,7 @@ void main() { runApp(const MyApp()); } -class MyApp extends StatelessWidget { - const MyApp({super.key}); - +class const MyApp({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( @@ -24,9 +22,7 @@ class MyApp extends StatelessWidget { } } -class PlatformerGame extends FlameGame { - PlatformerGame({super.camera}); - +class PlatformerGame({super.camera}) extends FlameGame { @override Color backgroundColor() => Colors.white70; diff --git a/packages/flame_sprite_fusion/example/pubspec.yaml b/packages/flame_sprite_fusion/example/pubspec.yaml index bbcbfb138a3..4787ae5ddac 100644 --- a/packages/flame_sprite_fusion/example/pubspec.yaml +++ b/packages/flame_sprite_fusion/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: "none" version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_sprite_fusion/lib/flame_sprite_fusion.dart b/packages/flame_sprite_fusion/lib/flame_sprite_fusion.dart index d802cb69434..f085341eafc 100644 --- a/packages/flame_sprite_fusion/lib/flame_sprite_fusion.dart +++ b/packages/flame_sprite_fusion/lib/flame_sprite_fusion.dart @@ -1,5 +1,3 @@ -library flame_sprite_fusion; - export 'src/sprite_fusion_layer_data.dart'; export 'src/sprite_fusion_tile_data.dart'; export 'src/sprite_fusion_tilemap_component.dart'; diff --git a/packages/flame_sprite_fusion/lib/src/sprite_fusion_layer_data.dart b/packages/flame_sprite_fusion/lib/src/sprite_fusion_layer_data.dart index 36c8fcd7f8d..f80ac115628 100644 --- a/packages/flame_sprite_fusion/lib/src/sprite_fusion_layer_data.dart +++ b/packages/flame_sprite_fusion/lib/src/sprite_fusion_layer_data.dart @@ -1,23 +1,16 @@ import 'package:flame_sprite_fusion/flame_sprite_fusion.dart'; /// A class that holds the data of a layer from a sprite fusion map. -class SpriteFusionLayerData { +class SpriteFusionLayerData({ /// The name of the layer. - final String name; + required final String name, /// The tiles of the layer. - final List tiles; + required final List tiles, /// If the layer is a collider. - final bool collider; - - /// Creates a new instance of [SpriteFusionLayerData]. - SpriteFusionLayerData({ - required this.name, - required this.tiles, - required this.collider, - }); - + required final bool collider, +}) { /// Creates a new instance of [SpriteFusionLayerData] from a map. factory SpriteFusionLayerData.fromMap(Map map) { return SpriteFusionLayerData( diff --git a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tile_data.dart b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tile_data.dart index 6e60de27070..ff420ced595 100644 --- a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tile_data.dart +++ b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tile_data.dart @@ -1,28 +1,20 @@ /// A class that holds the data of a tile from a sprite fusion map. -class SpriteFusionTileData { +class SpriteFusionTileData({ /// The id of the tile. /// /// This is also the index position of the tile in the tileset, starting at 0, /// from left to right, top to bottom. - final int id; + required final int id, /// The x position of the tile in tile units. - final int x; + required final int x, /// The y position of the tile in tile units. - final int y; + required final int y, /// The attributes of the tile. - final Map? attributes; - - /// Creates a new instance of [SpriteFusionTileData]. - SpriteFusionTileData({ - required this.id, - required this.x, - required this.y, - this.attributes, - }); - + final Map? attributes, +}) { /// Creates a new instance of [SpriteFusionTileData] from a map. factory SpriteFusionTileData.fromMap(Map map) { return SpriteFusionTileData( diff --git a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart index 68dfe6bc8bc..bd6990532aa 100644 --- a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart +++ b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart @@ -9,36 +9,34 @@ import 'package:flame_sprite_fusion/flame_sprite_fusion.dart'; import 'package:flutter/widgets.dart'; /// A component that renders a tilemap from a sprite fusion. -class SpriteFusionTilemapComponent extends PositionComponent { +class SpriteFusionTilemapComponent({ /// The data of the tilemap. - final SpriteFusionTilemapData tilemapData; + required final SpriteFusionTilemapData tilemapData, /// The sprite sheet of the tilemap. - final SpriteSheet spriteSheet; - + required final SpriteSheet spriteSheet, + bool useAtlas = true, + super.position, + super.scale, + super.angle, + super.nativeAngle, + super.anchor, + super.children, + super.priority, + super.key, +}) extends PositionComponent { /// The sprite batch of the tilemap. late final SpriteBatch _spriteBatch; /// Creates a new [SpriteFusionTilemapComponent] with the given [tilemapData] /// and [spriteSheet]. - SpriteFusionTilemapComponent({ - required this.tilemapData, - required this.spriteSheet, - bool useAtlas = true, - super.position, - super.scale, - super.angle, - super.nativeAngle, - super.anchor, - super.children, - super.priority, - super.key, - }) : super( - size: Vector2( - tilemapData.mapWidth * tilemapData.tileSize, - tilemapData.mapHeight * tilemapData.tileSize, - ), - ) { + this + : super( + size: Vector2( + tilemapData.mapWidth * tilemapData.tileSize, + tilemapData.mapHeight * tilemapData.tileSize, + ), + ) { _spriteBatch = SpriteBatch(spriteSheet.image, useAtlas: useAtlas); for (final data in tilemapData.layers.reversed) { diff --git a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_data.dart b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_data.dart index 1be0dcd5f04..d40dc12fdab 100644 --- a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_data.dart +++ b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_data.dart @@ -2,27 +2,19 @@ import 'package:collection/collection.dart'; import 'package:flame_sprite_fusion/flame_sprite_fusion.dart'; /// A class that holds the data of the tilemap from a sprite fusion. -class SpriteFusionTilemapData { +class SpriteFusionTilemapData({ /// The size of the tiles in the tilemap. - final double tileSize; + required final double tileSize, /// The width of the tilemap in tile units. - final double mapWidth; + required final double mapWidth, /// The height of the tilemap in tile units. - final double mapHeight; + required final double mapHeight, /// The layers of the tilemap. - final List layers; - - /// Creates a new instance of [SpriteFusionTilemapData]. - SpriteFusionTilemapData({ - required this.tileSize, - required this.mapWidth, - required this.mapHeight, - required this.layers, - }); - + required final List layers, +}) { /// Creates a new instance of [SpriteFusionTilemapData] from a map. factory SpriteFusionTilemapData.fromMap(Map map) { return SpriteFusionTilemapData( diff --git a/packages/flame_sprite_fusion/pubspec.yaml b/packages/flame_sprite_fusion/pubspec.yaml index 1b8b51f01d6..e6bb3cb0924 100644 --- a/packages/flame_sprite_fusion/pubspec.yaml +++ b/packages/flame_sprite_fusion/pubspec.yaml @@ -12,8 +12,8 @@ topics: - tilemap environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.19.1 diff --git a/packages/flame_sprite_fusion/test/test_asset_bundle.dart b/packages/flame_sprite_fusion/test/test_asset_bundle.dart index f84cd5d9650..b09f0caf174 100644 --- a/packages/flame_sprite_fusion/test/test_asset_bundle.dart +++ b/packages/flame_sprite_fusion/test/test_asset_bundle.dart @@ -8,15 +8,10 @@ import 'package:flutter/services.dart' show CachingAssetBundle; /// Keys are full asset paths, exactly as they would be declared in a /// `pubspec.yaml`, and are mapped onto the fixture directory. For example, /// `assets/map.json` resolves to `test/assets/map.json`. -class TestAssetBundle extends CachingAssetBundle { - TestAssetBundle({ - required this.imageNames, - required this.stringNames, - }); - - final List imageNames; - final List stringNames; - +class TestAssetBundle({ + required final List imageNames, + required final List stringNames, +}) extends CachingAssetBundle { String _resolve(String key, List known) { final name = key.startsWith('assets/') ? key.substring('assets/'.length) diff --git a/packages/flame_steering_behaviors/example/lib/src/behaviors/screen_wrapping_behavior.dart b/packages/flame_steering_behaviors/example/lib/src/behaviors/screen_wrapping_behavior.dart index 355eaee5059..3cbe8bf0118 100644 --- a/packages/flame_steering_behaviors/example/lib/src/behaviors/screen_wrapping_behavior.dart +++ b/packages/flame_steering_behaviors/example/lib/src/behaviors/screen_wrapping_behavior.dart @@ -3,7 +3,8 @@ import 'package:flame_behaviors/flame_behaviors.dart'; /// Simplified "screen wrapping" behavior, while not perfect it does showcase /// the possibility of acting on collision with non-entities. -class ScreenWrappingBehavior extends ScreenCollisionBehavior { +class ScreenWrappingBehavior() + extends ScreenCollisionBehavior { @override void onCollisionEnd(ScreenHitbox other) { if (parent.position.x < other.position.x) { diff --git a/packages/flame_steering_behaviors/example/lib/src/entities/dot/dot.dart b/packages/flame_steering_behaviors/example/lib/src/entities/dot/dot.dart index eac10c4d9df..5346f30e565 100644 --- a/packages/flame_steering_behaviors/example/lib/src/entities/dot/dot.dart +++ b/packages/flame_steering_behaviors/example/lib/src/entities/dot/dot.dart @@ -7,29 +7,30 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; import 'package:flame_steering_behaviors_example/src/behaviors/behaviors.dart'; import 'package:flame_steering_behaviors_example/src/example_game.dart'; -class Dot extends PositionedEntity with Steerable { - Dot({ - super.position, - Random? random, - }) : super( - size: Vector2.all(relativeValue), - children: [ - CircleComponent.relative( - 1, - parentSize: Vector2.all(relativeValue), - ), - ], - behaviors: [ - PropagatingCollisionBehavior(CircleHitbox()), - ScreenWrappingBehavior(), - WanderBehavior( - circleDistance: 3 * relativeValue, - maximumAngle: 45 * degrees2Radians, - startingAngle: 0, - random: random, - ), - ], - ); +class Dot({ + super.position, + Random? random, +}) extends PositionedEntity with Steerable { + this + : super( + size: Vector2.all(relativeValue), + children: [ + CircleComponent.relative( + 1, + parentSize: Vector2.all(relativeValue), + ), + ], + behaviors: [ + PropagatingCollisionBehavior(CircleHitbox()), + ScreenWrappingBehavior(), + WanderBehavior( + circleDistance: 3 * relativeValue, + maximumAngle: 45 * degrees2Radians, + startingAngle: 0, + random: random, + ), + ], + ); @override double get maxVelocity => 10 * relativeValue; diff --git a/packages/flame_steering_behaviors/example/lib/src/example_game.dart b/packages/flame_steering_behaviors/example/lib/src/example_game.dart index f5cf061c359..b86420aa075 100644 --- a/packages/flame_steering_behaviors/example/lib/src/example_game.dart +++ b/packages/flame_steering_behaviors/example/lib/src/example_game.dart @@ -4,8 +4,8 @@ import 'package:flame_steering_behaviors_example/src/entities/entities.dart'; const relativeValue = 16.0; -class ExampleGame extends FlameGame with HasCollisionDetection { - ExampleGame() +class ExampleGame() extends FlameGame with HasCollisionDetection { + this : super( children: [ FpsTextComponent(position: Vector2.zero()), diff --git a/packages/flame_steering_behaviors/example/pubspec.yaml b/packages/flame_steering_behaviors/example/pubspec.yaml index 590561517cc..93939561ae2 100644 --- a/packages/flame_steering_behaviors/example/pubspec.yaml +++ b/packages/flame_steering_behaviors/example/pubspec.yaml @@ -5,7 +5,7 @@ version: 1.0.0+1 publish_to: none environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_steering_behaviors/example/test/helpers/test_game.dart b/packages/flame_steering_behaviors/example/test/helpers/test_game.dart index bc6a5ad5393..63938718e16 100644 --- a/packages/flame_steering_behaviors/example/test/helpers/test_game.dart +++ b/packages/flame_steering_behaviors/example/test/helpers/test_game.dart @@ -1,3 +1,3 @@ import 'package:flame/game.dart'; -class TestGame extends FlameGame with HasCollisionDetection {} +class TestGame() extends FlameGame with HasCollisionDetection; diff --git a/packages/flame_steering_behaviors/example/test/src/behaviors/screen_wrapping_behavior_test.dart b/packages/flame_steering_behaviors/example/test/src/behaviors/screen_wrapping_behavior_test.dart index f0ec4064698..5e11f2c4a48 100644 --- a/packages/flame_steering_behaviors/example/test/src/behaviors/screen_wrapping_behavior_test.dart +++ b/packages/flame_steering_behaviors/example/test/src/behaviors/screen_wrapping_behavior_test.dart @@ -8,10 +8,10 @@ import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; -class _MockScreenHitbox extends Mock implements ScreenHitbox {} +class _MockScreenHitbox() extends Mock implements ScreenHitbox; -class _TestEntity extends PositionedEntity { - _TestEntity({super.position}) : super(size: Vector2.all(50)); +class _TestEntity({super.position}) extends PositionedEntity { + this : super(size: Vector2.all(50)); } void main() { diff --git a/packages/flame_steering_behaviors/example/test/src/entities/dot_test.dart b/packages/flame_steering_behaviors/example/test/src/entities/dot_test.dart index 3d78c21f449..eabee7e1201 100644 --- a/packages/flame_steering_behaviors/example/test/src/entities/dot_test.dart +++ b/packages/flame_steering_behaviors/example/test/src/entities/dot_test.dart @@ -10,7 +10,7 @@ import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; -class _MockRandom extends Mock implements Random {} +class _MockRandom() extends Mock implements Random; void main() { final flameTester = FlameTester(TestGame.new); diff --git a/packages/flame_steering_behaviors/lib/src/behaviors/flee_behavior.dart b/packages/flame_steering_behaviors/lib/src/behaviors/flee_behavior.dart index 62707ea4c6c..84fe132a490 100644 --- a/packages/flame_steering_behaviors/lib/src/behaviors/flee_behavior.dart +++ b/packages/flame_steering_behaviors/lib/src/behaviors/flee_behavior.dart @@ -5,24 +5,17 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template flee_behavior} /// Flee steering behavior. /// {@endtemplate} -class FleeBehavior extends SteeringBehavior { - /// {@macro flee_behavior} - FleeBehavior( - this.target, { - required this.maxAcceleration, - required this.panicDistance, - }); - +class FleeBehavior( /// The target to flee from. - final ReadOnlyPositionProvider target; + final ReadOnlyPositionProvider target, { /// The maximum acceleration of the entity. - final double maxAcceleration; + required final double maxAcceleration, /// The maximum distance between the target and entity for the entity to /// panic. - final double panicDistance; - + required final double panicDistance, +}) extends SteeringBehavior { @override void update(double dt) { final distanceToTarget = target.position.distanceTo(parent.position); diff --git a/packages/flame_steering_behaviors/lib/src/behaviors/pursue_behavior.dart b/packages/flame_steering_behaviors/lib/src/behaviors/pursue_behavior.dart index 97385cf4086..8a2cfe653df 100644 --- a/packages/flame_steering_behaviors/lib/src/behaviors/pursue_behavior.dart +++ b/packages/flame_steering_behaviors/lib/src/behaviors/pursue_behavior.dart @@ -6,24 +6,16 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template pursue_behavior} /// Pursue steering behavior. /// {@endtemplate} -class PursueBehavior - extends SteeringBehavior { - /// {@macro pursue_behavior} - PursueBehavior( - this.target, { - required this.pursueRange, - this.maxPrediction = 1, - }); - +class PursueBehavior( /// The target to pursue. - final PositionComponent target; - - /// The maximum prediction time. - final double maxPrediction; + final PositionComponent target, { /// The range in which the goblin will pursue the player. - final double pursueRange; + required final double pursueRange, + /// The maximum prediction time. + final double maxPrediction = 1, +}) extends SteeringBehavior { @override void update(double dt) { final distanceToTarget = target.distance(parent); diff --git a/packages/flame_steering_behaviors/lib/src/behaviors/separation_behavior.dart b/packages/flame_steering_behaviors/lib/src/behaviors/separation_behavior.dart index 9d1b5092271..5c530b04608 100644 --- a/packages/flame_steering_behaviors/lib/src/behaviors/separation_behavior.dart +++ b/packages/flame_steering_behaviors/lib/src/behaviors/separation_behavior.dart @@ -4,24 +4,16 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template separation_behavior} /// Separation steering behavior. /// {@endtemplate} -class SeparationBehavior - extends SteeringBehavior { - /// {@macro separation_behavior} - SeparationBehavior( - this.entities, { - required this.maxDistance, - required this.maxAcceleration, - }); +class SeparationBehavior( + /// The entities to separate from. + final Iterable entities, { /// The maximum distance at which the entity will separate. - final double maxDistance; + required final double maxDistance, /// The maximum acceleration the entity can apply to enable separation. - final double maxAcceleration; - - /// The entities to separate from. - final Iterable entities; - + required final double maxAcceleration, +}) extends SteeringBehavior { @override void update(double dt) { steer( diff --git a/packages/flame_steering_behaviors/lib/src/behaviors/steering_behavior.dart b/packages/flame_steering_behaviors/lib/src/behaviors/steering_behavior.dart index 6780c2515b3..1f4b0b9dd3d 100644 --- a/packages/flame_steering_behaviors/lib/src/behaviors/steering_behavior.dart +++ b/packages/flame_steering_behaviors/lib/src/behaviors/steering_behavior.dart @@ -4,6 +4,6 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template steering_behavior} /// Abstract base class for steering behaviors. /// {@endtemplate} -abstract class SteeringBehavior +abstract class SteeringBehavior() extends Behavior - with Steering {} + with Steering; diff --git a/packages/flame_steering_behaviors/lib/src/behaviors/wander_behavior.dart b/packages/flame_steering_behaviors/lib/src/behaviors/wander_behavior.dart index 1419727bd51..fc0372a2276 100644 --- a/packages/flame_steering_behaviors/lib/src/behaviors/wander_behavior.dart +++ b/packages/flame_steering_behaviors/lib/src/behaviors/wander_behavior.dart @@ -5,29 +5,21 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template wander_behavior} /// Wander steering behavior. /// {@endtemplate} -class WanderBehavior - extends SteeringBehavior { - /// {@macro wander_behavior} - WanderBehavior({ - required this.circleDistance, - required this.maximumAngle, - required double startingAngle, - Random? random, - }) : _angle = startingAngle, - random = random ?? Random(); - +class WanderBehavior({ /// The distance to the circle center of the next target. - final double circleDistance; + required final double circleDistance, /// The rate at which the wander angle can change in radians. - final double maximumAngle; - + required final double maximumAngle, + required double startingAngle, + Random? random, +}) extends SteeringBehavior { /// The current wander angle in radians. double get angle => _angle; - double _angle; + double _angle = startingAngle; /// The random number generator used to calculate the next wander [angle]. - final Random random; + final Random random = random ?? Random(); @override void update(double dt) { diff --git a/packages/flame_steering_behaviors/lib/src/steering/flee.dart b/packages/flame_steering_behaviors/lib/src/steering/flee.dart index 03b692b947c..5e60b14ccee 100644 --- a/packages/flame_steering_behaviors/lib/src/steering/flee.dart +++ b/packages/flame_steering_behaviors/lib/src/steering/flee.dart @@ -5,19 +5,13 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template flee} /// Flee steering algorithm. /// {@endtemplate} -class Flee extends SteeringCore { - /// {@macro flee} - const Flee( - this.target, { - required this.maxAcceleration, - }); - +class const Flee( /// The target to flee from. - final ReadOnlyPositionProvider target; + final ReadOnlyPositionProvider target, { /// The maximum acceleration of the entity. - final double maxAcceleration; - + required final double maxAcceleration, +}) extends SteeringCore { @override Vector2 getSteering(Steerable parent) { final desiredVelocity = (parent.position - target.position) diff --git a/packages/flame_steering_behaviors/lib/src/steering/pursue.dart b/packages/flame_steering_behaviors/lib/src/steering/pursue.dart index b0111175878..580794ea0fe 100644 --- a/packages/flame_steering_behaviors/lib/src/steering/pursue.dart +++ b/packages/flame_steering_behaviors/lib/src/steering/pursue.dart @@ -6,19 +6,13 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template pursue} /// Pursue steering algorithm. /// {@endtemplate} -class Pursue extends SteeringCore { - /// {@macro pursue} - const Pursue( - this.target, { - required this.maxPrediction, - }); - +class const Pursue( /// The target to pursue. - final ReadOnlyPositionProvider target; + final ReadOnlyPositionProvider target, { /// The maximum prediction time. - final double maxPrediction; - + required final double maxPrediction, +}) extends SteeringCore { @override Vector2 getSteering(Steerable parent) { final displacement = target.position - parent.position; diff --git a/packages/flame_steering_behaviors/lib/src/steering/separation.dart b/packages/flame_steering_behaviors/lib/src/steering/separation.dart index 34c3a1244da..ba256e318a5 100644 --- a/packages/flame_steering_behaviors/lib/src/steering/separation.dart +++ b/packages/flame_steering_behaviors/lib/src/steering/separation.dart @@ -4,23 +4,16 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template separation} /// Separation steering algorithm. /// {@endtemplate} -class Separation extends SteeringCore { - /// {@macro separation} - const Separation( - this.entities, { - required this.maxDistance, - required this.maxAcceleration, - }); +class const Separation( + /// The entities to separate from. + final Iterable entities, { /// The maximum distance at which the entity will separate. - final double maxDistance; + required final double maxDistance, /// The maximum acceleration the entity can apply to enable separation. - final double maxAcceleration; - - /// The entities to separate from. - final Iterable entities; - + required final double maxAcceleration, +}) extends SteeringCore { @override Vector2 getSteering(Steerable parent) { final acceleration = Vector2.zero(); diff --git a/packages/flame_steering_behaviors/lib/src/steering/steering_core.dart b/packages/flame_steering_behaviors/lib/src/steering/steering_core.dart index 2b2b04d09c2..e91e09505a3 100644 --- a/packages/flame_steering_behaviors/lib/src/steering/steering_core.dart +++ b/packages/flame_steering_behaviors/lib/src/steering/steering_core.dart @@ -4,10 +4,7 @@ import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template steering_core} /// Base class for all steering behaviors. /// {@endtemplate} -abstract class SteeringCore { - /// {@macro steering_core} - const SteeringCore(); - +abstract class const SteeringCore() { /// Calculates the next target position to steer towards. Vector2 getSteering(Steerable parent); diff --git a/packages/flame_steering_behaviors/lib/src/steering/wander.dart b/packages/flame_steering_behaviors/lib/src/steering/wander.dart index a2a1c75c414..3d0e7d15e44 100644 --- a/packages/flame_steering_behaviors/lib/src/steering/wander.dart +++ b/packages/flame_steering_behaviors/lib/src/steering/wander.dart @@ -10,35 +10,26 @@ import 'package:flutter/foundation.dart'; /// The [onNewAngle] should be used to get the [angle] value for the next /// [Wander] creation. /// {@endtemplate} -class Wander extends SteeringCore { - /// {@macro wander} - Wander({ - required this.circleDistance, - required this.maximumAngle, - required this.angle, - required this.onNewAngle, - required this.random, - }); - +class Wander({ /// The distance to the circle center of the next target. - final double circleDistance; + required final double circleDistance, /// The maximum angle used to calculate the next wander [angle]. /// /// Value is represented in radians. - final double maximumAngle; + required final double maximumAngle, /// The current wander angle in radians. - final double angle; + required final double angle, /// Called when the next [angle] value is calculated. /// /// The next call to [Wander] expects the angle to be this value. - final ValueChanged onNewAngle; + required final ValueChanged onNewAngle, /// The random number generator used to calculate the next wander [angle]. - final Random random; - + required final Random random, +}) extends SteeringCore { @override Vector2 getSteering(Steerable parent) { // Calculate the circle center for the next target that is right in front diff --git a/packages/flame_steering_behaviors/pubspec.yaml b/packages/flame_steering_behaviors/pubspec.yaml index c1fa67974cd..97f7843129c 100644 --- a/packages/flame_steering_behaviors/pubspec.yaml +++ b/packages/flame_steering_behaviors/pubspec.yaml @@ -5,8 +5,8 @@ version: 0.3.0-dev.0+7 homepage: https://github.com/flame-engine/flame/tree/main/packages/flame_steering_behaviors environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_steering_behaviors/test/helpers/steerable_entity.dart b/packages/flame_steering_behaviors/test/helpers/steerable_entity.dart index 2750993087d..99c92b72c38 100644 --- a/packages/flame_steering_behaviors/test/helpers/steerable_entity.dart +++ b/packages/flame_steering_behaviors/test/helpers/steerable_entity.dart @@ -2,13 +2,11 @@ import 'package:flame/extensions.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; -class SteerableEntity extends PositionedEntity with Steerable { - SteerableEntity({ - super.position, - super.behaviors, - super.size, - }); - +class SteerableEntity({ + super.position, + super.behaviors, + super.size, +}) extends PositionedEntity with Steerable { @override double get maxVelocity => 100; diff --git a/packages/flame_steering_behaviors/test/helpers/test_game.dart b/packages/flame_steering_behaviors/test/helpers/test_game.dart index bc6a5ad5393..63938718e16 100644 --- a/packages/flame_steering_behaviors/test/helpers/test_game.dart +++ b/packages/flame_steering_behaviors/test/helpers/test_game.dart @@ -1,3 +1,3 @@ import 'package:flame/game.dart'; -class TestGame extends FlameGame with HasCollisionDetection {} +class TestGame() extends FlameGame with HasCollisionDetection; diff --git a/packages/flame_steering_behaviors/test/src/behaviors/wander_behavior_test.dart b/packages/flame_steering_behaviors/test/src/behaviors/wander_behavior_test.dart index 2780a015afb..83c9ec48cb8 100644 --- a/packages/flame_steering_behaviors/test/src/behaviors/wander_behavior_test.dart +++ b/packages/flame_steering_behaviors/test/src/behaviors/wander_behavior_test.dart @@ -8,7 +8,7 @@ import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; -class _MockRandom extends Mock implements Random {} +class _MockRandom() extends Mock implements Random; const _startAngle = 90 * degrees2Radians; const _randomValue = 0.25; diff --git a/packages/flame_steering_behaviors/test/src/mixins/steering_test.dart b/packages/flame_steering_behaviors/test/src/mixins/steering_test.dart index e220811da07..e3d50ae6126 100644 --- a/packages/flame_steering_behaviors/test/src/mixins/steering_test.dart +++ b/packages/flame_steering_behaviors/test/src/mixins/steering_test.dart @@ -7,11 +7,11 @@ import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; -class _TestBehavior extends Behavior with Steering {} +class _TestBehavior() extends Behavior with Steering; -class _MockSteeringCore extends Mock implements SteeringCore {} +class _MockSteeringCore() extends Mock implements SteeringCore; -class _FakeSteerable extends Fake implements Steerable {} +class _FakeSteerable() extends Fake implements Steerable; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame_steering_behaviors/test/src/steering/steering_core_test.dart b/packages/flame_steering_behaviors/test/src/steering/steering_core_test.dart index 53cbb44faaa..e0641a46a50 100644 --- a/packages/flame_steering_behaviors/test/src/steering/steering_core_test.dart +++ b/packages/flame_steering_behaviors/test/src/steering/steering_core_test.dart @@ -5,7 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; import '../../helpers/helpers.dart'; -class _TestSteeringCore extends SteeringCore { +class _TestSteeringCore() extends SteeringCore { @override Vector2 getSteering(Steerable parent) { throw UnimplementedError(); diff --git a/packages/flame_steering_behaviors/test/src/steering/wander_test.dart b/packages/flame_steering_behaviors/test/src/steering/wander_test.dart index 1068c13b8a3..0af5657db8d 100644 --- a/packages/flame_steering_behaviors/test/src/steering/wander_test.dart +++ b/packages/flame_steering_behaviors/test/src/steering/wander_test.dart @@ -8,7 +8,7 @@ import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; -class _MockRandom extends Mock implements Random {} +class _MockRandom() extends Mock implements Random; void main() { group('Wander', () { diff --git a/packages/flame_studio/example/main.dart b/packages/flame_studio/example/main.dart index 183b2822b2f..c35fce1601b 100644 --- a/packages/flame_studio/example/main.dart +++ b/packages/flame_studio/example/main.dart @@ -1,4 +1,5 @@ import 'dart:math'; + import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; import 'package:flame_studio/flame_studio.dart'; @@ -13,7 +14,7 @@ void main() { ); } -class MyGame extends FlameGame { +class MyGame() extends FlameGame { @override Color backgroundColor() => const Color(0x00000000); @@ -38,14 +39,11 @@ class MyGame extends FlameGame { } } -class Circle extends CircleComponent { - Circle({ - required this.velocity, - required super.position, - super.radius = 15.0, - }); - - final Vector2 velocity; +class Circle({ + required final Vector2 velocity, + required super.position, + super.radius = 15.0, +}) extends CircleComponent { final Vector2 gameSize = Vector2.zero(); @override diff --git a/packages/flame_studio/lib/src/core/component_tree.dart b/packages/flame_studio/lib/src/core/component_tree.dart index b99a68ccca6..7b17ab586d6 100644 --- a/packages/flame_studio/lib/src/core/component_tree.dart +++ b/packages/flame_studio/lib/src/core/component_tree.dart @@ -11,9 +11,10 @@ final componentTreeProvider = }); @immutable -class ComponentTreeNode { - const ComponentTreeNode._(this.component, this.children); - +class const ComponentTreeNode._( + final Component component, + final List? children, +) { factory ComponentTreeNode.fromComponent(Component component) { return ComponentTreeNode._( component, @@ -23,8 +24,6 @@ class ComponentTreeNode { ); } - final Component component; - final List? children; String get name => component.runtimeType.toString(); bool get hasChildren => children?.isNotEmpty ?? false; @@ -39,13 +38,11 @@ class ComponentTreeNode { } @immutable -class ComponentTreeState { - ComponentTreeState(Component? rootComponent) - : root = rootComponent == null - ? null - : ComponentTreeNode.fromComponent(rootComponent); - - final ComponentTreeNode? root; +// ignore: prefer_const_constructors_in_immutables +class ComponentTreeState(Component? rootComponent) { + final ComponentTreeNode? root = rootComponent == null + ? null + : ComponentTreeNode.fromComponent(rootComponent); @override bool operator ==(Object other) => @@ -55,9 +52,9 @@ class ComponentTreeState { int get hashCode => root?.hashCode ?? 0; } -class ComponentTreeObserver extends StateNotifier { - ComponentTreeObserver(Component? rootComponent) - : super(ComponentTreeState(rootComponent)) { +class ComponentTreeObserver(Component? rootComponent) + extends StateNotifier { + this : super(ComponentTreeState(rootComponent)) { if (rootComponent != null) { _refresh(); } diff --git a/packages/flame_studio/lib/src/core/game_controller.dart b/packages/flame_studio/lib/src/core/game_controller.dart index e4710c24288..cfd00256384 100644 --- a/packages/flame_studio/lib/src/core/game_controller.dart +++ b/packages/flame_studio/lib/src/core/game_controller.dart @@ -8,12 +8,7 @@ final gameControllerProvider = ); @immutable -class _GameState { - const _GameState({this.game, this.paused = false}); - - final Game? game; - final bool paused; - +class const _GameState({final Game? game, final bool paused = false}) { _GameState copyWith({ Game? game, bool? paused, @@ -32,8 +27,8 @@ class _GameState { int get hashCode => Object.hash(game, paused); } -class _GameController extends StateNotifier<_GameState> { - _GameController() : super(const _GameState()) { +class _GameController() extends StateNotifier<_GameState> { + this : super(const _GameState()) { WidgetsFlutterBinding.ensureInitialized(); WidgetsBinding.instance.addPostFrameCallback((_) { final game = _findGame(); diff --git a/packages/flame_studio/lib/src/core/theme.dart b/packages/flame_studio/lib/src/core/theme.dart index 5a95b2c2b10..41aa11092fe 100644 --- a/packages/flame_studio/lib/src/core/theme.dart +++ b/packages/flame_studio/lib/src/core/theme.dart @@ -6,7 +6,7 @@ final textDirectionProvider = Provider((ref) => TextDirection.ltr); final themeProvider = Provider((ref) => Theme()); -class Theme { +class Theme() { final Color backdropColor = const Color(0xFF484848); final Color toolbarColor = const Color(0xFF303030); final Color panelColor = const Color(0xFF383838); diff --git a/packages/flame_studio/lib/src/widgets/flame_studio.dart b/packages/flame_studio/lib/src/widgets/flame_studio.dart index 49033c925cb..8a21a258059 100644 --- a/packages/flame_studio/lib/src/widgets/flame_studio.dart +++ b/packages/flame_studio/lib/src/widgets/flame_studio.dart @@ -2,11 +2,8 @@ import 'package:flame_studio/src/widgets/ui_scaffold.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class FlameStudio extends StatelessWidget { - const FlameStudio(this.child, {super.key}); - - final Widget child; - +class const FlameStudio(final Widget child, {super.key}) + extends StatelessWidget { @override Widget build(BuildContext context) { return ProviderScope( diff --git a/packages/flame_studio/lib/src/widgets/left_panel.dart b/packages/flame_studio/lib/src/widgets/left_panel.dart index 50293ebe35d..13220de228e 100644 --- a/packages/flame_studio/lib/src/widgets/left_panel.dart +++ b/packages/flame_studio/lib/src/widgets/left_panel.dart @@ -4,9 +4,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/legacy.dart'; -class LeftPanel extends ConsumerWidget { - const LeftPanel({super.key}); - +class const LeftPanel({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final width = ref.watch(leftPanelWidthProvider); @@ -34,8 +32,8 @@ class LeftPanel extends ConsumerWidget { } } -class _WidthNotifier extends StateNotifier { - _WidthNotifier() : super(250.0); +class _WidthNotifier() extends StateNotifier { + this : super(250.0); static const minWidth = 200.0; static const maxWidth = 500.0; diff --git a/packages/flame_studio/lib/src/widgets/left_panel_grip.dart b/packages/flame_studio/lib/src/widgets/left_panel_grip.dart index af59add18a3..86df4f176be 100644 --- a/packages/flame_studio/lib/src/widgets/left_panel_grip.dart +++ b/packages/flame_studio/lib/src/widgets/left_panel_grip.dart @@ -3,9 +3,7 @@ import 'package:flame_studio/src/widgets/left_panel.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class LeftPanelGrip extends ConsumerWidget { - const LeftPanelGrip({super.key}); - +class const LeftPanelGrip({super.key}) extends ConsumerWidget { /// Tracks the initial coordinates of a drag event. This can be static /// because we support only one drag at a time. static double _delta = 0; diff --git a/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart b/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart index 1acb161790d..0f4389e0ea3 100644 --- a/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart +++ b/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart @@ -3,14 +3,12 @@ import 'package:flame_studio/src/core/component_tree.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class HierarchyView extends ConsumerStatefulWidget { - const HierarchyView({super.key}); - +class const HierarchyView({super.key}) extends ConsumerStatefulWidget { @override HierarchyViewState createState() => HierarchyViewState(); } -class HierarchyViewState extends ConsumerState { +class HierarchyViewState() extends ConsumerState { Component? selectedComponent; Set expandedComponents = {}; @@ -67,14 +65,14 @@ class HierarchyViewState extends ConsumerState { } } -class _ListItem extends StatelessWidget { - _ListItem(this.state, this.node, this.indent, {required this.isFirst}) - : super(key: ObjectKey(node.component)); - - final HierarchyViewState state; - final ComponentTreeNode node; - final int indent; - final bool isFirst; +// ignore: prefer_const_constructors_in_immutables +class _ListItem( + final HierarchyViewState state, + final ComponentTreeNode node, + final int indent, { + required final bool isFirst, +}) extends StatelessWidget { + this : super(key: ObjectKey(node.component)); @override Widget build(BuildContext context) { @@ -135,10 +133,7 @@ class _ListItem extends StatelessWidget { } } -class _ClosingBrace extends StatelessWidget { - const _ClosingBrace(this.indent); - final int indent; - +class const _ClosingBrace(final int indent) extends StatelessWidget { @override Widget build(BuildContext context) { return Row( @@ -151,19 +146,12 @@ class _ClosingBrace extends StatelessWidget { } } -class _ExpanderIcon extends StatelessWidget { - const _ExpanderIcon({ - required this.hasChildren, - this.isExpanded = false, - this.isFirst = false, - this.isLast = false, - }); - - final bool hasChildren; - final bool isExpanded; - final bool isFirst; - final bool isLast; - +class const _ExpanderIcon({ + required final bool hasChildren, + final bool isExpanded = false, + final bool isFirst = false, + final bool isLast = false, +}) extends StatelessWidget { @override Widget build(BuildContext context) { return CustomPaint( @@ -173,10 +161,7 @@ class _ExpanderIcon extends StatelessWidget { } } -class _ExpanderIconPainter extends CustomPainter { - _ExpanderIconPainter(this.icon); - - final _ExpanderIcon icon; +class _ExpanderIconPainter(final _ExpanderIcon icon) extends CustomPainter { static final _paint = Paint() ..color = const Color(0xFFFFFFFF) ..style = PaintingStyle.stroke; diff --git a/packages/flame_studio/lib/src/widgets/toolbar/flame_studio_toolbar.dart b/packages/flame_studio/lib/src/widgets/toolbar/flame_studio_toolbar.dart index 9c52bb3b743..fee51d3ada8 100644 --- a/packages/flame_studio/lib/src/widgets/toolbar/flame_studio_toolbar.dart +++ b/packages/flame_studio/lib/src/widgets/toolbar/flame_studio_toolbar.dart @@ -7,9 +7,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; final toolbarHeightProvider = Provider((ref) => 28.0); -class FlameStudioToolbar extends ConsumerWidget { - const FlameStudioToolbar({super.key}); - +class const FlameStudioToolbar({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { const middleButtons = [ diff --git a/packages/flame_studio/lib/src/widgets/toolbar/next_frame_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/next_frame_button.dart index f86d6dff420..85e92f9cf1b 100644 --- a/packages/flame_studio/lib/src/widgets/toolbar/next_frame_button.dart +++ b/packages/flame_studio/lib/src/widgets/toolbar/next_frame_button.dart @@ -3,9 +3,7 @@ import 'package:flame_studio/src/widgets/toolbar/toolbar_button.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class NextFrameButton extends ConsumerWidget { - const NextFrameButton({super.key}); - +class const NextFrameButton({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final gameState = ref.watch(gameControllerProvider); diff --git a/packages/flame_studio/lib/src/widgets/toolbar/pause_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/pause_button.dart index 43bd65d2a57..0ba414409c5 100644 --- a/packages/flame_studio/lib/src/widgets/toolbar/pause_button.dart +++ b/packages/flame_studio/lib/src/widgets/toolbar/pause_button.dart @@ -3,9 +3,7 @@ import 'package:flame_studio/src/widgets/toolbar/toolbar_button.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class PauseButton extends ConsumerWidget { - const PauseButton({super.key}); - +class const PauseButton({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final gameState = ref.watch(gameControllerProvider); diff --git a/packages/flame_studio/lib/src/widgets/toolbar/start_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/start_button.dart index 62100ea7a39..38ccc14cb75 100644 --- a/packages/flame_studio/lib/src/widgets/toolbar/start_button.dart +++ b/packages/flame_studio/lib/src/widgets/toolbar/start_button.dart @@ -3,9 +3,7 @@ import 'package:flame_studio/src/widgets/toolbar/toolbar_button.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class StartButton extends ConsumerWidget { - const StartButton({super.key}); - +class const StartButton({super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final gameState = ref.watch(gameControllerProvider); diff --git a/packages/flame_studio/lib/src/widgets/toolbar/toolbar_button.dart b/packages/flame_studio/lib/src/widgets/toolbar/toolbar_button.dart index f6163eabd7e..29b232afcfb 100644 --- a/packages/flame_studio/lib/src/widgets/toolbar/toolbar_button.dart +++ b/packages/flame_studio/lib/src/widgets/toolbar/toolbar_button.dart @@ -2,23 +2,17 @@ import 'package:flame_studio/src/core/theme.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class ToolbarButton extends ConsumerStatefulWidget { - const ToolbarButton({ - required this.icon, - this.onClick, - this.disabled = false, - super.key, - }); - - final void Function()? onClick; - final Path icon; - final bool disabled; - +class const ToolbarButton({ + required final Path icon, + final void Function()? onClick, + final bool disabled = false, + super.key, +}) extends ConsumerStatefulWidget { @override ToolbarButtonState createState() => ToolbarButtonState(); } -class ToolbarButtonState extends ConsumerState { +class ToolbarButtonState() extends ConsumerState { bool _isHovered = false; bool _isActive = false; @@ -68,28 +62,20 @@ class ToolbarButtonState extends ConsumerState { } } -enum _ToolbarButtonRenderState { +enum _ToolbarButtonRenderState() { disabled, active, hovered, normal, } -class _ToolbarButtonPainter extends CustomPainter { - _ToolbarButtonPainter( - this.icon, - this.theme, { - required this.isDisabled, - required this.isHovered, - required this.isActive, - }); - - final bool isDisabled; - final bool isHovered; - final bool isActive; - final Path icon; - final Theme theme; - +class _ToolbarButtonPainter( + final Path icon, + final Theme theme, { + required final bool isDisabled, + required final bool isHovered, + required final bool isActive, +}) extends CustomPainter { @override void paint(Canvas canvas, Size size) { final scale = size.height / 20.0; diff --git a/packages/flame_studio/lib/src/widgets/ui_scaffold.dart b/packages/flame_studio/lib/src/widgets/ui_scaffold.dart index 745dc4bf126..2d15bf5dbb4 100644 --- a/packages/flame_studio/lib/src/widgets/ui_scaffold.dart +++ b/packages/flame_studio/lib/src/widgets/ui_scaffold.dart @@ -5,11 +5,8 @@ import 'package:flame_studio/src/widgets/toolbar/flame_studio_toolbar.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -class UiScaffold extends ConsumerWidget { - const UiScaffold({required this.gameApp, super.key}); - - final Widget gameApp; - +class const UiScaffold({required final Widget gameApp, super.key}) + extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final toolbarHeight = ref.watch(toolbarHeightProvider); diff --git a/packages/flame_studio/pubspec.yaml b/packages/flame_studio/pubspec.yaml index f4aaaf7cfdd..31e71c78f93 100644 --- a/packages/flame_studio/pubspec.yaml +++ b/packages/flame_studio/pubspec.yaml @@ -10,8 +10,8 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.17.1 diff --git a/packages/flame_svg/example/lib/main.dart b/packages/flame_svg/example/lib/main.dart index 0a46056b92e..f4ecf2b64d8 100644 --- a/packages/flame_svg/example/lib/main.dart +++ b/packages/flame_svg/example/lib/main.dart @@ -6,7 +6,7 @@ void main() { runApp(GameWidget(game: MyGame())); } -class MyGame extends FlameGame { +class MyGame() extends FlameGame { late Svg svgInstance; @override diff --git a/packages/flame_svg/example/pubspec.yaml b/packages/flame_svg/example/pubspec.yaml index 1ec1b217e0a..de6ded9694e 100644 --- a/packages/flame_svg/example/pubspec.yaml +++ b/packages/flame_svg/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_svg/lib/flame_svg.dart b/packages/flame_svg/lib/flame_svg.dart index 34b9fe4c1f5..75a75eb6c74 100644 --- a/packages/flame_svg/lib/flame_svg.dart +++ b/packages/flame_svg/lib/flame_svg.dart @@ -1,4 +1,2 @@ -library flame_svg; - -export './svg.dart'; -export './svg_component.dart'; +export 'svg.dart'; +export 'svg_component.dart'; diff --git a/packages/flame_svg/lib/svg.dart b/packages/flame_svg/lib/svg.dart index a919c83723d..a5d5df46dfc 100644 --- a/packages/flame_svg/lib/svg.dart +++ b/packages/flame_svg/lib/svg.dart @@ -9,7 +9,13 @@ import 'package:flutter/widgets.dart' show WidgetsBinding; import 'package:flutter_svg/flutter_svg.dart'; /// A [Svg] to be rendered on a Flame [Game]. -class Svg { +class Svg( + /// The [PictureInfo] that this [Svg] represents. + final PictureInfo pictureInfo, { + double? pixelRatio, + var bool _fixedRatio = false, + var int _cacheSize = defaultCacheSize, +}) { /// Creates an [Svg] with the received [pictureInfo]. /// Default [pixelRatio] is the device pixel ratio. /// Setting [fixedRatio] to `true` ensures the cache uses one entry @@ -17,32 +23,20 @@ class Svg { /// Default [cacheSize] is [defaultCacheSize], which is 10 as previously; /// specifying [unlimitedCacheSize] is the same as using a [Map] instead /// of a [MemoryCache]. - Svg( - this.pictureInfo, { - double? pixelRatio, - bool fixedRatio = false, - int cacheSize = defaultCacheSize, - }) : pixelRatio = - pixelRatio ?? - WidgetsBinding - .instance - .platformDispatcher - .views - .first - .devicePixelRatio { - _fixedRatio = fixedRatio; - _cacheSize = cacheSize; - assert(_cacheSize >= 1, 'The cache size must support at least one slot.'); + this + : assert( + _cacheSize >= 1, + 'The cache size must support at least one slot.', + ) { _imageCache = MemoryCache( cacheSize: _cacheSize >= 1 ? _cacheSize : defaultCacheSize, ); } - /// The [PictureInfo] that this [Svg] represents. - final PictureInfo pictureInfo; - /// The pixel ratio that this [Svg] is rendered based on. - final double pixelRatio; + final double pixelRatio = + pixelRatio ?? + WidgetsBinding.instance.platformDispatcher.views.first.devicePixelRatio; /// Whether we're using a fixed ratio for the cache keys (default: false). bool get fixedRatio => _fixedRatio; @@ -51,8 +45,6 @@ class Svg { _fixedRatio = fixed; } - late bool _fixedRatio; - /// The current cache size (default 10): changing the size also empties it. int get cacheSize => _cacheSize; set cacheSize(int size) { @@ -64,8 +56,6 @@ class Svg { } } - late int _cacheSize; - /// The number of images currently used by the cache. int get cacheUsage => _imageCache.size; @@ -85,7 +75,7 @@ class Svg { }) async { cache ??= Flame.assets; final svgString = await cache.readFile(fileName, package: package); - return Svg.loadFromString( + return await Svg.loadFromString( svgString, pixelRatio: pixelRatio, fixedRatio: fixedRatio, diff --git a/packages/flame_svg/lib/svg_component.dart b/packages/flame_svg/lib/svg_component.dart index f9fa645e147..29b38ebe7b7 100644 --- a/packages/flame_svg/lib/svg_component.dart +++ b/packages/flame_svg/lib/svg_component.dart @@ -4,26 +4,24 @@ import 'package:flame/components.dart'; import 'package:flame_svg/svg.dart'; /// Wraps [Svg] in a Flame component. -class SvgComponent extends PositionComponent with HasPaint { +class SvgComponent({ + /// The wrapped instance of [Svg]. + var Svg? _svg, + super.position, + super.size, + super.scale, + super.angle, + super.anchor, + super.children, + super.priority, + Paint? paint, + super.key, +}) extends PositionComponent with HasPaint { /// Creates an [SvgComponent] - SvgComponent({ - this._svg, - super.position, - super.size, - super.scale, - super.angle, - super.anchor, - super.children, - super.priority, - Paint? paint, - super.key, - }) { + this { this.paint = paint ?? (this.paint..filterQuality = FilterQuality.medium); } - /// The wrapped instance of [Svg]. - Svg? _svg; - set svg(Svg? svg) { _svg?.dispose(); _svg = svg; diff --git a/packages/flame_svg/pubspec.yaml b/packages/flame_svg/pubspec.yaml index 756ff34eb3c..c39940f2625 100644 --- a/packages/flame_svg/pubspec.yaml +++ b/packages/flame_svg/pubspec.yaml @@ -13,8 +13,8 @@ topics: - vector-graphics environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_svg/test/svg_component_test.dart b/packages/flame_svg/test/svg_component_test.dart index 66b9dfc07b9..6a8fff3f8df 100644 --- a/packages/flame_svg/test/svg_component_test.dart +++ b/packages/flame_svg/test/svg_component_test.dart @@ -2,7 +2,7 @@ import 'package:flame_svg/flame_svg.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; -class _MockSvg extends Mock implements Svg {} +class _MockSvg() extends Mock implements Svg; void main() { group('SvgComponent', () { diff --git a/packages/flame_svg/test/svg_test.dart b/packages/flame_svg/test/svg_test.dart index 7c0d6417da9..af88b51a175 100644 --- a/packages/flame_svg/test/svg_test.dart +++ b/packages/flame_svg/test/svg_test.dart @@ -7,11 +7,7 @@ import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; -class _SvgPainter extends CustomPainter { - final flame_svg.Svg svg; - - _SvgPainter(this.svg); - +class _SvgPainter(final flame_svg.Svg svg) extends CustomPainter { @override void paint(Canvas canvas, Size size) { svg.render(canvas, Vector2(size.width, size.height)); diff --git a/packages/flame_test/example/lib/game.dart b/packages/flame_test/example/lib/game.dart index 3df4d592129..ac05f9f6a3f 100644 --- a/packages/flame_test/example/lib/game.dart +++ b/packages/flame_test/example/lib/game.dart @@ -2,16 +2,14 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:material_ui/material_ui.dart'; -class MyGameWidget extends StatelessWidget { - const MyGameWidget({super.key}); - +class const MyGameWidget({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return GameWidget(game: MyGame()); } } -class Background extends SpriteComponent with HasGameRef { +class Background() extends SpriteComponent with HasGameRef { @override Future onLoad() async { sprite = await gameRef.loadSprite('assets/images/city.png'); @@ -20,7 +18,7 @@ class Background extends SpriteComponent with HasGameRef { } } -class MyGame extends FlameGame { +class MyGame() extends FlameGame { @override Future onLoad() async { final background = Background(); diff --git a/packages/flame_test/example/lib/main.dart b/packages/flame_test/example/lib/main.dart index 1260c7e5f95..507db015f7e 100644 --- a/packages/flame_test/example/lib/main.dart +++ b/packages/flame_test/example/lib/main.dart @@ -2,13 +2,13 @@ import 'package:flame/extensions.dart'; void main() {} -class MyVectorChanger { +class MyVectorChanger() { Vector2 addOne(Vector2 vector) { return vector + Vector2.all(1.0); } } -class MyDoubleChanger { +class MyDoubleChanger() { double addOne(double number) { return number + 1.0; } diff --git a/packages/flame_test/example/pubspec.yaml b/packages/flame_test/example/pubspec.yaml index cb938ced236..8abe27ccdda 100644 --- a/packages/flame_test/example/pubspec.yaml +++ b/packages/flame_test/example/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_test/lib/src/close_to_aabb.dart b/packages/flame_test/lib/src/close_to_aabb.dart index 92712a54fcb..9861a957569 100644 --- a/packages/flame_test/lib/src/close_to_aabb.dart +++ b/packages/flame_test/lib/src/close_to_aabb.dart @@ -14,12 +14,8 @@ Matcher closeToAabb(Aabb2 expected, [double epsilon = 1e-15]) { return _IsCloseToAabb(expected, epsilon); } -class _IsCloseToAabb extends Matcher { - const _IsCloseToAabb(this._expected, this._epsilon); - - final Aabb2 _expected; - final double _epsilon; - +class const _IsCloseToAabb(final Aabb2 _expected, final double _epsilon) + extends Matcher { @override bool matches(dynamic item, Map matchState) { return (item is Aabb2) && diff --git a/packages/flame_test/lib/src/close_to_matrix4.dart b/packages/flame_test/lib/src/close_to_matrix4.dart index cfdc9a142c6..33c941e8bd7 100644 --- a/packages/flame_test/lib/src/close_to_matrix4.dart +++ b/packages/flame_test/lib/src/close_to_matrix4.dart @@ -23,12 +23,8 @@ Matcher closeToMatrix4(Matrix4 matrix, [double epsilon = 1e-15]) { return _IsCloseTo(matrix, epsilon); } -class _IsCloseTo extends Matcher { - const _IsCloseTo(this._value, this._epsilon); - - final Matrix4 _value; - final double _epsilon; - +class const _IsCloseTo(final Matrix4 _value, final double _epsilon) + extends Matcher { @override bool matches(dynamic item, Map matchState) { if (item is! Matrix4) { diff --git a/packages/flame_test/lib/src/close_to_quaternion.dart b/packages/flame_test/lib/src/close_to_quaternion.dart index 90b42f5d0f8..9092be451c0 100644 --- a/packages/flame_test/lib/src/close_to_quaternion.dart +++ b/packages/flame_test/lib/src/close_to_quaternion.dart @@ -15,9 +15,8 @@ Matcher closeToQuaternion(Quaternion quaternion, [double epsilon = 1e-15]) { return _IsCloseToQuaternion(quaternion, epsilon); } -class _IsCloseToQuaternion extends IsCloseToVector { - const _IsCloseToQuaternion(super.value, super.epsilon); - +class const _IsCloseToQuaternion(super.value, super.epsilon) + extends IsCloseToVector { @override double dist(Quaternion a, Quaternion b) => (a - b).length; diff --git a/packages/flame_test/lib/src/close_to_vector.dart b/packages/flame_test/lib/src/close_to_vector.dart index e177e17c8f2..51bc7bd159a 100644 --- a/packages/flame_test/lib/src/close_to_vector.dart +++ b/packages/flame_test/lib/src/close_to_vector.dart @@ -13,9 +13,8 @@ Matcher closeToVector(Vector2 vector, [double epsilon = 1e-15]) { return _IsCloseToVector2(vector, epsilon); } -class _IsCloseToVector2 extends IsCloseToVector { - const _IsCloseToVector2(super.value, super.epsilon); - +class const _IsCloseToVector2(super.value, super.epsilon) + extends IsCloseToVector { @override double dist(Vector2 a, Vector2 b) => (a - b).length; diff --git a/packages/flame_test/lib/src/close_to_vector3.dart b/packages/flame_test/lib/src/close_to_vector3.dart index 9f4c5f2e332..996176b89cd 100644 --- a/packages/flame_test/lib/src/close_to_vector3.dart +++ b/packages/flame_test/lib/src/close_to_vector3.dart @@ -13,9 +13,8 @@ Matcher closeToVector3(Vector3 vector, [double epsilon = 1e-15]) { return _IsCloseToVector3(vector, epsilon); } -class _IsCloseToVector3 extends IsCloseToVector { - const _IsCloseToVector3(super.value, super.epsilon); - +class const _IsCloseToVector3(super.value, super.epsilon) + extends IsCloseToVector { @override double dist(Vector3 a, Vector3 b) => (a - b).length; diff --git a/packages/flame_test/lib/src/close_to_vector4.dart b/packages/flame_test/lib/src/close_to_vector4.dart index 98fe2d10572..291a63342b5 100644 --- a/packages/flame_test/lib/src/close_to_vector4.dart +++ b/packages/flame_test/lib/src/close_to_vector4.dart @@ -13,9 +13,8 @@ Matcher closeToVector4(Vector4 vector, [double epsilon = 1e-15]) { return _IsCloseToVector4(vector, epsilon); } -class _IsCloseToVector4 extends IsCloseToVector { - const _IsCloseToVector4(super.value, super.epsilon); - +class const _IsCloseToVector4(super.value, super.epsilon) + extends IsCloseToVector { @override double dist(Vector4 a, Vector4 b) => (a - b).length; diff --git a/packages/flame_test/lib/src/debug_text_renderer.dart b/packages/flame_test/lib/src/debug_text_renderer.dart index c04f4aa9c54..c35d3861109 100644 --- a/packages/flame_test/lib/src/debug_text_renderer.dart +++ b/packages/flame_test/lib/src/debug_text_renderer.dart @@ -8,21 +8,13 @@ import 'package:flame/text.dart'; /// Rendering regular text in golden tests is unreliable due to differences in /// font definitions across platforms and different algorithms used for anti- /// aliasing. -class DebugTextRenderer extends TextRenderer { - DebugTextRenderer({ - this.color = const Color(0xFFFFFFFF), - this.fontSize = 16.0, - this.lineHeight = 1.2, - this.fontWeight = FontWeight.normal, - this.fontStyle = FontStyle.normal, - }); - - final Color color; - final double fontSize; - final double lineHeight; - final FontWeight fontWeight; - final FontStyle fontStyle; - +class DebugTextRenderer({ + final Color color = const Color(0xFFFFFFFF), + final double fontSize = 16.0, + final double lineHeight = 1.2, + final FontWeight fontWeight = FontWeight.normal, + final FontStyle fontStyle = FontStyle.normal, +}) extends TextRenderer { @override InlineTextElement format(String text) => _DebugTextElement(this, text); @@ -38,8 +30,9 @@ class DebugTextRenderer extends TextRenderer { } } -class _DebugTextElement extends InlineTextElement { - _DebugTextElement(this.style, this.text) { +class _DebugTextElement(final DebugTextRenderer style, final String text) + extends InlineTextElement { + this { final charWidth = style.fontSize * 1.0; final charHeight = style.fontSize; paint @@ -56,8 +49,6 @@ class _DebugTextElement extends InlineTextElement { _initRects(charWidth, charHeight); } - final DebugTextRenderer style; - final String text; final List rects = []; final Paint paint = Paint(); @override diff --git a/packages/flame_test/lib/src/expect_color.dart b/packages/flame_test/lib/src/expect_color.dart index b25b4aaebf8..ffb3771f397 100644 --- a/packages/flame_test/lib/src/expect_color.dart +++ b/packages/flame_test/lib/src/expect_color.dart @@ -1,4 +1,5 @@ import 'dart:ui' show Color; + import 'package:test/test.dart'; /// A test helper function that compares two [Color] objects for equality with diff --git a/packages/flame_test/lib/src/flame_test.dart b/packages/flame_test/lib/src/flame_test.dart index 7d2ee64e3a2..5c36639e65f 100644 --- a/packages/flame_test/lib/src/flame_test.dart +++ b/packages/flame_test/lib/src/flame_test.dart @@ -60,60 +60,49 @@ extension FlameGameExtension on Component { typedef GameCreateFunction = T Function(); typedef VerifyFunction = dynamic Function(T); -typedef GameWidgetCreateFunction = - GameWidget Function( - T game, - ); -typedef WidgetVerifyFunction = - Future Function( - T, - WidgetTester, - ); -typedef WidgetSetupFunction = - Future Function( - T, - WidgetTester, - ); -typedef PumpWidgetFunction = - Future Function( - GameWidget, - WidgetTester tester, - ); +typedef GameWidgetCreateFunction = GameWidget Function( + T game, +); +typedef WidgetVerifyFunction = Future Function( + T, + WidgetTester, +); +typedef WidgetSetupFunction = Future Function( + T, + WidgetTester, +); +typedef PumpWidgetFunction = Future Function( + GameWidget, + WidgetTester tester, +); /// Customize this class with your specific Game type [T] and a custom /// provider `() -> T`, plus some additional configurations including a game /// widget builder [createGameWidget], a custom [pumpWidget] function and a /// custom [gameSize]. -class GameTester { +class GameTester( /// Use [createGame] to create your game instance. - final GameCreateFunction createGame; + final GameCreateFunction createGame, { + + /// Override the game size to be provided during `onGameResize`. + /// By default it will be a 500x500 square. + final Vector2? gameSize, /// Use [createGameWidget] to create the [GameWidget]. If omitted, /// the game instance returned by [createGame] will be wrapped into /// an empty [GameWidget] instance. - final GameWidgetCreateFunction? createGameWidget; + final GameWidgetCreateFunction? createGameWidget, /// Use [pumpWidget] to define your own function to pump widgets into /// the Flutter test environment. When omitted, [testGameWidget] simply /// will pass the created game widget instance to the test. - final PumpWidgetFunction? pumpWidget; - - /// Override the game size to be provided during `onGameResize`. - /// By default it will be a 500x500 square. - final Vector2? gameSize; - + final PumpWidgetFunction? pumpWidget, +}) { /// If true, the game will be brought into the "fully ready" state (meaning /// all its pending lifecycle events will be resolved) before the start of /// the test. bool makeReady = true; - GameTester( - this.createGame, { - this.gameSize, - this.createGameWidget, - this.pumpWidget, - }); - /// Creates a [Game] specific test case with given [description] /// which runs inside the Flutter test environment. /// @@ -183,14 +172,12 @@ class GameTester { /// provider `() -> T`, plus some additional configurations including a game /// widget builder [createGameWidget], a custom [pumpWidget] function and a /// custom [gameSize]. -class FlameTester extends GameTester { - FlameTester( - super.createGame, { - super.gameSize, - super.createGameWidget, - super.pumpWidget, - }); -} +class FlameTester( + super.createGame, { + super.gameSize, + super.createGameWidget, + super.pumpWidget, +}) extends GameTester; /// Default instance of Flame Tester to be used when you don't care about /// changing any configuration. diff --git a/packages/flame_test/lib/src/is_close_to_vector.dart b/packages/flame_test/lib/src/is_close_to_vector.dart index a3f953ea470..1769ed62f96 100644 --- a/packages/flame_test/lib/src/is_close_to_vector.dart +++ b/packages/flame_test/lib/src/is_close_to_vector.dart @@ -1,11 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; -abstract class IsCloseToVector extends Matcher { - const IsCloseToVector(this._value, this._epsilon); - - final V _value; - final double _epsilon; - +abstract class const IsCloseToVector(final V _value, final double _epsilon) + extends Matcher { double dist(V a, V b); List storage(V value); diff --git a/packages/flame_test/lib/src/random_test.dart b/packages/flame_test/lib/src/random_test.dart index 11a028a6239..7e2831e149c 100644 --- a/packages/flame_test/lib/src/random_test.dart +++ b/packages/flame_test/lib/src/random_test.dart @@ -87,11 +87,10 @@ void testRandom( } } -typedef TestWidgetsCallback = - Future Function( - Random random, - WidgetTester widgetTester, - ); +typedef TestWidgetsCallback = Future Function( + Random random, + WidgetTester widgetTester, +); /// This function is equivalent to `testWidgets(name, body)`, except that /// it is better suited for randomized testing: it will create a Random diff --git a/packages/flame_test/lib/src/test_golden.dart b/packages/flame_test/lib/src/test_golden.dart index 4843bc53dcb..0db8df28d92 100644 --- a/packages/flame_test/lib/src/test_golden.dart +++ b/packages/flame_test/lib/src/test_golden.dart @@ -14,7 +14,7 @@ import 'package:meta/meta.dart'; /// captured at the creation of the test. In order to create a golden file, you /// first specify its desired name in the [goldenFile] parameter, and then run /// the tests using the command -/// ``` +/// ```sh /// flutter test --update-goldens /// ``` /// @@ -77,17 +77,12 @@ void testGolden( ); } -typedef PrepareFunction = - Future Function( - FlameGame game, - WidgetTester tester, - ); - -class GameWithBackgroundColor extends FlameGame { - final Color _backgroundColor; - - GameWithBackgroundColor(this._backgroundColor); +typedef PrepareFunction = Future Function( + FlameGame game, + WidgetTester tester, +); +class GameWithBackgroundColor(final Color _backgroundColor) extends FlameGame { @override Color backgroundColor() => _backgroundColor; } diff --git a/packages/flame_test/lib/src/test_paths.dart b/packages/flame_test/lib/src/test_paths.dart index 1957d1af671..8d1c19cbfd7 100644 --- a/packages/flame_test/lib/src/test_paths.dart +++ b/packages/flame_test/lib/src/test_paths.dart @@ -10,7 +10,7 @@ import 'package:flame/extensions.dart'; /// in size and position. [byIndex] and [byName] return them fitted into a /// given size, with their aspect ratio kept, and centered on the origin. Only /// [roundRect] takes its size directly, so it is never scaled by them. -abstract final class TestPaths { +abstract final class TestPaths() { static final _paths = <(String, Path Function(Size))>[ ('roundRect', roundRect), ('flame', (_) => flame()), diff --git a/packages/flame_test/pubspec.yaml b/packages/flame_test/pubspec.yaml index a163963113a..7448b04bd8c 100644 --- a/packages/flame_test/pubspec.yaml +++ b/packages/flame_test/pubspec.yaml @@ -13,8 +13,8 @@ topics: - testing environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_test/test/debug_text_formatter_test.dart b/packages/flame_test/test/debug_text_formatter_test.dart index a8c62fb1256..2f98646c75c 100644 --- a/packages/flame_test/test/debug_text_formatter_test.dart +++ b/packages/flame_test/test/debug_text_formatter_test.dart @@ -41,11 +41,8 @@ void main() { }); } -class _TextElementsComponent extends PositionComponent { - _TextElementsComponent(this.elements); - - final List elements; - +class _TextElementsComponent(final List elements) + extends PositionComponent { @override void render(Canvas canvas) { for (final element in elements) { diff --git a/packages/flame_test/test/ensure_add_test.dart b/packages/flame_test/test/ensure_add_test.dart index e29f228b9a6..086da7bb334 100644 --- a/packages/flame_test/test/ensure_add_test.dart +++ b/packages/flame_test/test/ensure_add_test.dart @@ -40,11 +40,9 @@ void main() { }); } -class _LoadException implements Exception { - const _LoadException(); -} +class const _LoadException() implements Exception; -class _FailingLoadComponent extends Component { +class _FailingLoadComponent() extends Component { @override Future onLoad() async { await Future.delayed(const Duration(milliseconds: 10)); diff --git a/packages/flame_test/test/fails_assert_test.dart b/packages/flame_test/test/fails_assert_test.dart index 65a10d64e40..9054024dada 100644 --- a/packages/flame_test/test/fails_assert_test.dart +++ b/packages/flame_test/test/fails_assert_test.dart @@ -6,7 +6,6 @@ void main() { test('without message', () { expect( () { - // ignore: prefer_asserts_with_message assert(2 + 2 == 5); }, failsAssert(), diff --git a/packages/flame_test/test/test_with_game_test.dart b/packages/flame_test/test/test_with_game_test.dart index de32276716a..06e390c87cc 100644 --- a/packages/flame_test/test/test_with_game_test.dart +++ b/packages/flame_test/test/test_with_game_test.dart @@ -44,7 +44,7 @@ void main() { }); } -class _RecordedGame extends FlameGame { +class _RecordedGame() extends FlameGame { final List events = []; @override diff --git a/packages/flame_texturepacker/example/lib/main.dart b/packages/flame_texturepacker/example/lib/main.dart index afde3ea9e5b..f24ca860911 100644 --- a/packages/flame_texturepacker/example/lib/main.dart +++ b/packages/flame_texturepacker/example/lib/main.dart @@ -12,7 +12,7 @@ void main() { ); } -class MyGame extends FlameGame { +class MyGame() extends FlameGame { @override Future onLoad() async { super.onLoad(); diff --git a/packages/flame_texturepacker/example/pubspec.yaml b/packages/flame_texturepacker/example/pubspec.yaml index 7e867cc1707..8b45460d042 100644 --- a/packages/flame_texturepacker/example/pubspec.yaml +++ b/packages/flame_texturepacker/example/pubspec.yaml @@ -5,8 +5,8 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_texturepacker/lib/flame_texturepacker.dart b/packages/flame_texturepacker/lib/flame_texturepacker.dart index ba7bc284a5a..d06b32b730b 100644 --- a/packages/flame_texturepacker/lib/flame_texturepacker.dart +++ b/packages/flame_texturepacker/lib/flame_texturepacker.dart @@ -1,5 +1,3 @@ -library flame_texturepacker; - export 'package:flame_texturepacker/src/extension_on_game.dart'; export 'package:flame_texturepacker/src/texture_packer_atlas.dart'; export 'package:flame_texturepacker/src/texture_packer_parser.dart'; diff --git a/packages/flame_texturepacker/lib/src/model/page.dart b/packages/flame_texturepacker/lib/src/model/page.dart index 97d851c3463..8e8053a5db3 100644 --- a/packages/flame_texturepacker/lib/src/model/page.dart +++ b/packages/flame_texturepacker/lib/src/model/page.dart @@ -1,6 +1,6 @@ import 'dart:ui'; -class Page { +class Page() { late String textureFile; Image? texture; late int width; diff --git a/packages/flame_texturepacker/lib/src/model/region.dart b/packages/flame_texturepacker/lib/src/model/region.dart index a589444ea15..0da19f4df3b 100644 --- a/packages/flame_texturepacker/lib/src/model/region.dart +++ b/packages/flame_texturepacker/lib/src/model/region.dart @@ -3,74 +3,58 @@ import 'package:flutter/foundation.dart'; /// Represents a region within the texture packer atlas. @immutable -final class Region { +final class const Region({ /// The page in the texture pack this region belongs to. - final Page page; + required final Page page, /// The name of the original image file, without the file's extension. /// If the name ends with an underscore followed by only numbers, that part is /// excluded: underscores denote special instructions to the texture packer. - final String name; + required final String name, /// The left position of the region in the texture atlas. - final double left; + final double left = 0, /// The top position of the region in the texture atlas. - final double top; + final double top = 0, /// The width of the image, after whitespace was removed for packing. - final double width; + final double width = 0, /// The height of the image, after whitespace was removed for packing. - final double height; + final double height = 0, /// The offset from the left of the original image to the left of the packed /// image, after whitespace was removed for packing. - final double offsetX; + final double offsetX = 0, /// The offset from the bottom of the original image to the bottom of the /// packed image, after whitespace was removed for packing. - final double offsetY; - - /// The width of the image, before whitespace was removed and rotation was - /// applied for packing. - final double originalWidth; - - /// The height of the image, before whitespace was removed for packing. - final double originalHeight; + final double offsetY = 0, + double? originalWidth, + double? originalHeight, /// The degrees the region has been rotated, counter clockwise between 0 and /// 359. Most atlas region handling deals only with 0 or 90 degree rotation /// (enough to handle rectangles). /// More advanced texture packing may support other rotations (eg, for tightly /// packing polygons). - final int degrees; + final int degrees = 0, /// If true, the region has been rotated 90 degrees counter clockwise. - final bool rotate; + final bool rotate = false, /// The number at the end of the original image file name, or -1 if none. /// /// When sprites are packed, if the original file name ends with a number, it /// is stored as the index and is not considered as part of the sprite's name. /// This is useful for keeping animation frames in order. - final int index; + final int index = -1, +}) { + /// The width of the image, before whitespace was removed and rotation was + /// applied for packing. + final double originalWidth = originalWidth ?? width; - /// Creates a new [Region] with the given properties. - const Region({ - required this.page, - required this.name, - this.left = 0, - this.top = 0, - this.width = 0, - this.height = 0, - this.offsetX = 0, - this.offsetY = 0, - double? originalWidth, - double? originalHeight, - this.degrees = 0, - this.rotate = false, - this.index = -1, - }) : originalWidth = originalWidth ?? width, - originalHeight = originalHeight ?? height; + /// The height of the image, before whitespace was removed for packing. + final double originalHeight = originalHeight ?? height; } diff --git a/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart b/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart index 2eb678de3dd..c388703dad0 100644 --- a/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart +++ b/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart @@ -1,5 +1,3 @@ -library flame_texturepacker; - import 'package:collection/collection.dart'; import 'package:flame/cache.dart'; import 'package:flame/components.dart'; @@ -11,13 +9,10 @@ import 'package:flame_texturepacker/src/texture_packer_sprite.dart'; /// /// This class provides methods to load and query sprites from a texture atlas /// created by TexturePacker or similar tools. -class TexturePackerAtlas { +class TexturePackerAtlas( /// List of all sprites contained in this atlas. - final List sprites; - - /// Creates a new [TexturePackerAtlas] with the given [sprites]. - TexturePackerAtlas(this.sprites); - + final List sprites, +) { /// Creates a [TexturePackerAtlas] from parsed atlas data. /// /// [atlasData] - The parsed atlas data containing pages and regions diff --git a/packages/flame_texturepacker/lib/src/texture_packer_parser.dart b/packages/flame_texturepacker/lib/src/texture_packer_parser.dart index 4d074ead9d6..cdfc5add24a 100644 --- a/packages/flame_texturepacker/lib/src/texture_packer_parser.dart +++ b/packages/flame_texturepacker/lib/src/texture_packer_parser.dart @@ -12,7 +12,7 @@ import 'package:flutter/painting.dart'; typedef TextureAtlasData = ({List pages, List regions}); /// Internal parser for TexturePacker atlas files. -abstract class TexturePackerParser { +abstract class TexturePackerParser() { /// Parses structural data of a texture atlas file. /// /// The [path] is the full path of the atlas, as declared in the diff --git a/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart b/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart index 5e4c1bda5de..71ea685eb41 100644 --- a/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart +++ b/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart @@ -9,9 +9,16 @@ import 'package:flame_texturepacker/src/model/region.dart'; /// {@template _texture_packer_sprite} /// A [Sprite] extracted from a texture packer file. /// {@endtemplate} -class TexturePackerSprite extends Sprite { +class TexturePackerSprite( + /// Region object for [clone] function, don't modify this object properties. + final Region region, { + + /// If true, use [Region.originalWidth] and [Region.originalHeight] as size; + /// otherwise use [Region.width] and [Region.height] as size. + final bool useOriginalSize = true, +}) extends Sprite { /// {@macro _texture_packer_sprite} - TexturePackerSprite(this.region, {this.useOriginalSize = true}) + this : super( region.page.texture ?? _emptyImage, srcPosition: Vector2(region.left, region.top), @@ -28,13 +35,6 @@ class TexturePackerSprite extends Sprite { } } - /// Region object for [clone] function, don't modify this object properties. - final Region region; - - /// If true, use [Region.originalWidth] and [Region.originalHeight] as size; - /// otherwise use [Region.width] and [Region.height] as size. - final bool useOriginalSize; - /// The [Region.degrees] field (angle) represented as radians. double get angle => radians(region.degrees.toDouble()); diff --git a/packages/flame_texturepacker/pubspec.yaml b/packages/flame_texturepacker/pubspec.yaml index 22e4f3f4c35..cb22e6e9f7e 100644 --- a/packages/flame_texturepacker/pubspec.yaml +++ b/packages/flame_texturepacker/pubspec.yaml @@ -12,8 +12,8 @@ topics: - spritesheet environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.17.1 diff --git a/packages/flame_texturepacker/test/atlas_path_resolution_test.dart b/packages/flame_texturepacker/test/atlas_path_resolution_test.dart index 619823968ab..53358b32aa8 100644 --- a/packages/flame_texturepacker/test/atlas_path_resolution_test.dart +++ b/packages/flame_texturepacker/test/atlas_path_resolution_test.dart @@ -1,15 +1,16 @@ import 'dart:ui' as ui; + import 'package:flame/cache.dart'; import 'package:flame_texturepacker/flame_texturepacker.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockAssetBundle extends Mock implements AssetBundle {} +class _MockAssetBundle() extends Mock implements AssetBundle; -class _MockImages extends Mock implements Images {} +class _MockImages() extends Mock implements Images; -class FakeImage extends Mock implements ui.Image {} +class FakeImage() extends Mock implements ui.Image; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame_texturepacker/test/flame_texturepacker_test.dart b/packages/flame_texturepacker/test/flame_texturepacker_test.dart index 83c3ccc34b8..3fc1bddb3e5 100644 --- a/packages/flame_texturepacker/test/flame_texturepacker_test.dart +++ b/packages/flame_texturepacker/test/flame_texturepacker_test.dart @@ -7,7 +7,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockAssetBundle extends Mock implements AssetBundle {} +class _MockAssetBundle() extends Mock implements AssetBundle; void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -36,7 +36,7 @@ void main() { final bundle = _MockAssetBundle(); when( () => bundle.loadString(any()), - ).thenAnswer((_) async => File(atlasPath).readAsString()); + ).thenAnswer((_) async => await File(atlasPath).readAsString()); when(() => bundle.load(any())).thenAnswer( (_) async => ByteData.sublistView( File(atlasImage1).readAsBytesSync(), diff --git a/packages/flame_texturepacker/test/legacy_format_test.dart b/packages/flame_texturepacker/test/legacy_format_test.dart index f7b32ef2168..7efaf17802a 100644 --- a/packages/flame_texturepacker/test/legacy_format_test.dart +++ b/packages/flame_texturepacker/test/legacy_format_test.dart @@ -6,7 +6,7 @@ import 'package:flame_texturepacker/flame_texturepacker.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockCanvas extends Mock implements Canvas {} +class _MockCanvas() extends Mock implements Canvas; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame_texturepacker/test/new_format_test.dart b/packages/flame_texturepacker/test/new_format_test.dart index 2066010c52f..32e3034cd71 100644 --- a/packages/flame_texturepacker/test/new_format_test.dart +++ b/packages/flame_texturepacker/test/new_format_test.dart @@ -6,7 +6,7 @@ import 'package:flame_texturepacker/flame_texturepacker.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -class _MockCanvas extends Mock implements Canvas {} +class _MockCanvas() extends Mock implements Canvas; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/flame_texturepacker/test/separated_parsing_test.dart b/packages/flame_texturepacker/test/separated_parsing_test.dart index ae404d6b635..987036e70a2 100644 --- a/packages/flame_texturepacker/test/separated_parsing_test.dart +++ b/packages/flame_texturepacker/test/separated_parsing_test.dart @@ -1,4 +1,5 @@ import 'dart:io'; + import 'package:flame_texturepacker/flame_texturepacker.dart'; import 'package:flutter_test/flutter_test.dart'; diff --git a/packages/flame_tiled/example/lib/main.dart b/packages/flame_tiled/example/lib/main.dart index 2239bfa645b..bf1535abf80 100644 --- a/packages/flame_tiled/example/lib/main.dart +++ b/packages/flame_tiled/example/lib/main.dart @@ -13,7 +13,7 @@ void main() { /// Scrolls the layer that it is added to, which makes the repeating snow /// image layer of the example map fall. -class SnowScroller extends Component with ParentIsA { +class SnowScroller() extends Component with ParentIsA { double _elapsed = 0; @override @@ -25,10 +25,10 @@ class SnowScroller extends Component with ParentIsA { } } -class TiledGame extends FlameGame { +class TiledGame() extends FlameGame { late TiledComponent mapComponent; - TiledGame() + this : super( camera: CameraComponent.withFixedResolution( width: 16 * 28, diff --git a/packages/flame_tiled/example/pubspec.yaml b/packages/flame_tiled/example/pubspec.yaml index 10ddc3fbf9b..03508241223 100644 --- a/packages/flame_tiled/example/pubspec.yaml +++ b/packages/flame_tiled/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_tiled/lib/flame_tiled.dart b/packages/flame_tiled/lib/flame_tiled.dart index c8cbe1bddc6..bdbaafac94e 100644 --- a/packages/flame_tiled/lib/flame_tiled.dart +++ b/packages/flame_tiled/lib/flame_tiled.dart @@ -1,5 +1,3 @@ -library flame_tiled; - export 'package:tiled/tiled.dart'; export 'src/extensions.dart'; diff --git a/packages/flame_tiled/lib/src/flame_tsx_provider.dart b/packages/flame_tiled/lib/src/flame_tsx_provider.dart index 012b3bb631f..a2b4fffb36f 100644 --- a/packages/flame_tiled/lib/src/flame_tsx_provider.dart +++ b/packages/flame_tiled/lib/src/flame_tsx_provider.dart @@ -8,15 +8,13 @@ import 'package:tiled/tiled.dart'; /// `RenderableTiledMap` resolves external tilesets on its own, this is only /// needed when parsing a map manually, for example through /// [TiledMap.parseTmx]. -class FlameTsxProvider implements ParserProvider { +class FlameTsxProvider._( /// Parsed data for this tsx file. - final String data; + final String data, /// Stored filename for corresponding tsx file. - final String filename; - - FlameTsxProvider._(this.data, this.filename); - + final String filename, +) implements ParserProvider { @override bool canProvide(String path) => path == filename; diff --git a/packages/flame_tiled/lib/src/mutable_rect.dart b/packages/flame_tiled/lib/src/mutable_rect.dart index 3fa92f25305..4c38a9cd8cb 100644 --- a/packages/flame_tiled/lib/src/mutable_rect.dart +++ b/packages/flame_tiled/lib/src/mutable_rect.dart @@ -1,10 +1,10 @@ import 'dart:ui' show Rect; /// A mutable version of [Rect] for tile map animations. -class MutableRect extends Rect { +class MutableRect.fromLTRB(this.left, this.top, this.right, this.bottom) + extends Rect { /// Construct a rectangle from its left, top, right, and bottom edges. - MutableRect.fromLTRB(this.left, this.top, this.right, this.bottom) - : super.fromLTRB(left, top, right, bottom); + this : super.fromLTRB(left, top, right, bottom); /// Create a new instance from [other]. factory MutableRect.fromRect(Rect other) => diff --git a/packages/flame_tiled/lib/src/rectangle_bin_packer.dart b/packages/flame_tiled/lib/src/rectangle_bin_packer.dart index 268ac7b5cf3..82b5e2eb64f 100644 --- a/packages/flame_tiled/lib/src/rectangle_bin_packer.dart +++ b/packages/flame_tiled/lib/src/rectangle_bin_packer.dart @@ -9,15 +9,10 @@ import 'dart:ui'; /// Light reading: /// * https://en.wikipedia.org/wiki/Rectangle_packing#Packing_different_rectangles_in_a_minimum-area_rectangle /// * https://www.david-colson.com/2020/03/10/exploring-rect-packing.html -class RectangleBinPacker { - final double maxX; - final double maxY; - +class RectangleBinPacker(final double maxX, final double maxY) { /// The bins of free space that we can search. late final List bins = [Rect.fromLTWH(0, 0, maxX, maxY)]; - RectangleBinPacker(this.maxX, this.maxY); - /// Finds a free space for a rectangle of lengths [width] and [height] in /// the atlas. Rect pack(double width, double height) { diff --git a/packages/flame_tiled/lib/src/renderable_layers/group_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/group_layer.dart index 4f6b8054ef3..0201dd076ee 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/group_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/group_layer.dart @@ -6,14 +6,12 @@ import 'package:meta/meta.dart'; import 'package:tiled/tiled.dart'; @internal -class GroupLayer extends RenderableLayer { - GroupLayer({ - required super.layer, - required super.map, - required super.destTileSize, - super.filterQuality, - }); - +class GroupLayer({ + required super.layer, + required super.map, + required super.destTileSize, + super.filterQuality, +}) extends RenderableLayer { /// The layers of this group, in the order they are rendered. Iterable get layers => children.whereType(); diff --git a/packages/flame_tiled/lib/src/renderable_layers/image_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/image_layer.dart index 8258f1db56c..c0fc284bb42 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/image_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/image_layer.dart @@ -8,18 +8,17 @@ import 'package:meta/meta.dart'; import 'package:tiled/tiled.dart'; @internal -class FlameImageLayer extends RenderableLayer { - final Image _image; +class FlameImageLayer({ + required super.layer, + required super.map, + required super.destTileSize, + required final Image _image, + super.filterQuality, +}) extends RenderableLayer { late final ImageRepeat _repeat; final MutableRect _paintArea = MutableRect.fromLTRB(0, 0, 0, 0); - FlameImageLayer({ - required super.layer, - required super.map, - required super.destTileSize, - required this._image, - super.filterQuality, - }) { + this { _initImageRepeat(); } diff --git a/packages/flame_tiled/lib/src/renderable_layers/object_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/object_layer.dart index fdb6cd8be15..3d8afe298ed 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/object_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/object_layer.dart @@ -6,14 +6,12 @@ import 'package:tiled/tiled.dart'; /// component tree so that components can be added to it and be rendered at the /// depth of the layer. @internal -class ObjectLayer extends RenderableLayer { - ObjectLayer({ - required super.layer, - required super.map, - required super.destTileSize, - super.filterQuality, - }); - +class ObjectLayer({ + required super.layer, + required super.map, + required super.destTileSize, + super.filterQuality, +}) extends RenderableLayer { @override void refreshCache() {} } diff --git a/packages/flame_tiled/lib/src/renderable_layers/renderable_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/renderable_layer.dart index 0b1ca69341d..d8cd672a69f 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/renderable_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/renderable_layer.dart @@ -33,18 +33,19 @@ import 'package:tiled/tiled.dart'; /// is recalculated whenever the map is rendered, so move a layer by changing /// [offsetX] and [offsetY] instead of [position]. /// {@endtemplate} -abstract class RenderableLayer extends PositionComponent { +abstract class RenderableLayer({ /// The Tiled layer that this component renders. - final T layer; - - /// The target size for each tile of the map. - final Vector2 destTileSize; + required final T layer, /// The map that [layer] belongs to. - final TiledMap map; + required final TiledMap map, + /// The target size for each tile of the map. + required final Vector2 destTileSize, + FilterQuality? filterQuality, +}) extends PositionComponent { /// The [FilterQuality] that should be used by all the layers. - final FilterQuality filterQuality; + final FilterQuality filterQuality = filterQuality ?? FilterQuality.none; /// The horizontal offset of this layer, relative to its parent, scaled to /// [destTileSize]. @@ -55,12 +56,7 @@ abstract class RenderableLayer extends PositionComponent { late double offsetY = layer.offsetY * scaleY; /// {@macro renderable_layer} - RenderableLayer({ - required this.layer, - required this.map, - required this.destTileSize, - FilterQuality? filterQuality, - }) : filterQuality = filterQuality ?? FilterQuality.none { + this { position.setValues(offsetX, offsetY); } @@ -91,7 +87,7 @@ abstract class RenderableLayer extends PositionComponent { layerPaintFactory: layerPaintFactory, ); } else if (layer is ImageLayer) { - return FlameImageLayer.load( + return await FlameImageLayer.load( layer: layer, map: map, destTileSize: destTileSize, @@ -226,13 +222,11 @@ abstract class RenderableLayer extends PositionComponent { /// It is still added to the component tree so that its offset and parallax /// factor propagate to any components that are added to it. @internal -class UnsupportedLayer extends RenderableLayer { - UnsupportedLayer({ - required super.layer, - required super.map, - required super.destTileSize, - }); - +class UnsupportedLayer({ + required super.layer, + required super.map, + required super.destTileSize, +}) extends RenderableLayer { @override void refreshCache() {} } diff --git a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/hexagonal_tile_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/hexagonal_tile_layer.dart index e8a35125ebf..a8079cd21c0 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/hexagonal_tile_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/hexagonal_tile_layer.dart @@ -8,18 +8,16 @@ import 'package:meta/meta.dart'; /// [HexagonalTileLayer] have hexagonal-shaped tiles and also its overall shape /// is like a honeycomb. @internal -class HexagonalTileLayer extends FlameTileLayer { - HexagonalTileLayer({ - required super.layer, - required super.map, - required super.destTileSize, - required super.tiledAtlas, - required super.animationFrames, - required super.ignoreFlip, - required super.layerPaintFactory, - super.filterQuality, - }); - +class HexagonalTileLayer({ + required super.layer, + required super.map, + required super.destTileSize, + required super.tiledAtlas, + required super.animationFrames, + required super.ignoreFlip, + required super.layerPaintFactory, + super.filterQuality, +}) extends FlameTileLayer { @override void cacheTiles() { final halfDestinationTile = destTileSize / 2; diff --git a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/isometric_tile_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/isometric_tile_layer.dart index c0f85a0946f..934cdcb8ee6 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/isometric_tile_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/isometric_tile_layer.dart @@ -7,18 +7,16 @@ import 'package:meta/meta.dart'; /// [IsometricTileLayer] is the tile layer that has an isometric view. /// You can see the details in the [https://en.wikipedia.org/wiki/Isometric_video_game_graphics]. @internal -class IsometricTileLayer extends FlameTileLayer { - IsometricTileLayer({ - required super.layer, - required super.map, - required super.destTileSize, - required super.tiledAtlas, - required super.animationFrames, - required super.ignoreFlip, - required super.layerPaintFactory, - super.filterQuality, - }); - +class IsometricTileLayer({ + required super.layer, + required super.map, + required super.destTileSize, + required super.tiledAtlas, + required super.animationFrames, + required super.ignoreFlip, + required super.layerPaintFactory, + super.filterQuality, +}) extends FlameTileLayer { @override void cacheTiles() { final halfDestinationTile = destTileSize / 2; diff --git a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/orthogonal_tile_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/orthogonal_tile_layer.dart index 88de5d4c1af..a9c20ef9010 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/orthogonal_tile_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/orthogonal_tile_layer.dart @@ -7,18 +7,16 @@ import 'package:meta/meta.dart'; /// [OrthogonalTileLayer] is a tile layer that each axis is represented /// orthogonally. @internal -class OrthogonalTileLayer extends FlameTileLayer { - OrthogonalTileLayer({ - required super.layer, - required super.map, - required super.destTileSize, - required super.tiledAtlas, - required super.animationFrames, - required super.ignoreFlip, - required super.layerPaintFactory, - super.filterQuality, - }); - +class OrthogonalTileLayer({ + required super.layer, + required super.map, + required super.destTileSize, + required super.tiledAtlas, + required super.animationFrames, + required super.ignoreFlip, + required super.layerPaintFactory, + super.filterQuality, +}) extends FlameTileLayer { @override void cacheTiles() { final size = destTileSize; diff --git a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/staggered_tile_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/staggered_tile_layer.dart index 43d0be4b3dd..64d830104a1 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/staggered_tile_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/staggered_tile_layer.dart @@ -7,18 +7,16 @@ import 'package:meta/meta.dart'; /// [StaggeredTileLayer] is an isometric map using a staggered axis. @internal -class StaggeredTileLayer extends FlameTileLayer { - StaggeredTileLayer({ - required super.layer, - required super.map, - required super.destTileSize, - required super.tiledAtlas, - required super.animationFrames, - required super.ignoreFlip, - required super.layerPaintFactory, - super.filterQuality, - }); - +class StaggeredTileLayer({ + required super.layer, + required super.map, + required super.destTileSize, + required super.tiledAtlas, + required super.animationFrames, + required super.ignoreFlip, + required super.layerPaintFactory, + super.filterQuality, +}) extends FlameTileLayer { @override void cacheTiles() { final halfDestinationTile = destTileSize / 2; diff --git a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart index 1fd3d8b5dc9..de8e2d4e790 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart @@ -31,9 +31,17 @@ import 'package:meta/meta.dart'; /// /// {@endtemplate} @internal -abstract class FlameTileLayer extends RenderableLayer { +abstract class FlameTileLayer({ + required super.layer, + required super.map, + required super.destTileSize, + required final TiledAtlas tiledAtlas, + required final Map animationFrames, + required final bool ignoreFlip, + required var Paint Function(double opacity) layerPaintFactory, + super.filterQuality, +}) extends RenderableLayer { late Paint _layerPaint = layerPaintFactory(opacity); - final TiledAtlas tiledAtlas; /// Cached transform of every tile, indexed as /// `transforms[x - originX][y - originY]` for the Tiled tile `(x, y)`. @@ -49,21 +57,6 @@ abstract class FlameTileLayer extends RenderableLayer { int originX = 0; int originY = 0; final animations = []; - final Map animationFrames; - final bool ignoreFlip; - Paint Function(double opacity) layerPaintFactory; - - FlameTileLayer({ - required super.layer, - required super.map, - required super.destTileSize, - required this.tiledAtlas, - required this.animationFrames, - required this.ignoreFlip, - required this.layerPaintFactory, - super.filterQuality, - }); - @override void onOpacityChanged() { _layerPaint = layerPaintFactory(opacity); diff --git a/packages/flame_tiled/lib/src/renderable_tile_map.dart b/packages/flame_tiled/lib/src/renderable_tile_map.dart index 5db36c27e57..eca6fb089b2 100644 --- a/packages/flame_tiled/lib/src/renderable_tile_map.dart +++ b/packages/flame_tiled/lib/src/renderable_tile_map.dart @@ -54,19 +54,29 @@ Paint _defaultLayerPaintFactory(double opacity) => /// and [update]. /// /// {@endtemplate} -class RenderableTiledMap extends Component { +class RenderableTiledMap( /// [TiledMap] instance for this map. - final TiledMap map; + final TiledMap map, /// The top level layers of the map, in the same order as [TiledMap.layers]. /// /// The layers nested in a group layer are the children of that group's /// [RenderableLayer]. - final List renderableLayers; + final List renderableLayers, /// The target size for each tile in the tiled map. - final Vector2 destTileSize; + final Vector2 destTileSize, { + /// The camera that the parallax factors of the layers are calculated + /// against. + /// + /// When this is null, which is the default, the camera that is currently + /// rendering the map is used, falling back to the camera of the game when + /// the map is not rendered through a camera. It only needs to be set when + /// the map is rendered outside of a game. + var CameraComponent? camera, + final Map animationFrames = const {}, +}) extends Component { /// The size of the rendered map, see [TiledComponent.computeSize]. late final Vector2 size = TiledComponent.computeSize( map.orientation, @@ -78,28 +88,11 @@ class RenderableTiledMap extends Component { map.staggerAxis, ); - /// The camera that the parallax factors of the layers are calculated - /// against. - /// - /// When this is null, which is the default, the camera that is currently - /// rendering the map is used, falling back to the camera of the game when - /// the map is not rendered through a camera. It only needs to be set when - /// the map is rendered outside of a game. - CameraComponent? camera; - /// Paint for the map's background color, if there is one late final Paint? _backgroundPaint; - final Map animationFrames; - /// {@macro _renderable_tiled_map} - RenderableTiledMap( - this.map, - this.renderableLayers, - this.destTileSize, { - this.camera, - this.animationFrames = const {}, - }) { + this { _refreshCache(); final backgroundColor = map.backgroundColor?.toColor(); @@ -328,7 +321,7 @@ class RenderableTiledMap extends Component { }) async { final mapPath = package == null ? fileName : 'packages/$package/$fileName'; final contents = await (bundle ?? Flame.bundle).loadString(mapPath); - return fromString( + return await fromString( contents, destTileSize, atlasMaxX: atlasMaxX, @@ -381,7 +374,7 @@ class RenderableTiledMap extends Component { contents, (path) => (bundle ?? Flame.bundle).loadString('$tsxDirectory$path'), ); - return fromTiledMap( + return await fromTiledMap( map, destTileSize, atlasMaxX: atlasMaxX, diff --git a/packages/flame_tiled/lib/src/simple_flips.dart b/packages/flame_tiled/lib/src/simple_flips.dart index 033fc944ebc..eab49a15ecc 100644 --- a/packages/flame_tiled/lib/src/simple_flips.dart +++ b/packages/flame_tiled/lib/src/simple_flips.dart @@ -19,35 +19,26 @@ import 'package:tiled/tiled.dart'; /// Hexagonal maps are the exception: Tiled rotates their tiles in steps of /// pi/3 instead, see [SimpleFlips.fromHexagonalFlips]. /// {@endtemplate} -class SimpleFlips { +class SimpleFlips( /// The angle (in steps of pi/2 rads, or pi/3 rads if [isHexagonal] is true), /// clockwise, around the center of the tile. - final int angle; + final int angle, /// The cosine of the rotation. - final double cos; + final double cos, /// The sine of the rotation. - final double sin; + final double sin, { /// Whether to flip (across a central vertical axis). - final bool flip; + required final bool flip, /// Whether the rotation is in steps of pi/3, as in hexagonal maps, instead /// of steps of pi/2. /// /// Tiles that are rotated in steps of pi/2 swap their width and height. - final bool isHexagonal; - - /// {@macro _simple_flips} - SimpleFlips( - this.angle, - this.cos, - this.sin, { - required this.flip, - this.isHexagonal = false, - }); - + final bool isHexagonal = false, +}) { /// Converts the flips of a tile in a hexagonal map. /// /// Tiled doesn't rotate tiles in steps of 90º in hexagonal maps, the diff --git a/packages/flame_tiled/lib/src/tile_animation.dart b/packages/flame_tiled/lib/src/tile_animation.dart index b129caf3375..4c3fc56d6f8 100644 --- a/packages/flame_tiled/lib/src/tile_animation.dart +++ b/packages/flame_tiled/lib/src/tile_animation.dart @@ -7,21 +7,16 @@ import 'package:flame_tiled/src/mutable_rect.dart'; /// This works because SpriteBatch holds a list of [Rect]. Those rectangles /// are usually immutable, but flame_tile uses a mutable rectangle to update /// the offsets in the image atlas. -class TileAnimation { - /// Frames of the animation loop. - final TileFrames frames; - +class TileAnimation( /// Rectangle that gets updated for each new frame in the animation. - final MutableRect batchedSource; + final MutableRect batchedSource, + /// Frames of the animation loop. + final TileFrames frames, +) { /// Current frame counter. int frame = 0; - TileAnimation( - this.batchedSource, - this.frames, - ); - void update(double dt) { if (frame != frames.frame) { frame = frames.frame; @@ -31,21 +26,19 @@ class TileAnimation { } /// Records the list of frames for a tile so that it can be reused. -class TileFrames { +class TileFrames( /// Rectangles for each frame in the animation. - final List sources; + final List sources, /// Duration, in seconds, for each frame in the animation. - final List durations; - + final List durations, +) { /// Current frame lifetime. double frameTime = 0.0; /// Current frame counter for all frames sharing this animation. int frame = 0; - TileFrames(this.sources, this.durations); - void update(double dt) { frameTime += dt; diff --git a/packages/flame_tiled/lib/src/tile_atlas.dart b/packages/flame_tiled/lib/src/tile_atlas.dart index 5c445f03aa4..9cdfdb5e9ea 100644 --- a/packages/flame_tiled/lib/src/tile_atlas.dart +++ b/packages/flame_tiled/lib/src/tile_atlas.dart @@ -14,38 +14,31 @@ bool _defaultTilesetPackingFilter(Tileset _) => true; /// /// Please note that [TiledAtlas] should not be reused without [clone] as it may /// have a different [batch] instance. -class TiledAtlas { +/// +/// Track one atlas for all images in the Tiled map. +/// +/// See [fromTiledMap] for asynchronous loading. +class TiledAtlas._({ /// Single atlas for all renders. - // Retain this as SpriteBatch can dispose of the original image for flips. - final Image? atlas; + required final Image? atlas, /// Map of all source images to their new offset. - final Map offsets; - - /// The single batch operation for this atlas. - final SpriteBatch? batch; + required final Map offsets, /// Image key for this atlas. - final String key; + required final String key, /// If SpriteBatch should use atlas or not. - final bool useAtlas; - - /// Track one atlas for all images in the Tiled map. - /// - /// See [fromTiledMap] for asynchronous loading. - TiledAtlas._({ - required this.atlas, - required this.offsets, - required this.key, - this.useAtlas = true, - }) : batch = atlas == null - ? null - : SpriteBatch( - atlas, - imageKey: key, - useAtlas: useAtlas, - ); + final bool useAtlas = true, +}) { + /// The single batch operation for this atlas. + final SpriteBatch? batch = atlas == null + ? null + : SpriteBatch( + atlas, + imageKey: key, + useAtlas: useAtlas, + ); /// Returns whether or not this atlas contains [source]. bool contains(String? source) => offsets.containsKey(source); diff --git a/packages/flame_tiled/lib/src/tile_stack.dart b/packages/flame_tiled/lib/src/tile_stack.dart index b6328b5133c..53e91f9233a 100644 --- a/packages/flame_tiled/lib/src/tile_stack.dart +++ b/packages/flame_tiled/lib/src/tile_stack.dart @@ -7,14 +7,12 @@ import 'package:flame/rendering.dart'; /// Tiles are nothing more than an x/y coordinate in each layer. TileStack lets /// you collect a certain group of tiles out of all the layers, and then /// set their positions. This is typically done by using Flame's effects. -class TileStack extends Component implements PositionProvider { - final List _tiles; - +class TileStack(final List _tiles) + extends Component + implements PositionProvider { /// The number of tiles in this stack. int get length => _tiles.length; - TileStack(this._tiles); - @override Vector2 get position => _tiles.first.position; diff --git a/packages/flame_tiled/lib/src/tile_transform.dart b/packages/flame_tiled/lib/src/tile_transform.dart index 15f35fba950..170d783caa0 100644 --- a/packages/flame_tiled/lib/src/tile_transform.dart +++ b/packages/flame_tiled/lib/src/tile_transform.dart @@ -7,16 +7,9 @@ import 'package:meta/meta.dart'; /// Caches transforms for staggered maps as the row/col are switched. @internal -class TileTransform { - final Rect source; - final MutableRSTransform transform; - final SimpleFlips flip; - final SpriteBatch batch; - - TileTransform( - this.source, - this.transform, - this.flip, - this.batch, - ); -} +class TileTransform( + final Rect source, + final MutableRSTransform transform, + final SimpleFlips flip, + final SpriteBatch batch, +); diff --git a/packages/flame_tiled/lib/src/tiled_component.dart b/packages/flame_tiled/lib/src/tiled_component.dart index 4b58292d1c4..a2e77399891 100644 --- a/packages/flame_tiled/lib/src/tiled_component.dart +++ b/packages/flame_tiled/lib/src/tiled_component.dart @@ -16,14 +16,20 @@ import 'package:tiled/tiled.dart'; /// Sprite Batches. The map, and the layers of the map, are children of this /// component. /// {@endtemplate} -class TiledComponent extends PositionComponent - with HasGameRef { +class TiledComponent( /// The map that this component renders, which is a child of this component. /// /// A map holds the state of its layers, so it can only belong to one /// [TiledComponent] at a time. - final RenderableTiledMap tileMap; - + final RenderableTiledMap tileMap, { + super.position, + super.scale, + super.angle, + super.anchor, + Iterable? children, + super.priority, + super.key, +}) extends PositionComponent with HasGameRef { /// This property **cannot** be reassigned at runtime. To make the /// [PositionComponent] larger or smaller, change its [scale]. @override @@ -46,20 +52,12 @@ class TiledComponent extends PositionComponent } /// {@macro _tiled_component} - TiledComponent( - this.tileMap, { - super.position, - super.scale, - super.angle, - super.anchor, - Iterable? children, - super.priority, - super.key, - }) : assert( - tileMap.parent == null, - 'A RenderableTiledMap can only belong to one TiledComponent', - ), - super(size: tileMap.size) { + this + : assert( + tileMap.parent == null, + 'A RenderableTiledMap can only belong to one TiledComponent', + ), + super(size: tileMap.size) { add(tileMap); if (children != null) { addAll(children); diff --git a/packages/flame_tiled/pubspec.yaml b/packages/flame_tiled/pubspec.yaml index a00c1b1c0cc..449af9c083f 100644 --- a/packages/flame_tiled/pubspec.yaml +++ b/packages/flame_tiled/pubspec.yaml @@ -13,8 +13,8 @@ topics: - tilemap environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: collection: ^1.17.1 diff --git a/packages/flame_tiled/test/test_asset_bundle.dart b/packages/flame_tiled/test/test_asset_bundle.dart index 0ef82f48389..9172609de99 100644 --- a/packages/flame_tiled/test/test_asset_bundle.dart +++ b/packages/flame_tiled/test/test_asset_bundle.dart @@ -10,15 +10,10 @@ import 'package:flutter/services.dart' show CachingAssetBundle; /// `assets/images/map.png` and `assets/tiles/map.tmx` resolve to /// `test/assets/...`, so fixtures can be laid out flat regardless of the /// directory a test addresses them through. -class TestAssetBundle extends CachingAssetBundle { - TestAssetBundle({ - required this.imageNames, - required this.stringNames, - }); - - final List imageNames; - final List stringNames; - +class TestAssetBundle({ + required final List imageNames, + required final List stringNames, +}) extends CachingAssetBundle { static const _roots = ['assets/images/', 'assets/tiles/', 'assets/']; /// Collapses `..` segments, the way a real asset layout would already have diff --git a/packages/flame_tiled/test/test_image_utils.dart b/packages/flame_tiled/test/test_image_utils.dart index f201f1a8336..379a474be61 100644 --- a/packages/flame_tiled/test/test_image_utils.dart +++ b/packages/flame_tiled/test/test_image_utils.dart @@ -17,7 +17,7 @@ Future renderMapToPng( // Map size is now 320 wide, but it has 1 extra tile of height because // its actually double-height tiles. final image = await picture.toImageSafe(size.x.toInt(), size.y.toInt()); - return imageToPng(image); + return await imageToPng(image); } /// Renders the part of [map] inside [region], which is given in map pixels. @@ -38,7 +38,7 @@ Future renderMapRegionToPng( region.width.toInt(), region.height.toInt(), ); - return imageToPng(image); + return await imageToPng(image); } /// Renders the [game] the way it is shown on the screen, through its camera. @@ -50,7 +50,7 @@ Future renderGameToPng(FlameGame game) async { final size = game.canvasSize; final image = await picture.toImageSafe(size.x.toInt(), size.y.toInt()); - return imageToPng(image); + return await imageToPng(image); } Future imageToPng(Image image) async => diff --git a/packages/flame_typled/example/lib/main.dart b/packages/flame_typled/example/lib/main.dart index efd1709893c..5bb5b32fb7e 100644 --- a/packages/flame_typled/example/lib/main.dart +++ b/packages/flame_typled/example/lib/main.dart @@ -9,9 +9,7 @@ void main() { runApp(const MyApp()); } -class MyApp extends StatelessWidget { - const MyApp({super.key}); - +class const MyApp({super.key}) extends StatelessWidget { @override Widget build(BuildContext context) { return const MaterialApp( @@ -22,7 +20,7 @@ class MyApp extends StatelessWidget { } } -class TypledExample extends FlameGame { +class TypledExample() extends FlameGame { @override Color backgroundColor() => const Color(0xFF2A1D3A); diff --git a/packages/flame_typled/example/pubspec.yaml b/packages/flame_typled/example/pubspec.yaml index 4678b907174..c8dd0fa3a6e 100644 --- a/packages/flame_typled/example/pubspec.yaml +++ b/packages/flame_typled/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: "none" version: 1.0.0+1 environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/packages/flame_typled/lib/flame_typled.dart b/packages/flame_typled/lib/flame_typled.dart index a65c3765bc7..c2346fd9e37 100644 --- a/packages/flame_typled/lib/flame_typled.dart +++ b/packages/flame_typled/lib/flame_typled.dart @@ -1,3 +1 @@ -library flame_typled; - export 'typled_sprite_atlas.dart'; diff --git a/packages/flame_typled/lib/typled_sprite_atlas.dart b/packages/flame_typled/lib/typled_sprite_atlas.dart index c37dabcb43b..5dbe45971c7 100644 --- a/packages/flame_typled/lib/typled_sprite_atlas.dart +++ b/packages/flame_typled/lib/typled_sprite_atlas.dart @@ -13,27 +13,22 @@ import 'package:typled/typled.dart'; /// Loads a Typled atlas definition and its associated image, applying /// edge-repeated padding to eliminate "ghost lines" caused by /// floating-point texture sampling errors. -class TypledSpriteAtlas { +class TypledSpriteAtlas({ /// The parsed Typled atlas definition. - final TypledAtlas atlas; + required final TypledAtlas atlas, /// The tile size in pixels. - final double tileSize; + required final double tileSize, /// The atlas image (padded or original depending on configuration). - final Image image; + required final Image image, /// Padding added around each tile in the atlas (1px per side, /// or 0 if padding is disabled). - final int padding; - + required final int padding, +}) { /// Creates a [TypledSpriteAtlas] from a pre-loaded [atlas] and [image]. - TypledSpriteAtlas({ - required this.atlas, - required this.tileSize, - required this.image, - required this.padding, - }); + this; /// Creates a [SpriteBatch] from this atlas image. SpriteBatch toBatch({bool useAtlas = false}) { @@ -193,7 +188,7 @@ class TypledSpriteAtlas { } final picture = recorder.endRecording(); - return picture.toImage(newWidth, newHeight); + return await picture.toImage(newWidth, newHeight); } static Future _loadAtlas( @@ -215,7 +210,7 @@ extension TypledSpriteAtlasGameExtension on Game { String path, { bool disablePadding = false, }) async { - return TypledSpriteAtlas.load( + return await TypledSpriteAtlas.load( path, cache: assets, disablePadding: disablePadding, diff --git a/packages/flame_typled/pubspec.yaml b/packages/flame_typled/pubspec.yaml index 94699b79957..c8c456710e0 100644 --- a/packages/flame_typled/pubspec.yaml +++ b/packages/flame_typled/pubspec.yaml @@ -13,8 +13,8 @@ topics: - sprite-atlas environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: flame: ^2.0.0-dev.0 diff --git a/pubspec.yaml b/pubspec.yaml index d208a277a4e..e71779f9897 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -8,7 +8,7 @@ workspace: - examples/games/** environment: - sdk: ">=3.12.0 <4.0.0" + sdk: ">=3.13.0 <4.0.0" dev_dependencies: melos: ^8.1.0 @@ -25,8 +25,8 @@ melos: bootstrap: environment: - sdk: ">=3.12.0 <4.0.0" - flutter: ">=3.44.0" + sdk: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" dependencies: meta: ^1.12.0 vector_math: ^2.1.4