@@ -2,56 +2,34 @@ import 'package:country_pickers/countries.dart';
2
2
import 'package:country_pickers/country.dart' ;
3
3
4
4
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
+
5
13
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);
13
15
}
14
16
15
17
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);
23
19
}
24
20
25
21
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);
33
23
}
34
24
35
25
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);
43
27
}
44
28
45
29
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);
56
34
}
57
35
}
0 commit comments