Skip to content

Commit

Permalink
refactor!: Make query() result an Iterable (#3209)
Browse files Browse the repository at this point in the history
Avoid hard-to-detect bugs by disallowing people to touch the list that
they get from `query()`.
  • Loading branch information
filiph committed Jun 28, 2024
1 parent 61e9aa5 commit c094caa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
31 changes: 31 additions & 0 deletions packages/flame/lib/src/components/core/component_set.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,37 @@ class ComponentSet extends QueryableOrderedSet<Component> {
@override
bool get isNotEmpty => !isEmpty;

/// Queries the component set (typically [Component.children]) for
/// components of type [C].
///
/// Example:
///
/// ```dart
/// final myComponents = world.children.query<MyCustomComponent>();
/// ```
///
/// This is equivalent to `world.children.whereType<MyCustomComponent>()`
/// except that [query] is O(1).
///
/// The function returns an [Iterable]. In past versions of Flame,
/// it was a modifiable [List] but modifying this list would have been a bug.
///
/// When [strictMode] is `true`, you *must* call [register]
/// for every type [C] you desire to use. Use something like:
///
/// ```dart
/// world.children.register<MyCustomComponent>();
/// ```
@override
Iterable<C> query<C extends Component>() {
// We are returning an iterable (view) here to avoid hard-to-detect
// bugs where the user assumes the query is a unique result list
// and they start doing things like `removeWhere()`.
// This would remove components from the component set itself
// (but not from the game)!
return super.query();
}

/// Sorts the components according to their `priority`s. This method is
/// invoked by the framework when it knows that the priorities of the
/// components in this set has changed.
Expand Down
2 changes: 1 addition & 1 deletion packages/flame/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ dependencies:
flutter:
sdk: flutter
meta: ^1.12.0
ordered_set: ^5.0.3
ordered_set: ^6.0.0
vector_math: ^2.1.4

dev_dependencies:
Expand Down

0 comments on commit c094caa

Please sign in to comment.