Merge branch 'main' into main

This commit is contained in:
Chandra Abdul Fattah
2025-01-31 23:22:13 +07:00
committed by GitHub
20 changed files with 508 additions and 1273 deletions

View File

@@ -1,10 +1,11 @@
## 3.0.0 - March 10 2023 ## 3.1.0 - October 24 2024
- Add some improvement
## 3.0.0 - March 10 2023
- Support Flutter 3.7.0 - Support Flutter 3.7.0
- Restructured package follow linter - Restructured package follow linter
## 2.0.2 ## 2.0.2
- added localization for no_country text in italian and english (please open a pr with other languages if you know them 🙏) - added localization for no_country text in italian and english (please open a pr with other languages if you know them 🙏)
- added possibility to inject a custom list of countries using `CountryCodePicker.countryList` - added possibility to inject a custom list of countries using `CountryCodePicker.countryList`
- minor fixes - minor fixes

View File

@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android" name="Android">
<configuration>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/example/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/build" />
</content>
<orderEntry type="jdk" jdkName="Android API 24 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Dart Packages" level="project" />
</component>
</module>

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/lib" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/packages" />
<excludeFolder url="file://$MODULE_DIR$/test/packages" />
</content>
<orderEntry type="jdk" jdkName="Android API 25 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart Packages" level="project" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Flutter Plugins" level="project" />
</component>
</module>

View File

@@ -1,71 +1,58 @@
plugins {
id "com.android.application"
id "kotlin-android"
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties() def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties') def localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) { if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader -> localPropertiesFile.withReader("UTF-8") { reader ->
localProperties.load(reader) localProperties.load(reader)
} }
} }
def flutterRoot = localProperties.getProperty('flutter.sdk') def flutterVersionCode = localProperties.getProperty("flutter.versionCode")
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) { if (flutterVersionCode == null) {
flutterVersionCode = '1' flutterVersionCode = "1"
} }
def flutterVersionName = localProperties.getProperty('flutter.versionName') def flutterVersionName = localProperties.getProperty("flutter.versionName")
if (flutterVersionName == null) { if (flutterVersionName == null) {
flutterVersionName = '1.0' flutterVersionName = "1.0"
} }
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android { android {
compileSdkVersion flutter.compileSdkVersion namespace = "com.example.example"
ndkVersion flutter.ndkVersion compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions { compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
} }
defaultConfig { defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.example" applicationId = "com.example.example"
// You can update the following values to match your application needs. // You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
minSdkVersion flutter.minSdkVersion minSdk = flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion targetSdk = flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger() versionCode = flutterVersionCode.toInteger()
versionName flutterVersionName versionName = flutterVersionName
} }
buildTypes { buildTypes {
release { release {
// TODO: Add your own signing config for the release build. // TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works. // Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug signingConfig = signingConfigs.debug
} }
} }
} }
flutter { flutter {
source '../..' source = "../.."
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
} }

View File

@@ -1,16 +1,3 @@
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects { allprojects {
repositories { repositories {
google() google()
@@ -18,14 +5,14 @@ allprojects {
} }
} }
rootProject.buildDir = '../build' rootProject.buildDir = "../build"
subprojects { subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}" project.buildDir = "${rootProject.buildDir}/${project.name}"
} }
subprojects { subprojects {
project.evaluationDependsOn(':app') project.evaluationDependsOn(":app")
} }
task clean(type: Delete) { tasks.register("clean", Delete) {
delete rootProject.buildDir delete rootProject.buildDir
} }

View File

@@ -1,11 +1,25 @@
include ':app' pluginManagement {
def flutterSdkPath = {
def properties = new Properties()
file("local.properties").withInputStream { properties.load(it) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
return flutterSdkPath
}()
def localPropertiesFile = new File(rootProject.projectDir, "local.properties") includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
def properties = new Properties()
assert localPropertiesFile.exists() repositories {
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } google()
mavenCentral()
gradlePluginPortal()
}
}
def flutterSdkPath = properties.getProperty("flutter.sdk") plugins {
assert flutterSdkPath != null, "flutter.sdk not set in local.properties" id "dev.flutter.flutter-plugin-loader" version "1.0.0"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" id "com.android.application" version "7.3.0" apply false
id "org.jetbrains.kotlin.android" version "1.7.10" apply false
}
include ":app"

