Skip to content

Commit 674cb30

Browse files
authored
Merge pull request #332 from awhitford/country_picker_optimizations
Optimizations for CountryPickerUtil.
2 parents 7b5d33e + 85b4f58 commit 674cb30

File tree

1 file changed

+16
-38
lines changed

1 file changed

+16
-38
lines changed

lib/src/country_picker_util.dart

Lines changed: 16 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,56 +2,34 @@ import 'package:country_pickers/countries.dart';
22
import 'package:country_pickers/country.dart';
33

44
class CountryPickerUtil {
5+
static Country _getCountryByField(
6+
String Function(Country) fieldAccessor, String query) {
7+
final queryUpperCase = query.toUpperCase();
8+
return countryList.firstWhere(
9+
(country) => fieldAccessor(country).toUpperCase() == queryUpperCase,
10+
orElse: () => null);
11+
}
12+
513
static Country getCountryByIso3Code(String iso3Code) {
6-
try {
7-
return countryList.firstWhere(
8-
(country) => country.iso3Code.toLowerCase() == iso3Code.toLowerCase(),
9-
);
10-
} catch (error) {
11-
return null;
12-
}
14+
return _getCountryByField((country) => country.iso3Code, iso3Code);
1315
}
1416

1517
static Country getCountryByIsoCode(String isoCode) {
16-
try {
17-
return countryList.firstWhere(
18-
(country) => country.isoCode.toLowerCase() == isoCode.toLowerCase(),
19-
);
20-
} catch (error) {
21-
return null;
22-
}
18+
return _getCountryByField((country) => country.isoCode, isoCode);
2319
}
2420

2521
static Country getCountryByName(String name) {
26-
try {
27-
return countryList.firstWhere(
28-
(country) => country.name.toLowerCase() == name.toLowerCase(),
29-
);
30-
} catch (error) {
31-
return null;
32-
}
22+
return _getCountryByField((country) => country.name, name);
3323
}
3424

3525
static Country getCountryByPhoneCode(String phoneCode) {
36-
try {
37-
return countryList.firstWhere(
38-
(country) => country.phoneCode.toLowerCase() == phoneCode.toLowerCase(),
39-
);
40-
} catch (error) {
41-
return null;
42-
}
26+
return _getCountryByField((country) => country.phoneCode, phoneCode);
4327
}
4428

4529
static Country getCountryByCodeOrName(String codeOrName) {
46-
var country;
47-
country = getCountryByIso3Code(codeOrName);
48-
if (country != null) return country;
49-
country = getCountryByIsoCode(codeOrName);
50-
if (country != null) return country;
51-
country = getCountryByName(codeOrName);
52-
if (country != null) return country;
53-
country = getCountryByPhoneCode(codeOrName);
54-
if (country != null) return country;
55-
return country;
30+
return getCountryByIso3Code(codeOrName) ??
31+
getCountryByIsoCode(codeOrName) ??
32+
getCountryByName(codeOrName) ??
33+
getCountryByPhoneCode(codeOrName);
5634
}
5735
}

0 commit comments

Comments
 (0)