我无法在 Dart 中将父项 class 转换为子项 class

I can't cast a parent class to its child class in Dart

我正在使用 Flame 在 Flutter 中构建 2D 游戏,但我遇到了 CAST 问题。

import 'dart:ui';

class BarrierRect extends Rect {
  BarrierRect.fromLTWH(double left, double top, double width, double height) : super.fromLTWH(left, top, width, height);


  bool _barrier = true;

  bool get isBarrier {
    return this._barrier;
  }

  set isBarrier(bool isBarrier) {
    this._barrier = isBarrier;
  }

  BarrierRect shift(Offset offset) {
    Rect rect = super.shift(offset);
    return rect as BarrierRect; // There is an exception in this line
  }
}

以下是异常的详细信息。

I/flutter (18075): ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (18075): The following _CastError was thrown during a scheduler callback:
I/flutter (18075): type 'Rect' is not a subtype of type 'BarrierRect' in type cast
I/flutter (18075): 
I/flutter (18075): When the exception was thrown, this was the stack:
I/flutter (18075): #0      BarrierRect.shift (package:flappy_bird/util/barrier-rect.dart:19:17)
I/flutter (18075): #1      GameBorder.update (package:flappy_bird/component/game-border.dart:43:25)
I/flutter (18075): #2      FlyGame.update (package:flappy_bird/fly-game.dart:40:18)
I/flutter (18075): #3      GameRenderBox._update (package:flame/game.dart:293:10)
I/flutter (18075): #4      GameRenderBox._tick (package:flame/game.dart:286:5)
I/flutter (18075): #5      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1016:15)
I/flutter (18075): #6      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleBeginFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:934:11)
I/flutter (18075): #7      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:367:8)

那么,我应该怎么做才能 return BarrierRect class?

Rect.shift 不创建新的 BarrierRect:

Rect shift(Offset offset) {
  return Rect.fromLTRB(left + offset.dx, top + offset.dy, right + offset.dx, bottom + offset.dy);
}

https://api.flutter.dev/flutter/dart-ui/Rect/shift.html

所以从 super.shift(...) 返回的 Rect 不能转换为 BarrierRect 是正确的。

考虑制作 BarrierRect decoratewrap 一个给定的 Rect 或者只是简单地复制一个。

class BarrierRect extends Rect {

  BarrierRect.fromRect(final Rect rect) : super(...);


  bool _barrier = true;

  bool get isBarrier {
    return this._barrier;
  }

  set isBarrier(bool isBarrier) {
    this._barrier = isBarrier;
  }

  BarrierRect shift(Offset offset) {
    Rect rect = super.shift(offset);
    return BarrierRect.fromRect(rect);
  }
}
  • 或 -
class BarrierRect {
    final Rect origin;
    BarrierRect(this.origin);

    ... 

    BarrierRect shift(Offset offset) {
      Rect rect = origin.shift(offset);
      return BarrierRect(rect);
    }
}