View File

@@ -5,7 +5,7 @@ import 'package:flutter_localizations/flutter_localizations.dart';
void main() => runApp(const MyApp()); void main() => runApp(const MyApp());
class MyApp extends StatefulWidget { class MyApp extends StatefulWidget {
const MyApp({Key key}) : super(key: key); const MyApp({super.key});
@override @override
MyAppState createState() => MyAppState(); MyAppState createState() => MyAppState();
@@ -104,15 +104,14 @@ class MyAppState extends State<MyApp> {
onChanged: print, onChanged: print,
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39') // Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: 'IT', initialSelection: 'IT',
favorite: const ['+39', 'FR'], //You can set the margin between the flag and the country name to your taste.
countryFilter: const ['IT', 'FR'], margin: const EdgeInsets.symmetric(horizontal: 6),
showFlagDialog: false, comparator: (a, b) => b.name!.compareTo(a.name!),
comparator: (a, b) => b.name.compareTo(a.name),
//Get the country information relevant to the initial selection //Get the country information relevant to the initial selection
onInit: (code) => debugPrint( onInit: (code) => debugPrint("on init ${code?.name} ${code?.dialCode} ${code?.name}"),
"on init ${code.name} ${code.dialCode} ${code.name}"),
), ),
CountryCodePicker( CountryCodePicker(
hideHeaderText: true,
onChanged: print, onChanged: print,
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39') // Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: 'IT', initialSelection: 'IT',

View File

@@ -11,7 +11,7 @@ version: 1.0.0+1
publish_to: none publish_to: none
environment: environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0" sdk: '>=2.17.0 <4.0.0'
dependencies: dependencies:
flutter: flutter:

View File

@@ -1,14 +0,0 @@
// This is a generated file; do not edit or check into version control.
FLUTTER_ROOT=/Users/bezzo/flutter
FLUTTER_APPLICATION_PATH=/Users/bezzo/Desktop/CountryCodePicker
COCOAPODS_PARALLEL_CODE_SIGN=true
FLUTTER_TARGET=lib/main.dart
FLUTTER_BUILD_DIR=build
FLUTTER_BUILD_NAME=3.0.0
FLUTTER_BUILD_NUMBER=3.0.0
EXCLUDED_ARCHS[sdk=iphonesimulator*]=i386
EXCLUDED_ARCHS[sdk=iphoneos*]=armv7
DART_OBFUSCATION=false
TRACK_WIDGET_CREATION=true
TREE_SHAKE_ICONS=false
PACKAGE_CONFIG=.dart_tool/package_config.json

View File

@@ -1,13 +0,0 @@
#!/bin/sh
# This is a generated file; do not edit or check into version control.
export "FLUTTER_ROOT=/Users/bezzo/flutter"
export "FLUTTER_APPLICATION_PATH=/Users/bezzo/Desktop/CountryCodePicker"
export "COCOAPODS_PARALLEL_CODE_SIGN=true"
export "FLUTTER_TARGET=lib/main.dart"
export "FLUTTER_BUILD_DIR=build"
export "FLUTTER_BUILD_NAME=3.0.0"
export "FLUTTER_BUILD_NUMBER=3.0.0"
export "DART_OBFUSCATION=false"
export "TRACK_WIDGET_CREATION=true"
export "TREE_SHAKE_ICONS=false"
export "PACKAGE_CONFIG=.dart_tool/package_config.json"

View File

@@ -1,19 +0,0 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GeneratedPluginRegistrant_h
#define GeneratedPluginRegistrant_h
#import <Flutter/Flutter.h>
NS_ASSUME_NONNULL_BEGIN
@interface GeneratedPluginRegistrant : NSObject
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry;
@end
NS_ASSUME_NONNULL_END
#endif /* GeneratedPluginRegistrant_h */

View File

@@ -1,14 +0,0 @@
//
// Generated file. Do not edit.
//
// clang-format off
#import "GeneratedPluginRegistrant.h"
@implementation GeneratedPluginRegistrant
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {
}
@end

View File

@@ -23,6 +23,7 @@ class CountryCodePicker extends StatefulWidget {
final List<String> favorite; final List<String> favorite;
final TextStyle? textStyle; final TextStyle? textStyle;
final EdgeInsetsGeometry padding; final EdgeInsetsGeometry padding;
final EdgeInsetsGeometry? margin;
final bool showCountryOnly; final bool showCountryOnly;
final InputDecoration searchDecoration; final InputDecoration searchDecoration;
final TextStyle? searchStyle; final TextStyle? searchStyle;
@@ -82,6 +83,9 @@ class CountryCodePicker extends StatefulWidget {
/// Set to true if you want to hide the search part /// Set to true if you want to hide the search part
final bool hideSearch; final bool hideSearch;
/// Set to true if you want to hide the close icon dialog
final bool hideCloseIcon;
/// Set to true if you want to show drop down button /// Set to true if you want to show drop down button
final bool showDropDownButton; final bool showDropDownButton;
@@ -92,6 +96,25 @@ class CountryCodePicker extends StatefulWidget {
/// with customized codes. /// with customized codes.
final List<Map<String, String>> countryList; final List<Map<String, String>> countryList;
final EdgeInsetsGeometry dialogItemPadding;
final EdgeInsetsGeometry searchPadding;
///Use This To Hide The Header Text
final bool hideHeaderText;
///Change The Header Text
final String? headerText;
///Header Text Style
final TextStyle headerTextStyle;
///Header Text Padding
final EdgeInsets topBarPadding;
///Header Text Alignment
final MainAxisAlignment headerAlignment;
const CountryCodePicker({ const CountryCodePicker({
this.onChanged, this.onChanged,
this.onInit, this.onInit,
@@ -99,6 +122,7 @@ class CountryCodePicker extends StatefulWidget {
this.favorite = const [], this.favorite = const [],
this.textStyle, this.textStyle,
this.padding = const EdgeInsets.all(8.0), this.padding = const EdgeInsets.all(8.0),
this.margin,
this.showCountryOnly = false, this.showCountryOnly = false,
this.searchDecoration = const InputDecoration(), this.searchDecoration = const InputDecoration(),
this.searchStyle, this.searchStyle,
@@ -121,12 +145,20 @@ class CountryCodePicker extends StatefulWidget {
this.comparator, this.comparator,
this.countryFilter, this.countryFilter,
this.hideSearch = false, this.hideSearch = false,
this.hideCloseIcon = false,
this.showDropDownButton = false, this.showDropDownButton = false,
this.dialogSize, this.dialogSize,
this.dialogBackgroundColor, this.dialogBackgroundColor,
this.closeIcon = const Icon(Icons.close), this.closeIcon = const Icon(Icons.close),
this.countryList = codes, this.countryList = codes,
this.pickerStyle = PickerStyle.dialog, this.pickerStyle = PickerStyle.dialog,
this.dialogItemPadding = const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
this.searchPadding = const EdgeInsets.symmetric(horizontal: 24),
this.headerAlignment = MainAxisAlignment.spaceBetween,
this.headerText = "Select County",
this.headerTextStyle = const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
this.hideHeaderText = false,
this.topBarPadding = const EdgeInsets.symmetric(vertical: 5.0, horizontal: 20),
Key? key, Key? key,
}) : super(key: key); }) : super(key: key);
@@ -135,22 +167,15 @@ class CountryCodePicker extends StatefulWidget {
State<StatefulWidget> createState() { State<StatefulWidget> createState() {
List<Map<String, String>> jsonList = countryList; List<Map<String, String>> jsonList = countryList;
List<CountryCode> elements = List<CountryCode> elements = jsonList.map((json) => CountryCode.fromJson(json)).toList();
jsonList.map((json) => CountryCode.fromJson(json)).toList();
if (comparator != null) { if (comparator != null) {
elements.sort(comparator); elements.sort(comparator);
} }
if (countryFilter != null && countryFilter!.isNotEmpty) { if (countryFilter != null && countryFilter!.isNotEmpty) {
final uppercaseCustomList = final uppercaseCustomList = countryFilter!.map((criteria) => criteria.toUpperCase()).toList();
countryFilter!.map((criteria) => criteria.toUpperCase()).toList(); elements = elements.where((criteria) => uppercaseCustomList.contains(criteria.code) || uppercaseCustomList.contains(criteria.name) || uppercaseCustomList.contains(criteria.dialCode)).toList();
elements = elements
.where((criteria) =>
uppercaseCustomList.contains(criteria.code) ||
uppercaseCustomList.contains(criteria.name) ||
uppercaseCustomList.contains(criteria.dialCode))
.toList();
} }
return CountryCodePickerState(elements, pickerStyle); return CountryCodePickerState(elements, pickerStyle);
@@ -172,7 +197,7 @@ class CountryCodePickerState extends State<CountryCodePicker> {
internalWidget = InkWell( internalWidget = InkWell(
onTap: pickerStyle == PickerStyle.dialog onTap: pickerStyle == PickerStyle.dialog
? showCountryCodePickerDialog ? showCountryCodePickerDialog
: showCountryCodePickerBottomSheet, : showCountryCodePickerBottomSheet
child: widget.builder!(selectedItem), child: widget.builder!(selectedItem),
); );
} else { } else {
@@ -188,20 +213,14 @@ class CountryCodePickerState extends State<CountryCodePicker> {
direction: Axis.horizontal, direction: Axis.horizontal,
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: <Widget>[ children: <Widget>[
if (widget.showFlagMain != null if (widget.showFlagMain != null ? widget.showFlagMain! : widget.showFlag)
? widget.showFlagMain!
: widget.showFlag)
Flexible( Flexible(
flex: widget.alignLeft ? 0 : 1, flex: widget.alignLeft ? 0 : 1,
fit: widget.alignLeft ? FlexFit.tight : FlexFit.loose, fit: widget.alignLeft ? FlexFit.tight : FlexFit.loose,
child: Container( child: Container(
clipBehavior: widget.flagDecoration == null clipBehavior: widget.flagDecoration == null ? Clip.none : Clip.hardEdge,
? Clip.none
: Clip.hardEdge,
decoration: widget.flagDecoration, decoration: widget.flagDecoration,
margin: widget.alignLeft margin: widget.margin ?? (widget.alignLeft ? const EdgeInsets.only(right: 16.0, left: 8.0) : const EdgeInsets.only(right: 16.0)),
? const EdgeInsets.only(right: 16.0, left: 8.0)
: const EdgeInsets.only(right: 16.0),
child: Image.asset( child: Image.asset(
selectedItem!.flagUri!, selectedItem!.flagUri!,
package: 'country_code_picker', package: 'country_code_picker',
@@ -213,11 +232,8 @@ class CountryCodePickerState extends State<CountryCodePicker> {
Flexible( Flexible(
fit: widget.alignLeft ? FlexFit.tight : FlexFit.loose, fit: widget.alignLeft ? FlexFit.tight : FlexFit.loose,
child: Text( child: Text(
widget.showOnlyCountryWhenClosed widget.showOnlyCountryWhenClosed ? selectedItem!.toCountryStringOnly() : selectedItem.toString(),
? selectedItem!.toCountryStringOnly() style: widget.textStyle ?? Theme.of(context).textTheme.labelLarge,
: selectedItem.toString(),
style: widget.textStyle ??
Theme.of(context).textTheme.labelLarge,
overflow: widget.textOverflow, overflow: widget.textOverflow,
), ),
), ),
@@ -226,9 +242,7 @@ class CountryCodePickerState extends State<CountryCodePicker> {
flex: widget.alignLeft ? 0 : 1, flex: widget.alignLeft ? 0 : 1,
fit: widget.alignLeft ? FlexFit.tight : FlexFit.loose, fit: widget.alignLeft ? FlexFit.tight : FlexFit.loose,
child: Padding( child: Padding(
padding: widget.alignLeft padding: (widget.alignLeft ? const EdgeInsets.only(right: 16.0, left: 8.0) : const EdgeInsets.only(right: 16.0)),
? const EdgeInsets.only(right: 16.0, left: 8.0)
: const EdgeInsets.only(right: 16.0),
child: Icon( child: Icon(
Icons.arrow_drop_down, Icons.arrow_drop_down,
color: Colors.grey, color: Colors.grey,
@@ -259,11 +273,9 @@ class CountryCodePickerState extends State<CountryCodePicker> {
if (widget.initialSelection != null) { if (widget.initialSelection != null) {
selectedItem = elements.firstWhere( selectedItem = elements.firstWhere(
(criteria) => (criteria) =>
(criteria.code!.toUpperCase() == (criteria.code!.toUpperCase() == widget.initialSelection!.toUpperCase()) ||
widget.initialSelection!.toUpperCase()) ||
(criteria.dialCode == widget.initialSelection) || (criteria.dialCode == widget.initialSelection) ||
(criteria.name!.toUpperCase() == (criteria.name!.toUpperCase() == widget.initialSelection!.toUpperCase()),
widget.initialSelection!.toUpperCase()),
orElse: () => elements[0]); orElse: () => elements[0]);
} else { } else {
selectedItem = elements[0]; selectedItem = elements[0];
@@ -279,11 +291,9 @@ class CountryCodePickerState extends State<CountryCodePicker> {
if (widget.initialSelection != null) { if (widget.initialSelection != null) {
selectedItem = elements.firstWhere( selectedItem = elements.firstWhere(
(item) => (item) =>
(item.code!.toUpperCase() == (item.code!.toUpperCase() == widget.initialSelection!.toUpperCase()) ||
widget.initialSelection!.toUpperCase()) ||
(item.dialCode == widget.initialSelection) || (item.dialCode == widget.initialSelection) ||
(item.name!.toUpperCase() == (item.name!.toUpperCase() == widget.initialSelection!.toUpperCase()),
widget.initialSelection!.toUpperCase()),
orElse: () => elements[0]); orElse: () => elements[0]);
} else { } else {
selectedItem = elements[0]; selectedItem = elements[0];
@@ -291,10 +301,7 @@ class CountryCodePickerState extends State<CountryCodePicker> {
favoriteElements = elements favoriteElements = elements
.where((item) => .where((item) =>
widget.favorite.firstWhereOrNull((criteria) => widget.favorite.firstWhereOrNull((criteria) => item.code!.toUpperCase() == criteria.toUpperCase() || item.dialCode == criteria || item.name!.toUpperCase() == criteria.toUpperCase()) !=
item.code!.toUpperCase() == criteria.toUpperCase() ||
item.dialCode == criteria ||
item.name!.toUpperCase() == criteria.toUpperCase()) !=
null) null)
.toList(); .toList();
} }
@@ -317,11 +324,19 @@ class CountryCodePickerState extends State<CountryCodePicker> {
showFlag: widget.showFlagDialog ?? widget.showFlag, showFlag: widget.showFlagDialog ?? widget.showFlag,
flagWidth: widget.flagWidth, flagWidth: widget.flagWidth,
size: widget.dialogSize, size: widget.dialogSize,
headerAlignment: widget.headerAlignment,
headerText: widget.headerText,
headerTextStyle: widget.headerTextStyle,
hideHeaderText: widget.hideHeaderText,
topBarPadding: widget.topBarPadding,
backgroundColor: widget.dialogBackgroundColor, backgroundColor: widget.dialogBackgroundColor,
barrierColor: widget.barrierColor, barrierColor: widget.barrierColor,
hideSearch: widget.hideSearch, hideSearch: widget.hideSearch,
hideCloseIcon: widget.hideCloseIcon,
closeIcon: widget.closeIcon, closeIcon: widget.closeIcon,
flagDecoration: widget.flagDecoration, flagDecoration: widget.flagDecoration,
dialogItemPadding: widget.dialogItemPadding,
searchPadding: widget.searchPadding,
), ),
), ),
), ),

View File

@@ -1,5 +1,7 @@
import 'package:collection/collection.dart' show IterableExtension; import 'package:collection/collection.dart' show IterableExtension;
import 'package:diacritic/diacritic.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show kDebugMode;
import 'country_codes.dart'; import 'country_codes.dart';
import 'country_localizations.dart'; import 'country_localizations.dart';
@@ -39,6 +41,15 @@ class CountryCode {
return CountryCode.fromJson(jsonCode!); return CountryCode.fromJson(jsonCode!);
} }
static CountryCode? tryFromCountryCode(String countryCode) {
try {
return CountryCode.fromCountryCode(countryCode);
} catch (e) {
if (kDebugMode) print('Failed to recognize country from countryCode: $countryCode');
return null;
}
}
factory CountryCode.fromDialCode(String dialCode) { factory CountryCode.fromDialCode(String dialCode) {
final Map<String, String>? jsonCode = codes.firstWhereOrNull( final Map<String, String>? jsonCode = codes.firstWhereOrNull(
(code) => code['dial_code'] == dialCode, (code) => code['dial_code'] == dialCode,
@@ -46,14 +57,24 @@ class CountryCode {
return CountryCode.fromJson(jsonCode!); return CountryCode.fromJson(jsonCode!);
} }
static CountryCode? tryFromDialCode(String dialCode) {
try {
return CountryCode.fromDialCode(dialCode);
} catch (e) {
if (kDebugMode) print('Failed to recognize country from dialCode: $dialCode');
return null;
}
}
CountryCode localize(BuildContext context) { CountryCode localize(BuildContext context) {
final nam = CountryLocalizations.of(context)?.translate(code) ?? name;
return this return this
..name = CountryLocalizations.of(context)?.translate(code) ?? name; ..name = nam == null? name : removeDiacritics(nam);
} }
factory CountryCode.fromJson(Map<String, dynamic> json) { factory CountryCode.fromJson(Map<String, dynamic> json) {
return CountryCode( return CountryCode(
name: json['name'], name: removeDiacritics(json['name']),
code: json['code'], code: json['code'],
dialCode: json['dial_code'], dialCode: json['dial_code'],
flagUri: 'flags/${json['code'].toLowerCase()}.png', flagUri: 'flags/${json['code'].toLowerCase()}.png',

File diff suppressed because it is too large Load Diff

View File

@@ -119,7 +119,7 @@ class _CountryLocalizationsDelegate
@override @override
Future<CountryLocalizations> load(Locale locale) async { Future<CountryLocalizations> load(Locale locale) async {
CountryLocalizations localizations = CountryLocalizations(locale); CountryLocalizations localizations = CountryLocalizations(const Locale('en'));//locale);
await localizations.load(); await localizations.load();
return localizations; return localizations;
} }

View File

@@ -10,6 +10,7 @@ class SelectionDialog extends StatefulWidget {
final InputDecoration searchDecoration; final InputDecoration searchDecoration;
final TextStyle? searchStyle; final TextStyle? searchStyle;
final TextStyle? textStyle; final TextStyle? textStyle;
final TextStyle headerTextStyle;
final BoxDecoration? boxDecoration; final BoxDecoration? boxDecoration;
final WidgetBuilder? emptySearchBuilder; final WidgetBuilder? emptySearchBuilder;
final bool? showFlag; final bool? showFlag;
@@ -17,7 +18,12 @@ class SelectionDialog extends StatefulWidget {
final Decoration? flagDecoration; final Decoration? flagDecoration;
final Size? size; final Size? size;
final bool hideSearch; final bool hideSearch;
final bool hideCloseIcon;
final Icon? closeIcon; final Icon? closeIcon;
final bool hideHeaderText;
final String? headerText;
final EdgeInsets topBarPadding;
final MainAxisAlignment headerAlignment;
/// Background color of SelectionDialog /// Background color of SelectionDialog
final Color? backgroundColor; final Color? backgroundColor;
@@ -28,15 +34,24 @@ class SelectionDialog extends StatefulWidget {
/// elements passed as favorite /// elements passed as favorite
final List<CountryCode> favoriteElements; final List<CountryCode> favoriteElements;
final EdgeInsetsGeometry dialogItemPadding;
final EdgeInsetsGeometry searchPadding;
SelectionDialog( SelectionDialog(
this.elements, this.elements,
this.favoriteElements, { this.favoriteElements, {
Key? key, Key? key,
this.showCountryOnly, this.showCountryOnly,
required this.hideHeaderText,
this.emptySearchBuilder, this.emptySearchBuilder,
required this.headerAlignment,
required this.headerTextStyle,
InputDecoration searchDecoration = const InputDecoration(), InputDecoration searchDecoration = const InputDecoration(),
this.searchStyle, this.searchStyle,
this.textStyle, this.textStyle,
required this.topBarPadding,
this.headerText,
this.boxDecoration, this.boxDecoration,
this.showFlag, this.showFlag,
this.flagDecoration, this.flagDecoration,
@@ -45,10 +60,11 @@ class SelectionDialog extends StatefulWidget {
this.backgroundColor, this.backgroundColor,
this.barrierColor, this.barrierColor,
this.hideSearch = false, this.hideSearch = false,
this.hideCloseIcon = false,
this.closeIcon, this.closeIcon,
}) : searchDecoration = searchDecoration.prefixIcon == null this.dialogItemPadding = const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
? searchDecoration.copyWith(prefixIcon: const Icon(Icons.search)) this.searchPadding = const EdgeInsets.symmetric(horizontal: 24),
: searchDecoration, }) : searchDecoration = searchDecoration.prefixIcon == null ? searchDecoration.copyWith(prefixIcon: const Icon(Icons.search)) : searchDecoration,
super(key: key); super(key: key);
@override @override
@@ -65,8 +81,7 @@ class _SelectionDialogState extends State<SelectionDialog> {
child: Container( child: Container(
clipBehavior: Clip.hardEdge, clipBehavior: Clip.hardEdge,
width: widget.size?.width ?? MediaQuery.of(context).size.width, width: widget.size?.width ?? MediaQuery.of(context).size.width,
height: height: widget.size?.height ?? MediaQuery.of(context).size.height * 0.85,
widget.size?.height ?? MediaQuery.of(context).size.height * 0.85,
decoration: widget.boxDecoration ?? decoration: widget.boxDecoration ??
BoxDecoration( BoxDecoration(
color: widget.backgroundColor ?? Colors.white, color: widget.backgroundColor ?? Colors.white,
@@ -84,15 +99,31 @@ class _SelectionDialogState extends State<SelectionDialog> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
IconButton( Padding(
padding: const EdgeInsets.all(0), padding:!widget.hideHeaderText? widget.topBarPadding: EdgeInsets.zero,
iconSize: 20, child: Row(
icon: widget.closeIcon!, mainAxisAlignment: widget.headerAlignment,
onPressed: () => Navigator.pop(context), children: [
!widget.hideHeaderText && widget.headerText != null
? Text(
widget.headerText!,
overflow: TextOverflow.fade,
style: widget.headerTextStyle,
)
: const SizedBox.shrink(),
if (!widget.hideCloseIcon)
IconButton(
padding: const EdgeInsets.all(0),
iconSize: 20,
icon: widget.closeIcon!,
onPressed: () => Navigator.pop(context),
),
],
),
), ),
if (!widget.hideSearch) if (!widget.hideSearch)
Padding( Padding(
padding: const EdgeInsets.symmetric(horizontal: 24), padding: widget.searchPadding,
child: TextField( child: TextField(
style: widget.searchStyle, style: widget.searchStyle,
decoration: widget.searchDecoration, decoration: widget.searchDecoration,
@@ -107,28 +138,28 @@ class _SelectionDialogState extends State<SelectionDialog> {
: Column( : Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
...widget.favoriteElements.map( ...widget.favoriteElements.map((f) => InkWell(
(f) => SimpleDialogOption( onTap: () {
child: _buildOption(f),
onPressed: () {
_selectItem(f); _selectItem(f);
}, },
), child: Padding(
), padding: widget.dialogItemPadding,
child: _buildOption(f),
))),
const Divider(), const Divider(),
], ],
), ),
if (filteredElements.isEmpty) if (filteredElements.isEmpty)
_buildEmptySearchWidget(context) _buildEmptySearchWidget(context)
else else
...filteredElements.map( ...filteredElements.map((e) => InkWell(
(e) => SimpleDialogOption( onTap: () {
child: _buildOption(e),
onPressed: () {
_selectItem(e); _selectItem(e);
}, },
), child: Padding(
), padding: widget.dialogItemPadding,
child: _buildOption(e),
))),
], ],
), ),
), ),
@@ -146,10 +177,11 @@ class _SelectionDialogState extends State<SelectionDialog> {
if (widget.showFlag!) if (widget.showFlag!)
Flexible( Flexible(
child: Container( child: Container(
margin: const EdgeInsets.only(right: 16.0), margin: Directionality.of(context) == TextDirection.ltr // Here Adding padding depending on the locale language direction
? const EdgeInsets.only(right: 16.0)
: const EdgeInsets.only(left: 16.0),
decoration: widget.flagDecoration, decoration: widget.flagDecoration,
clipBehavior: clipBehavior: widget.flagDecoration == null ? Clip.none : Clip.hardEdge,
widget.flagDecoration == null ? Clip.none : Clip.hardEdge,
child: Image.asset( child: Image.asset(
e.flagUri!, e.flagUri!,
package: 'country_code_picker', package: 'country_code_picker',
@@ -160,9 +192,7 @@ class _SelectionDialogState extends State<SelectionDialog> {
Expanded( Expanded(
flex: 4, flex: 4,
child: Text( child: Text(
widget.showCountryOnly! widget.showCountryOnly! ? e.toCountryStringOnly() : e.toLongString(),
? e.toCountryStringOnly()
: e.toLongString(),
overflow: TextOverflow.fade, overflow: TextOverflow.fade,
style: widget.textStyle, style: widget.textStyle,
), ),
@@ -178,8 +208,7 @@ class _SelectionDialogState extends State<SelectionDialog> {
} }
return Center( return Center(
child: Text(CountryLocalizations.of(context)?.translate('no_country') ?? child: Text(CountryLocalizations.of(context)?.translate('no_country') ?? 'No country found'),
'No country found'),
); );
} }
@@ -192,12 +221,7 @@ class _SelectionDialogState extends State<SelectionDialog> {
void _filterElements(String s) { void _filterElements(String s) {
s = s.toUpperCase(); s = s.toUpperCase();
setState(() { setState(() {
filteredElements = widget.elements filteredElements = widget.elements.where((e) => e.code!.contains(s) || e.dialCode!.contains(s) || e.name!.toUpperCase().contains(s)).toList();
.where((e) =>
e.code!.contains(s) ||
e.dialCode!.contains(s) ||
e.name!.toUpperCase().contains(s))
.toList();
}); });
} }

View File

@@ -1,17 +1,18 @@
name: country_code_picker name: country_code_picker
description: A flutter package for showing a country code selector. In addition it gives the possibility to select a list of favorites countries, as well as to search using a simple searchbox description: A flutter package for showing a country code selector. In addition it gives the possibility to select a list of favorites countries, as well as to search using a simple searchbox
version: 3.0.0 version: 3.1.0
homepage: https://github.com/chandrabezzo/CountryCodePicker homepage: https://github.com/chandrabezzo/CountryCodePicker
repository: https://github.com/chandrabezzo/CountryCodePicker repository: https://github.com/chandrabezzo/CountryCodePicker
issue_tracker: https://github.com/imtoori/CountryCodePicker/issues issue_tracker: https://github.com/imtoori/CountryCodePicker/issues
environment: environment:
sdk: '>=2.12.0 <3.0.0' sdk: '>=2.17.0 <4.0.0'
dependencies: dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
collection: ^1.15.0 collection: ^1.15.0
diacritic: ^0.1.5
flutter: flutter:
assets: assets:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 42 KiB