Skip to content

Commit

Permalink
Merge pull request #16 from jinyus/feat/exists
Browse files Browse the repository at this point in the history
Add exists() method to ScopedRef with tests
  • Loading branch information
jinyus authored Mar 14, 2024
2 parents bb52660 + 7b43259 commit ab1f4ea
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/lite_ref/lib/src/scoped/ref.dart
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,19 @@ class ScopedRef<T> {
_instance = _create(context);
}

/// Returns `true` if this [ScopedRef] is iniitalized
/// in the current [LiteRefScope].
bool exists(BuildContext context) {
assert(
context is Element,
'This must be called with the context of a Widget.',
);

final element = LiteRefScope._of(context);

return element._cache.containsKey(_id);
}

/// Returns the instance of [T] in the current scope.
///
/// ```dart
Expand Down
50 changes: 50 additions & 0 deletions packages/lite_ref/test/src/scoped/ref_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,56 @@ void main() {
expect(find.text('got: 2'), findsOneWidget);
},
);
testWidgets(
'should return true if the ScopedRef is '
'initialized in the current LiteRefScope',
(tester) async {
final countRef = Ref.scoped((ctx) => 1);

await tester.pumpWidget(
MaterialApp(
home: LiteRefScope(
child: Builder(
builder: (context) {
final initialized = countRef.exists(context);
expect(initialized, false);

final val = countRef.of(context);
expect(val, 1);

final initialized2 = countRef.exists(context);
expect(initialized2, true);

return LiteRefScope(
overrides: [
countRef.overrideWith((ctx) => 2),
],
child: Builder(
builder: (context) {
final initialized = countRef.exists(context);
expect(initialized, false);

final val = countRef.of(context);
expect(val, 2);

final initialized2 = countRef.exists(context);
expect(initialized2, true);

return Text('$val');
},
),
);
},
),
),
),
);

await tester.pumpAndSettle();

expect(find.text('2'), findsOneWidget);
},
);
}

class _Resource implements Disposable {
Expand Down

0 comments on commit ab1f4ea

Please sign in to comment.