Skip to content

Commit d3278cd

Browse files
authored
Align trExists API with tr/plural (#738)
* Make trExists context-aware * Add trExists to context extension
1 parent 0aa278e commit d3278cd

File tree

3 files changed

+21
-4
lines changed

3 files changed

+21
-4
lines changed

lib/src/public.dart

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,12 @@ String tr(
4545
.tr(key, args: args, namedArgs: namedArgs, gender: gender);
4646
}
4747

48-
bool trExists(String key) {
49-
return Localization.instance
50-
.exists(key);
48+
bool trExists(String key, {BuildContext? context}) {
49+
return context != null
50+
? Localization.of(context)!
51+
.exists(key)
52+
: Localization.instance
53+
.exists(key);
5154
}
5255

5356
/// {@template plural}

lib/src/public_ext.dart

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ extension StringTranslateExtension on String {
9090
ez.tr(this,
9191
context: context, args: args, namedArgs: namedArgs, gender: gender);
9292

93-
bool trExists() => ez.trExists(this);
93+
bool trExists({BuildContext? context}) => ez.trExists(this, context: context);
9494

9595
/// {@macro plural}
9696
String plural(
@@ -219,6 +219,16 @@ extension BuildContextEasyLocalizationExtension on BuildContext {
219219
);
220220
}
221221

222+
bool trExists(String key) {
223+
final localization = Localization.of(this);
224+
225+
if (localization == null) {
226+
throw const LocalizationNotFoundException();
227+
}
228+
229+
return localization.exists(key);
230+
}
231+
222232
String plural(
223233
String key,
224234
num number, {

test/easy_localization_test.dart

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,10 @@ void main() {
716716
test('tr', () {
717717
expect(tr('test'), 'test');
718718
});
719+
test('trExists', () {
720+
expect(trExists('test'), true);
721+
expect(trExists('xyz'), false);
722+
});
719723
test('plural', () {
720724
expect(plural('day', 0), '0 days');
721725
});

0 commit comments

Comments
 (0)