diff --git a/packages/lite_ref/lib/src/scoped/ref.dart b/packages/lite_ref/lib/src/scoped/ref.dart index 6f0972f..9c8aa53 100644 --- a/packages/lite_ref/lib/src/scoped/ref.dart +++ b/packages/lite_ref/lib/src/scoped/ref.dart @@ -54,6 +54,19 @@ class ScopedRef { _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 diff --git a/packages/lite_ref/test/src/scoped/ref_test.dart b/packages/lite_ref/test/src/scoped/ref_test.dart index 15a36b2..5327056 100644 --- a/packages/lite_ref/test/src/scoped/ref_test.dart +++ b/packages/lite_ref/test/src/scoped/ref_test.dart @@ -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 {