diff --git a/lib/src/public.dart b/lib/src/public.dart index ba419496..60c9d2a2 100644 --- a/lib/src/public.dart +++ b/lib/src/public.dart @@ -45,9 +45,12 @@ String tr( .tr(key, args: args, namedArgs: namedArgs, gender: gender); } -bool trExists(String key) { - return Localization.instance - .exists(key); +bool trExists(String key, {BuildContext? context}) { + return context != null + ? Localization.of(context)! + .exists(key) + : Localization.instance + .exists(key); } /// {@template plural} diff --git a/lib/src/public_ext.dart b/lib/src/public_ext.dart index 4b1aa878..f65c79a9 100644 --- a/lib/src/public_ext.dart +++ b/lib/src/public_ext.dart @@ -90,7 +90,7 @@ extension StringTranslateExtension on String { ez.tr(this, context: context, args: args, namedArgs: namedArgs, gender: gender); - bool trExists() => ez.trExists(this); + bool trExists({BuildContext? context}) => ez.trExists(this, context: context); /// {@macro plural} String plural( @@ -219,6 +219,16 @@ extension BuildContextEasyLocalizationExtension on BuildContext { ); } + bool trExists(String key) { + final localization = Localization.of(this); + + if (localization == null) { + throw const LocalizationNotFoundException(); + } + + return localization.exists(key); + } + String plural( String key, num number, { diff --git a/test/easy_localization_test.dart b/test/easy_localization_test.dart index 9078d9ef..3cf311fa 100644 --- a/test/easy_localization_test.dart +++ b/test/easy_localization_test.dart @@ -716,6 +716,10 @@ void main() { test('tr', () { expect(tr('test'), 'test'); }); + test('trExists', () { + expect(trExists('test'), true); + expect(trExists('xyz'), false); + }); test('plural', () { expect(plural('day', 0), '0 days'); });