Merge pull request 'feature/docsms/DOCSMS-#Implement-Auto-Received-Document-API' (#13) from feature/docsms/DOCSMS-#Implement-Auto-Received-Document-API into develop

Reviewed-on: http://git.agusandelnorte.gov.ph:3000/SoftwareDevelopmentSection/unit2-null-safety-repository/pulls/13
This commit is contained in:
rodolfobacuinjr
2023-06-07 00:17:30 +08:00
143 changed files with 28088 additions and 6391 deletions
+83 -56
View File
@@ -8,12 +8,12 @@
/* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
28FEB91C01FFFF1F3AF03958 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2946B4F99A9B9A85D9A4DC4F /* Pods_Runner.framework */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
EC92729992AEB29D54ECE4AD /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2E04E4456FC969F34935C233 /* Pods_Runner.framework */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -32,14 +32,13 @@
/* Begin PBXFileReference section */
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
24CA4A0209E683A311335098 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
2946B4F99A9B9A85D9A4DC4F /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
2E04E4456FC969F34935C233 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
74181747FCF55E0339265087 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
7435055C04EA907D4DF9DEFB /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
4AF585336026D31B5D98E4A0 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
9275E2137A20FFFC26EB3114 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -47,6 +46,7 @@
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
D017F5E329769A1D85398300 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -54,7 +54,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
28FEB91C01FFFF1F3AF03958 /* Pods_Runner.framework in Frameworks */,
EC92729992AEB29D54ECE4AD /* Pods_Runner.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -64,13 +64,21 @@
53E3B75A4BA5D03DDDC74903 /* Pods */ = {
isa = PBXGroup;
children = (
74181747FCF55E0339265087 /* Pods-Runner.debug.xcconfig */,
7435055C04EA907D4DF9DEFB /* Pods-Runner.release.xcconfig */,
24CA4A0209E683A311335098 /* Pods-Runner.profile.xcconfig */,
9275E2137A20FFFC26EB3114 /* Pods-Runner.debug.xcconfig */,
4AF585336026D31B5D98E4A0 /* Pods-Runner.release.xcconfig */,
D017F5E329769A1D85398300 /* Pods-Runner.profile.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
661D3BDF849DD3A816B38E4C /* Frameworks */ = {
isa = PBXGroup;
children = (
2E04E4456FC969F34935C233 /* Pods_Runner.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
9740EEB11CF90186004384FC /* Flutter */ = {
isa = PBXGroup;
children = (
@@ -89,7 +97,7 @@
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
53E3B75A4BA5D03DDDC74903 /* Pods */,
B81885F5B040F93E6F30E902 /* Frameworks */,
661D3BDF849DD3A816B38E4C /* Frameworks */,
);
sourceTree = "<group>";
};
@@ -116,14 +124,6 @@
path = Runner;
sourceTree = "<group>";
};
B81885F5B040F93E6F30E902 /* Frameworks */ = {
isa = PBXGroup;
children = (
2946B4F99A9B9A85D9A4DC4F /* Pods_Runner.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -131,14 +131,14 @@
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
961512EDE7FE1573CFAF92FB /* [CP] Check Pods Manifest.lock */,
DF69B491CB3FE4E427DD5727 /* [CP] Check Pods Manifest.lock */,
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
CC94AAA4981E9E5E5B1BC9E4 /* [CP] Embed Pods Frameworks */,
D82405DC020597FCACED184E /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
@@ -212,7 +212,39 @@
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
};
961512EDE7FE1573CFAF92FB /* [CP] Check Pods Manifest.lock */ = {
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Run Script";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
D82405DC020597FCACED184E /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
DF69B491CB3FE4E427DD5727 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
@@ -234,38 +266,6 @@
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Run Script";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
CC94AAA4981E9E5E5B1BC9E4 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -356,18 +356,27 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 2WLSMMLG6W;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "uniT-App";
MARKETING_VERSION = "1.0.0 ";
PRODUCT_BUNDLE_IDENTIFIER = "unit-app";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO;
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
VERSIONING_SYSTEM = "apple-generic";
};
name = Profile;
@@ -485,19 +494,28 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 2WLSMMLG6W;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "uniT-App";
MARKETING_VERSION = "1.0.0 ";
PRODUCT_BUNDLE_IDENTIFIER = "unit-app";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO;
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
@@ -508,18 +526,27 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 2WLSMMLG6W;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "uniT-App";
MARKETING_VERSION = "1.0.0 ";
PRODUCT_BUNDLE_IDENTIFIER = "unit-app";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO;
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
+4 -1
View File
@@ -2,9 +2,12 @@
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
location = "container:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
+8 -9
View File
@@ -26,6 +26,14 @@
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Always and when in use!</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Can I have location always?</string>
<key>NSLocationUsageDescription</key>
<string>Older devices need location.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Need location when in use</string>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchStoryboardName</key>
@@ -47,14 +55,5 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<!-- Permission options for the `location` group -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>Need location when in use</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Always and when in use!</string>
<key>NSLocationUsageDescription</key>
<string>Older devices need location.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Can I have location always?</string>
</dict>
</plist>
+28
View File
@@ -0,0 +1,28 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/sevices/docsms/docsms_service.dart';
import '../../model/docsms/document.dart';
part 'docsms_event.dart';
part 'docsms_state.dart';
class DocsmsBloc extends Bloc<DocsmsEvent, DocsmsState> {
DocsmsBloc() : super(DocsmsInitial()) {
Document? document;
on<LoadDocument>((event, emit)async {
emit(DocSmsLoadingState());
try {
document = await AutoReceiveDocumentServices.instance.getDocument(event.documentId);
if(document != null){
emit(DocumentLoaded(document: document!));
}else{
emit(const DocSmsErrorState(message: "Invalid Qr code"));
}
} catch (e) {
emit(DocSmsErrorState(message: e.toString()));
}
});
}
}
+15
View File
@@ -0,0 +1,15 @@
part of 'docsms_bloc.dart';
abstract class DocsmsEvent extends Equatable {
const DocsmsEvent();
@override
List<Object> get props => [];
}
class LoadDocument extends DocsmsEvent{
final String documentId;
const LoadDocument({required this.documentId});
@override
List<Object> get props => [];
}
+28
View File
@@ -0,0 +1,28 @@
part of 'docsms_bloc.dart';
abstract class DocsmsState extends Equatable {
const DocsmsState();
@override
List<Object> get props => [];
}
class DocsmsInitial extends DocsmsState {}
class DocSmsLoadingState extends DocsmsState{
}
class DocumentLoaded extends DocsmsState{
final Document document;
const DocumentLoaded({required this.document});
@override
List<Object> get props => [document];
}
class DocSmsErrorState extends DocsmsState{
final String message;
const DocSmsErrorState({required this.message});
@override
List<Object> get props => [message];
}
+119 -6
View File
@@ -8,15 +8,128 @@ part 'education_state.dart';
class EducationBloc extends Bloc<EducationEvent, EducationState> {
List<EducationalBackground> educationalBackgrounds = [];
List<School> schools = [];
List<Course> programs = [];
List<Honor> honors = [];
EducationBloc() : super(EducationInitial()) {
on<GetEducationalBackground>((event, emit) async {
emit(EducationalBackgroundLoadingState());
try {
List<EducationalBackground> educations = await EducationService.instace
.getEducationalBackground(event.profileId, event.token);
educationalBackgrounds = educations;
emit(EducationalBackgroundLoadedState(
educationalBackground: educationalBackgrounds));
try {
if (educationalBackgrounds.isEmpty) {
List<EducationalBackground> educations = await EducationService
.instace
.getEducationalBackground(event.profileId, event.token);
educationalBackgrounds = educations;
emit(EducationalBackgroundLoadedState(
educationalBackground: educationalBackgrounds));
} else {
emit(EducationalBackgroundLoadedState(
educationalBackground: educationalBackgrounds));
}
} catch (e) {
emit(EducationalBackgroundErrorState(message: e.toString()));
}
});
//// SHOW ADD FORM
on<ShowAddEducationForm>((event, emit) async {
emit(EducationalBackgroundLoadingState());
try {
if (schools.isEmpty) {
List<School> newSchools = await EducationService.instace.getSchools();
schools = newSchools;
}
if (programs.isEmpty) {
List<Course> newPrograms =
await EducationService.instace.getPrograms();
programs = newPrograms;
}
if (honors.isEmpty) {
List<Honor> newHonors = await EducationService.instace.getHonors();
honors = newHonors;
}
emit(AddEducationState(
schools: schools, programs: programs, honors: honors));
} catch (e) {
emit(EducationalBackgroundErrorState(message: e.toString()));
}
});
////Add
on<AddEducation>((event, emit) async {
Map<dynamic, dynamic> status = await EducationService.instace.add(
honors: event.honors,
educationalBackground: event.educationalBackground,
token: event.token,
profileId: event.profileId);
if (status['success']) {
EducationalBackground educationalBackground =
EducationalBackground.fromJson(status['data']);
educationalBackgrounds.add(educationalBackground);
emit(EducationAddedState(response: status));
} else {
emit(EducationAddedState(response: status));
}
});
////Update
on<UpdateEducation>((event, emit) async {
Map<dynamic, dynamic> status = await EducationService.instace.edit(
honors: event.honors,
educationalBackground: event.educationalBackground,
token: event.token,
profileId: event.profileId);
if (status['success']) {
educationalBackgrounds.removeWhere((element) => event.educationalBackground.id == element.id);
EducationalBackground educationalBackground =
EducationalBackground.fromJson(status['data']);
educationalBackgrounds.add(educationalBackground);
emit(EditedEducationState(response: status));
} else {
emit(EditedEducationState(response: status));
}
});
////LOAD
on<LoadEducations>((event, emit) {
emit(EducationalBackgroundLoadedState(
educationalBackground: educationalBackgrounds));
});
//// SHOW EDIT FORM
on<ShowEditEducationForm>((event, emit) async {
try {
if (schools.isEmpty) {
List<School> newSchools = await EducationService.instace.getSchools();
schools = newSchools;
}
if (programs.isEmpty) {
List<Course> newPrograms =
await EducationService.instace.getPrograms();
programs = newPrograms;
}
if (honors.isEmpty) {
List<Honor> newHonors = await EducationService.instace.getHonors();
honors = newHonors;
}
emit(EditEducationState(
schools: schools,
programs: programs,
honors: honors,
educationalBackground: event.educationalBackground));
} catch (e) {
emit(EducationalBackgroundErrorState(message: e.toString()));
}
});
////delete
on<DeleteEducation>((event, emit) async {
try {
final bool success = await EducationService.instace.delete(
profileId: event.profileId,
token: event.token,
educationalBackground: event.educationalBackground);
if (success) {
educationalBackgrounds.removeWhere(
(element) => element.id == event.educationalBackground.id);
emit(EducationDeletedState(success: success));
} else {
emit(EducationDeletedState(success: success));
}
} catch (e) {
emit(EducationalBackgroundErrorState(message: e.toString()));
}
@@ -6,10 +6,60 @@ abstract class EducationEvent extends Equatable {
@override
List<Object> get props => [];
}
class GetEducationalBackground extends EducationEvent{
class GetEducationalBackground extends EducationEvent {
final int profileId;
final String token;
const GetEducationalBackground({required this.profileId, required this.token});
@override
List<Object> get props => [profileId,token];
const GetEducationalBackground(
{required this.profileId, required this.token});
@override
List<Object> get props => [profileId, token];
}
////show add form
class ShowAddEducationForm extends EducationEvent {}
////show edit form
class ShowEditEducationForm extends EducationEvent {
final EducationalBackground educationalBackground;
final int profileId;
final String token;
const ShowEditEducationForm({required this.educationalBackground,required this.profileId, required this.token});
@override
List<Object> get props => [educationalBackground];
}
////load
class LoadEducations extends EducationEvent {}
////add
class AddEducation extends EducationEvent {
final List<Honor> honors;
final EducationalBackground educationalBackground;
final int profileId;
final String token;
const AddEducation(
{required this.educationalBackground,
required this.profileId,
required this.token, required this.honors});
@override
List<Object> get props => [educationalBackground, profileId, token];
}
////update education
class UpdateEducation extends EducationEvent{
final List<Honor> honors;
final EducationalBackground educationalBackground;
final int profileId;
final String token;
const UpdateEducation(
{required this.educationalBackground,
required this.profileId,
required this.token,required this.honors});
@override
List<Object> get props => [educationalBackground, profileId, token];
}
////delete
class DeleteEducation extends EducationEvent{
final int profileId;
final String token;
final EducationalBackground educationalBackground;
const DeleteEducation({required this.educationalBackground, required this.profileId, required this.token});
@override
List<Object> get props => [educationalBackground, profileId, token];
}
@@ -2,28 +2,73 @@ part of 'education_bloc.dart';
abstract class EducationState extends Equatable {
const EducationState();
@override
List<Object> get props => [];
}
class EducationInitial extends EducationState {}
class EducationalBackgroundLoadedState extends EducationState{
class EducationalBackgroundLoadedState extends EducationState {
final List<EducationalBackground> educationalBackground;
const EducationalBackgroundLoadedState({required this.educationalBackground});
@override
@override
List<Object> get props => [educationalBackground];
}
class EducationalBackgroundErrorState extends EducationState{
class EducationalBackgroundErrorState extends EducationState {
final String message;
const EducationalBackgroundErrorState({required this.message});
@override
@override
List<Object> get props => [message];
}
class EducationalBackgroundLoadingState extends EducationState{
class EducationalBackgroundLoadingState extends EducationState {}
////Add
class AddEducationState extends EducationState {
final List<School> schools;
final List<Course> programs;
final List<Honor> honors;
const AddEducationState(
{required this.honors, required this.programs, required this.schools});
@override
List<Object> get props => [schools, programs, honors];
}
////Edit
class EditEducationState extends EducationState {
final EducationalBackground educationalBackground;
final List<School> schools;
final List<Course> programs;
final List<Honor> honors;
const EditEducationState({
required this.educationalBackground,
required this.honors,
required this.programs,
required this.schools,
});
}
//// Added State
class EducationAddedState extends EducationState {
final Map<dynamic, dynamic> response;
const EducationAddedState({required this.response});
@override
List<Object> get props => [response];
}
//// Edited State
class EditedEducationState extends EducationState {
final Map<dynamic, dynamic> response;
const EditedEducationState({required this.response});
@override
List<Object> get props => [response];
}
////deleted State
class EducationDeletedState extends EducationState {
final bool success;
const EducationDeletedState({required this.success});
@override
List<Object> get props => [success];
}
@@ -14,18 +14,14 @@ part 'eligibility_state.dart';
class EligibilityBloc extends Bloc<EligibilityEvent, EligibilityState> {
EligibilityBloc() : super(EligibilityInitial()) {
List<Country>? globalCountries;
List<Region>? globalRegions;
List<Country> globalCountries = [];
List<Region> globalRegions = [];
List<Eligibility> globalEligibilities = [];
List<EligibityCert> eligibilities = [];
//// LOAD ELIGIBILTY
on<LoadEligibility>((event, emit) {
emit(EligibilityLoadingState());
if (eligibilities.isEmpty) {
GetEligibilities(profileId: event.profileId!, token: event.token!);
} else {
emit(EligibilityLoaded(eligibilities: eligibilities));
}
emit(EligibilityLoaded(eligibilities: eligibilities));
});
//// DELETE
@@ -36,7 +32,7 @@ class EligibilityBloc extends Bloc<EligibilityEvent, EligibilityState> {
profileId: int.parse(event.profileId),
token: event.token);
if (success) {
eligibilities.removeWhere(
eligibilities.removeWhere(
((EligibityCert element) => element.id == event.eligibilityId));
emit(DeletedState(
success: success,
@@ -67,11 +63,11 @@ class EligibilityBloc extends Bloc<EligibilityEvent, EligibilityState> {
//// SHOW EDIT FORM
on<ShowEditEligibilityForm>((event, emit) async {
try {
if (globalCountries == null) {
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
if (globalRegions == null) {
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
@@ -84,13 +80,12 @@ class EligibilityBloc extends Bloc<EligibilityEvent, EligibilityState> {
(Eligibility eligibility) =>
event.eligibityCert.eligibility!.id == eligibility.id);
bool? isOverseas = event.eligibityCert.overseas;
Country currentCountry = globalCountries!.firstWhere(
(Country country) =>
event.eligibityCert.examAddress!.country!.code == country.code);
Country currentCountry = globalCountries.firstWhere((Country country) =>
event.eligibityCert.examAddress!.country!.code == country.code);
if (event.eligibityCert.examAddress?.cityMunicipality?.province
?.region !=
null) {
Region currrentRegion = globalRegions!.firstWhere((Region region) =>
Region currrentRegion = globalRegions.firstWhere((Region region) =>
event.eligibityCert.examAddress!.cityMunicipality!.province!
.region!.code ==
region.code);
@@ -117,8 +112,8 @@ class EligibilityBloc extends Bloc<EligibilityEvent, EligibilityState> {
cities: cities,
isOverseas: isOverseas!,
eligibityCert: event.eligibityCert,
countries: globalCountries!,
regions: globalRegions!,
countries: globalCountries,
regions: globalRegions,
eligibilities: globalEligibilities));
} else {
emit(EditEligibilityState(
@@ -131,8 +126,8 @@ class EligibilityBloc extends Bloc<EligibilityEvent, EligibilityState> {
currentEligibility: currentEligibility,
isOverseas: isOverseas!,
eligibityCert: event.eligibityCert,
countries: globalCountries!,
regions: globalRegions!,
countries: globalCountries,
regions: globalRegions,
eligibilities: globalEligibilities));
}
} catch (e) {
@@ -164,24 +159,28 @@ class EligibilityBloc extends Bloc<EligibilityEvent, EligibilityState> {
//// SHOW ADD FORM
on<ShowAddEligibilityForm>((event, emit) async {
emit(EligibilityLoadingState());
if (globalRegions == null) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
if (globalEligibilities.isEmpty) {
List<Eligibility> eligibilities =
await ProfileUtilities.instance.getEligibilities();
globalEligibilities = eligibilities;
}
if (globalCountries == null) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
try {
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
if (globalEligibilities.isEmpty) {
List<Eligibility> eligibilities =
await ProfileUtilities.instance.getEligibilities();
globalEligibilities = eligibilities;
}
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
emit(AddEligibilityState(
eligibilities: globalEligibilities,
regions: globalRegions!,
countries: globalCountries!));
emit(AddEligibilityState(
eligibilities: globalEligibilities,
regions: globalRegions,
countries: globalCountries));
} catch (e) {
emit(EligibilityErrorState(message: e.toString()));
}
});
//// ADD
@@ -38,9 +38,8 @@ class UpdateEligibility extends EligibilityEvent{
List<Object> get props =>[eligibityCert,profileId,token,oldEligibility];
}
class LoadEligibility extends EligibilityEvent {
final int? profileId;
final String? token;
const LoadEligibility({ this.profileId, this.token});
const LoadEligibility();
@override
List<Object> get props => [];
}
+106 -6
View File
@@ -9,14 +9,114 @@ part 'family_state.dart';
class FamilyBloc extends Bloc<FamilyEvent, FamilyState> {
FamilyBloc() : super(FamilyInitial()) {
List<FamilyBackground> families = [];
on<GetFamilies>((event, emit) async{
List<FamilyBackground> families = [];
on<GetFamilies>((event, emit) async {
emit(FamilyLoadingState());
try{
List<FamilyBackground> family = await FamilyService.instance.getFamilies(event.profileId, event.token);
families = family;
try {
if (families.isEmpty) {
List<FamilyBackground> family = await FamilyService.instance
.getFamilies(event.profileId, event.token);
families = family;
}
emit(FamilyLoaded(families: families));
}catch(e){
} catch (e) {
emit(FamilyErrorState(message: e.toString()));
}
});
////Load
on<LoadFamily>((event, emit) {
emit(FamilyLoaded(families: families));
});
////Add Family
on<AddFamily>((event, emit) async {
try {
emit(FamilyLoadingState());
Map<dynamic, dynamic> status = await FamilyService.instance.add(
family: event.familyBackground,
relationshipId: event.relationshipId,
profileId: event.profileId,
token: event.token);
if (status['success']) {
FamilyBackground familyBackground =
FamilyBackground.fromJson(status['data']);
families.add(familyBackground);
emit(FamilyAddedState(response: status));
} else {
emit(FamilyAddedState(response: status));
}
} catch (e) {
emit(FamilyErrorState(message: e.toString()));
}
});
//// Add Emergency
on<AddEmergencyEvent>((event, emit) async {
try {
emit(FamilyLoadingState());
Map<dynamic, dynamic> status = await FamilyService.instance
.addEmergency(
requestType: event.requestType,
relatedPersonId: event.relatedPersonId,
numberMail: event.numberMail,
contactInfoId: event.contactInfoId,
profileId: event.profileId,
token: event.token);
if (status['success']) {
families.removeWhere(
(element) => element.relatedPerson!.id == event.relatedPersonId);
FamilyBackground familyBackground =
FamilyBackground.fromJson(status['data']);
families.add(familyBackground);
emit(EmergencyContactEditedState(response: status));
} else {
emit(EmergencyContactEditedState(response: status));
}
} catch (e) {
emit(FamilyErrorState(message: e.toString()));
}
});
////update
on<Updatefamily>((event, emit) async {
try {
emit(FamilyLoadingState());
Map<dynamic, dynamic> status = await FamilyService.instance.update(
family: event.familyBackground,
relationshipId: event.relationshipId,
profileId: event.profileId,
token: event.token);
if (status['success']) {
families.removeWhere((element) =>
element.relatedPerson!.id ==
event.familyBackground.relatedPerson!.id);
FamilyBackground familyBackground =
FamilyBackground.fromJson(status['data']);
families.add(familyBackground);
emit(FamilyEditedState(response: status));
} else {
emit(FamilyEditedState(response: status));
}
} catch (e) {
emit(FamilyErrorState(message: e.toString()));
}
});
////Delete
on<DeleteFamily>((event, emit) async {
try {
final bool success = await FamilyService.instance.delete(
personRelatedId: event.id,
profileId: event.profileId,
token: event.token);
if (success) {
families
.removeWhere((element) => element.relatedPerson!.id == event.id);
emit(DeletedState(success: success));
} else {
emit(DeletedState(success: success));
}
} catch (e) {
emit(FamilyErrorState(message: e.toString()));
}
});
+49
View File
@@ -15,3 +15,52 @@ class GetFamilies extends FamilyEvent{
@override
List<Object> get props => [profileId,token];
}
class LoadFamily extends FamilyEvent{
}
class ShowEditFamilyForm extends FamilyEvent{
final FamilyBackground familyBackground;
const ShowEditFamilyForm({required this.familyBackground});
@override
List<Object> get props => [familyBackground];
}
class AddFamily extends FamilyEvent{
final int profileId;
final String token;
final int relationshipId;
final FamilyBackground familyBackground;
const AddFamily({required this.familyBackground, required this.profileId, required this.token, required this.relationshipId});
@override
List<Object> get props => [profileId,token,familyBackground];
}
class Updatefamily extends FamilyEvent{
final int profileId;
final String token;
final int relationshipId;
final FamilyBackground familyBackground;
const Updatefamily({required this.familyBackground, required this.profileId, required this.token, required this.relationshipId,});
@override
List<Object> get props => [profileId,token,familyBackground];
}
class DeleteFamily extends FamilyEvent{
final int id;
final int profileId;
final String token;
const DeleteFamily({required this.id, required this.profileId, required this.token});
}
class AddEmergencyEvent extends FamilyEvent{
final int profileId;
final int relatedPersonId;
final int? contactInfoId;
final String token;
final String? numberMail;
final String requestType;
const AddEmergencyEvent({required this.contactInfoId, required this.numberMail, required this.profileId, required this.relatedPersonId, required this.token, required this.requestType});
@override
List<Object> get props => [profileId,token,relatedPersonId];
}
+26 -4
View File
@@ -10,13 +10,35 @@ abstract class FamilyState extends Equatable {
class FamilyInitial extends FamilyState {}
class FamilyLoaded extends FamilyState{
final List<FamilyBackground> families;
final List<FamilyBackground>? families;
const FamilyLoaded({required this.families});
@override
List<Object> get props => [families];
}
}
class DeletedState extends FamilyState {
final bool success;
const DeletedState({required this.success});
@override
List<Object> get props => [success];
}
class FamilyAddedState extends FamilyState{
final Map<dynamic,dynamic> response;
const FamilyAddedState({required this.response});
@override
List<Object> get props => [response];
}
class EmergencyContactEditedState extends FamilyState{
final Map<dynamic,dynamic> response;
const EmergencyContactEditedState({required this.response});
@override
List<Object> get props => [response];
}
class FamilyEditedState extends FamilyState{
final Map<dynamic,dynamic> response;
const FamilyEditedState({required this.response});
@override
List<Object> get props => [response];
}
class FamilyErrorState extends FamilyState{
final String message;
const FamilyErrorState({required this.message});
@@ -1,8 +1,22 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:unit2/model/location/country.dart';
import 'package:unit2/model/location/region.dart';
import 'package:unit2/screens/profile/components/other_information/org_membership/add_modal.dart';
import 'package:unit2/screens/unit2/login/components/update_required.dart';
import 'package:unit2/sevices/profile/learningDevelopment_service.dart';
import 'package:unit2/test_data.dart';
import 'package:unit2/utils/text_container.dart';
import '../../../model/location/barangay.dart';
import '../../../model/location/city.dart';
import '../../../model/location/provinces.dart';
import '../../../model/profile/learning_development.dart';
import '../../../model/utils/agency.dart';
import '../../../model/utils/category.dart';
import '../../../utils/location_utilities.dart';
import '../../../utils/profile_utilities.dart';
part 'learning_development_event.dart';
part 'learning_development_state.dart';
@@ -10,19 +24,253 @@ part 'learning_development_state.dart';
class LearningDevelopmentBloc
extends Bloc<LearningDevelopmentEvent, LearningDevelopmentState> {
LearningDevelopmentBloc() : super(LearningDevelopmentInitial()) {
List<LearningDevelopement> learningsAndDevelopments;
List<LearningDevelopement> learningsAndDevelopments = [];
List<LearningDevelopmentType> types = [];
List<LearningDevelopmentType> topics = [];
List<Country> globalCountries = [];
List<Region> globalRegions = [];
List<Province> globalProvinces = [];
List<CityMunicipality> globalCities = [];
List<Barangay> globalBarangay = [];
List<Agency> agencies = [];
List<Category> agencyCategory = [];
Region? currentRegion;
Country? currentCountry;
Province? currentProvince;
CityMunicipality? currentCity;
Barangay? currentBarangay;
on<GetLearningDevelopments>((event, emit) async {
// try {
emit(LearningDevelopmentLoadingState());
try {
List<LearningDevelopement> learnings = await LearningDevelopmentServices
.instance
.getLearningDevelopments(event.profileId, event.token);
learningsAndDevelopments = learnings;
emit(LearningDevelopmentLoadedState(
learningsAndDevelopment: learningsAndDevelopments));
} catch (e) {
emit(LearningDevelopmentErrorState(message: e.toString()));
}
});
////load
on<LoadLearniningDevelopment>((event, emit) {
emit(LearningDevelopmentLoadedState(
learningsAndDevelopment: learningsAndDevelopments));
});
//// show add form
on<ShowAddLearningDevelopmentForm>((event, emit) async {
try {
emit(LearningDevelopmentLoadingState());
List<LearningDevelopement> learnings = await LearningDevelopmentServices
.instance
.getLearningDevelopments(event.profileId, event.token);
learningsAndDevelopments = learnings;
emit(LearningDevelopmentLoadedState(
learningsAndDevelopment: learningsAndDevelopments));
// } catch (e) {
// emit(LeaningDevelopmentErrorState(message: e.toString()));
// }
if (types.isEmpty) {
List<LearningDevelopmentType> newTypes =
await LearningDevelopmentServices.instance
.getLearningDevelopmentType();
types = newTypes;
}
if (topics.isEmpty) {
List<LearningDevelopmentType> newTopics =
await LearningDevelopmentServices.instance.getTrainingTopics();
topics = newTopics;
}
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
if (agencies.isEmpty) {
List<Agency> newAgencies =
await ProfileUtilities.instance.getAgecies();
agencies = newAgencies;
}
if (agencyCategory.isEmpty) {
List<Category> categoryAgencies =
await ProfileUtilities.instance.agencyCategory();
agencyCategory = categoryAgencies;
}
emit(LearningDevelopmentAddingState(
types: types,
topics: topics,
countries: globalCountries,
regions: globalRegions,
conductedBy: agencies,
sponsorAgencies: agencies,
agencyCategory: agencyCategory));
} catch (e) {
emit(LeaningDevelopmentErrorState(message: e.toString()));
}
});
////Show edit form
on<ShowEditLearningDevelopmentForm>((event, emit) async {
try{
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
currentCountry = globalCountries.firstWhere((Country country) =>
event.learningDevelopment.conductedTraining!.venue!.country!.code ==
country.code);
if (!event.isOverseas) {
//// if not overseas
currentRegion = globalRegions.firstWhere((Region region) =>
event.learningDevelopment.conductedTraining!.venue!
.cityMunicipality!.province!.region!.code ==
region.code);
globalProvinces = await LocationUtils.instance
.getProvinces(regionCode: currentRegion!.code.toString());
currentProvince = globalProvinces.firstWhere((Province province) =>
event.learningDevelopment.conductedTraining!.venue!
.cityMunicipality!.province!.code ==
province.code);
globalCities = await LocationUtils.instance
.getCities(code: currentProvince!.code.toString());
currentCity = globalCities.firstWhere(
(CityMunicipality cityMunicipality) =>
event.learningDevelopment.conductedTraining!.venue!
.cityMunicipality!.code ==
cityMunicipality.code);
globalBarangay = await LocationUtils.instance
.getBarangay(code: currentCity!.code.toString());
if (event.learningDevelopment.conductedTraining?.venue?.barangay?.cityMunicipality !=
null) {
currentBarangay = globalBarangay.firstWhere((Barangay barangay) =>
event.learningDevelopment.conductedTraining!.venue!.barangay!
.code ==
barangay.code);
} else {
currentBarangay = null;
}
}
if (topics.isEmpty) {
List<LearningDevelopmentType> newTopics =
await LearningDevelopmentServices.instance.getTrainingTopics();
topics = newTopics;
}
if (types.isEmpty) {
List<LearningDevelopmentType> newTypes =
await LearningDevelopmentServices.instance
.getLearningDevelopmentType();
types = newTypes;
}
if (agencies.isEmpty) {
List<Agency> newAgencies = await ProfileUtilities.instance.getAgecies();
agencies = newAgencies;
}
if (agencyCategory.isEmpty) {
List<Category> categoryAgencies =
await ProfileUtilities.instance.agencyCategory();
agencyCategory = categoryAgencies;
}
emit(LearningDevelopmentUpdatingState(
cities: globalCities,
currentBarangay: currentBarangay,
barangay: globalBarangay,
provinces: globalProvinces,
types: types,
topics: topics,
training: event.learningDevelopment.conductedTraining!.title!,
learningDevelopement: event.learningDevelopment,
currentConductedBy:
event.learningDevelopment.conductedTraining!.conductedBy!,
currentSponsor: event.learningDevelopment.sponsoredBy,
conductedBy: agencies,
sponsorAgencies: agencies,
agencyCategory: agencyCategory,
countries: globalCountries,
regions: globalRegions,
currentRegion: currentRegion,
currentCountry: currentCountry!,
currentProvince: currentProvince,
currentCity: currentCity,
overseas: event.isOverseas));
}catch(e){
emit(LearningDevelopmentErrorState(message: e.toString()));
}
});
////Add
on<AddLearningAndDevelopment>((event, emit) async {
try {
Map<dynamic, dynamic> status =
await LearningDevelopmentServices.instance.add(
learningDevelopement: event.learningDevelopement,
token: event.token,
profileId: event.profileId);
if (status['success']) {
LearningDevelopement learningDevelopement =
LearningDevelopement.fromJson(status['data']);
learningsAndDevelopments.add(learningDevelopement);
emit(LearningDevelopmentAddedState(response: status));
} else {
emit(LearningDevelopmentAddedState(response: status));
}
} catch (e) {
emit(LearningDevelopmentErrorState(message: e.toString()));
}
});
////Update
on<UpdateLearningDevelopment>((event, emit) async {
try {
Map<dynamic, dynamic> status =
await LearningDevelopmentServices.instance.update(
learningDevelopement: event.learningDevelopement,
token: event.token,
profileId: event.profileId);
if (status['success']) {
learningsAndDevelopments.removeWhere((LearningDevelopement element) =>
element.conductedTraining!.id == event.learningDevelopement.conductedTraining!.id &&
element.conductedTraining!.totalHours == event.learningDevelopement.conductedTraining!.totalHours);
LearningDevelopement learningDevelopement =
LearningDevelopement.fromJson(status['data']);
learningsAndDevelopments.add(learningDevelopement);
emit(LearningDevelopmentUpdatedState(response: status));
} else {
emit(LearningDevelopmentUpdatedState(response: status));
}
} catch (e) {
emit(LearningDevelopmentErrorState(message: e.toString()));
}
});
////delete
on<DeleteLearningDevelopment>((event, emit) async {
try {
final bool success = await LearningDevelopmentServices.instance.delete(
profileId: event.profileId,
token: event.token,
sponsorId: event.sponsorId,
totalHours: event.hours,
trainingId: event.trainingId);
if (success) {
learningsAndDevelopments.removeWhere((LearningDevelopement element) =>
element.conductedTraining!.id == event.trainingId &&
element.conductedTraining!.totalHours == event.hours);
emit(DeleteLearningDevelopmentState(success: success));
} else {
emit(DeleteLearningDevelopmentState(success: success));
}
} catch (e) {
emit(LearningDevelopmentErrorState(message: e.toString()));
}
});
//// call errror
on<CallErrorState>((event, emit) {
emit(LeaningDevelopmentErrorState(message: event.message));
});
}
}
@@ -15,3 +15,54 @@ class GetLearningDevelopments extends LearningDevelopmentEvent {
@override
List<Object> get props => [profileId, token];
}
class ShowAddLearningDevelopmentForm extends LearningDevelopmentEvent{
}
class ShowEditLearningDevelopmentForm extends LearningDevelopmentEvent{
final LearningDevelopement learningDevelopment;
final int profileId;
final String token;
final bool isOverseas;
const ShowEditLearningDevelopmentForm({required this.isOverseas, required this.learningDevelopment, required this.profileId, required this.token});
}
class LoadLearniningDevelopment extends LearningDevelopmentEvent{
}
////delete
class DeleteLearningDevelopment extends LearningDevelopmentEvent {
final String token;
final int profileId;
final int? sponsorId;
final int trainingId;
final double hours;
const DeleteLearningDevelopment(
{required this.profileId, required this.token, required this.hours,required this.sponsorId, required this.trainingId});
@override
List<Object> get props => [profileId, token, hours,trainingId];
}
////add
class AddLearningAndDevelopment extends LearningDevelopmentEvent{
final LearningDevelopement learningDevelopement;
final int profileId;
final String token;
const AddLearningAndDevelopment({required this.learningDevelopement, required this.profileId, required this.token});
@override
List<Object> get props => [profileId, token,learningDevelopement];
}
////update
class UpdateLearningDevelopment extends LearningDevelopmentEvent{
final LearningDevelopement learningDevelopement;
final int profileId;
final String token;
const UpdateLearningDevelopment({required this.learningDevelopement, required this.profileId, required this.token});
@override
List<Object> get props => [profileId, token,learningDevelopement];
}
class CallErrorState extends LearningDevelopmentEvent{
final String message;
const CallErrorState({required this.message});
}
@@ -2,27 +2,120 @@ part of 'learning_development_bloc.dart';
abstract class LearningDevelopmentState extends Equatable {
const LearningDevelopmentState();
@override
List<Object> get props => [];
}
class LearningDevelopmentInitial extends LearningDevelopmentState {}
class LearningDevelopmentLoadedState extends LearningDevelopmentState{
final List<LearningDevelopement> learningsAndDevelopment;
const LearningDevelopmentLoadedState({required this.learningsAndDevelopment});
@override
class LearningDevelopmentLoadedState extends LearningDevelopmentState {
final List<LearningDevelopement> learningsAndDevelopment;
const LearningDevelopmentLoadedState({required this.learningsAndDevelopment});
@override
List<Object> get props => [learningsAndDevelopment];
}
class LeaningDevelopmentErrorState extends LearningDevelopmentState{
class LeaningDevelopmentErrorState extends LearningDevelopmentState {
final String message;
const LeaningDevelopmentErrorState({required this.message});
@override
@override
List<Object> get props => [message];
}
class LearningDevelopmentLoadingState extends LearningDevelopmentState{
class LearningDevelopmentLoadingState extends LearningDevelopmentState {}
////added State
class LearningDevelopmentAddedState extends LearningDevelopmentState {
final Map<dynamic, dynamic> response;
const LearningDevelopmentAddedState({required this.response});
@override
List<Object> get props => [response];
}
////Updated State
class LearningDevelopmentUpdatedState extends LearningDevelopmentState {
final Map<dynamic, dynamic> response;
const LearningDevelopmentUpdatedState({required this.response});
@override
List<Object> get props => [response];
}
//// Deleted State
class DeleteLearningDevelopmentState extends LearningDevelopmentState {
final bool success;
const DeleteLearningDevelopmentState({required this.success});
@override
List<Object> get props => [success];
}
////Update State
class LearningDevelopmentUpdatingState extends LearningDevelopmentState {
final List<LearningDevelopmentType> types;
final List<LearningDevelopmentType> topics;
final LearningDevelopmentType training;
final LearningDevelopement learningDevelopement;
final Agency currentConductedBy;
final Agency? currentSponsor;
final List<Agency> conductedBy;
final List<Agency> sponsorAgencies;
final List<Category> agencyCategory;
final List<Country> countries;
final List<Region> regions;
final List<Province> provinces;
final List<Barangay> barangay;
final List<CityMunicipality> cities;
final Region? currentRegion;
final Country currentCountry;
final Province? currentProvince;
final CityMunicipality? currentCity;
final Barangay? currentBarangay;
final bool overseas;
const LearningDevelopmentUpdatingState(
{required this.currentBarangay,
required this.cities,
required this.barangay,
required this.provinces,
required this.types,
required this.topics,
required this.training,
required this.learningDevelopement,
required this.currentConductedBy,
required this.currentSponsor,
required this.conductedBy,
required this.sponsorAgencies,
required this.agencyCategory,
required this.countries,
required this.regions,
required this.currentRegion,
required this.currentCountry,
required this.currentProvince,
required this.currentCity,
required this.overseas});
}
////Adding State
class LearningDevelopmentAddingState extends LearningDevelopmentState {
final List<LearningDevelopmentType> types;
final List<LearningDevelopmentType> topics;
final List<Agency> conductedBy;
final List<Agency> sponsorAgencies;
final List<Country> countries;
final List<Region> regions;
final List<Category> agencyCategory;
const LearningDevelopmentAddingState(
{required this.types,
required this.topics,
required this.countries,
required this.regions,
required this.conductedBy,
required this.sponsorAgencies,
required this.agencyCategory});
}
class LearningDevelopmentErrorState extends LearningDevelopmentState {
final String message;
const LearningDevelopmentErrorState({required this.message});
}
@@ -15,9 +15,11 @@ class HoobiesBloc extends Bloc<HobbiesEvent, HobbiesState> {
on<GetSkillsHobbies>((event, emit) async {
emit(HobbiesLoadingState());
try {
List<SkillsHobbies> hobbies = await SkillsHobbiesServices.instance
if(skillsAndHobbies.isEmpty){
List<SkillsHobbies> hobbies = await SkillsHobbiesServices.instance
.getSkillsHobbies(event.profileId, event.token);
skillsAndHobbies = hobbies;
}
emit(HobbiesLoadedState(skillsAndHobbies: skillsAndHobbies));
} catch (e) {
emit(HobbiesErrorState(message: e.toString()));
@@ -27,12 +27,10 @@ class NonAcademicRecognitionBloc
await NonAcademicRecognitionServices.instance
.getNonAcademicRecognition(event.profileId!, event.token!);
nonAcademicRecognitions = recognitions;
emit(NonAcademicRecognitionLoadedState(
nonAcademicRecognition: nonAcademicRecognitions));
} else {
emit(NonAcademicRecognitionLoadedState(
nonAcademicRecognition: nonAcademicRecognitions));
}
emit(NonAcademicRecognitionLoadedState(
nonAcademicRecognition: nonAcademicRecognitions));
} catch (e) {
emit(NonAcademicRecognitionErrorState(message: e.toString()));
}
@@ -40,7 +38,7 @@ class NonAcademicRecognitionBloc
////LOAD
on<LoadNonAcademeRecognition>((event,emit){
nonAcademicRecognitions = event.nonAcademicRecognitions;
emit(NonAcademicRecognitionLoadedState(nonAcademicRecognition: nonAcademicRecognitions));
});
////SHOW ADD FORM
@@ -14,10 +14,10 @@ class GetNonAcademicRecognition extends NonAcademicRecognitionEvent{
}
////LOAD EVENT
class LoadNonAcademeRecognition extends NonAcademicRecognitionEvent{
final List<NonAcademicRecognition> nonAcademicRecognitions;
const LoadNonAcademeRecognition({required this.nonAcademicRecognitions});
const LoadNonAcademeRecognition();
@override
List<Object> get props => [nonAcademicRecognitions];
List<Object> get props => [];
}
////SHOW ADD FORM EVENT
@@ -10,72 +10,104 @@ import '../../../../model/profile/other_information/organization_memberships.dar
part 'organization_membership_event.dart';
part 'organization_membership_state.dart';
class OrganizationMembershipBloc extends Bloc<OrganizationMembershipEvent, OrganizationMembershipState> {
List<Agency> agencies = [];
List<Category> agencyCategory = [];
class OrganizationMembershipBloc
extends Bloc<OrganizationMembershipEvent, OrganizationMembershipState> {
List<Agency> agencies = [];
List<Category> agencyCategory = [];
OrganizationMembershipBloc() : super(OrganizationMembershipInitial()) {
List<OrganizationMembership> organizationMemberships=[];
on<GetOrganizationMembership>((event, emit) async{
emit(OrgmembershipLoadingState());
try{
if(organizationMemberships.isEmpty){
List<OrganizationMembership> orgs = await OrganizationMembershipServices.instance.getOrgMemberships(event.profileId!, event.token!);
organizationMemberships = orgs;
List<OrganizationMembership> organizationMemberships = [];
on<GetOrganizationMembership>((event, emit) async {
emit(OrgmembershipLoadingState());
try {
if (organizationMemberships.isEmpty) {
List<OrganizationMembership> orgs =
await OrganizationMembershipServices.instance
.getOrgMemberships(event.profileId!, event.token!);
organizationMemberships = orgs;
}
if (agencies.isEmpty) {
List<Agency> newAgencies =
await ProfileUtilities.instance.getAgecies();
agencies = newAgencies;
}
if (agencyCategory.isEmpty) {
List<Category> newAgencyCategories =
await ProfileUtilities.instance.agencyCategory();
agencyCategory = newAgencyCategories;
}
emit(OrganizationMembershipLoaded(
orgMemberships: organizationMemberships,
agencies: agencies,
agencyCategory: agencyCategory));
} catch (e) {
emit(OrganizationMembershipErrorState(message: e.toString()));
}
emit(OrganizationMembershipLoaded(orgMemberships: organizationMemberships));
}catch(e){
OrganizationMembershipErrorState(message: e.toString());
}
});
on<LoadOrganizationMemberships>((event,emit){
emit(OrganizationMembershipLoaded(orgMemberships: organizationMemberships));
on<LoadOrganizationMemberships>((event, emit) {
emit(OrganizationMembershipLoaded(
orgMemberships: organizationMemberships,
agencies: agencies,
agencyCategory: agencyCategory));
});
////SHOW ADD ORG MEMBERSHIP FORM
on<ShowAddOrgMembershipForm>((event,emit)async{
on<ShowAddOrgMembershipForm>((event, emit) async {
emit(OrgmembershipLoadingState());
try{
if(agencies.isEmpty){
List<Agency> newAgencies = await ProfileUtilities.instance.getAgecies();
try {
if (agencies.isEmpty) {
List<Agency> newAgencies =
await ProfileUtilities.instance.getAgecies();
agencies = newAgencies;
}
if(agencyCategory.isEmpty){
List<Category>newAgencyCategories = await ProfileUtilities.instance.agencyCategory();
if (agencyCategory.isEmpty) {
List<Category> newAgencyCategories =
await ProfileUtilities.instance.agencyCategory();
agencyCategory = newAgencyCategories;
}
emit(AddOrgMembershipState(agencies: agencies, agencyCategories: agencyCategory));
}catch(e){
emit(AddOrgMembershipState(
agencies: agencies, agencyCategories: agencyCategory));
} catch (e) {
emit(OrganizationMembershipErrorState(message: e.toString()));
}
});
//// ADD ORGMEMBERSHIP
on<AddOrgMembership>((event,emit)async{
try{
Map<dynamic,dynamic> status= await OrganizationMembershipServices.instance.add(agency: event.agency, token: event.token, profileId: event.profileId.toString());
if(status["success"]){
OrganizationMembership organizationMembership = OrganizationMembership.fromJson(status["data"]);
on<AddOrgMembership>((event, emit) async {
try {
emit(OrgmembershipLoadingState());
Map<dynamic, dynamic> status =
await OrganizationMembershipServices.instance.add(
agency: event.agency,
token: event.token,
profileId: event.profileId.toString());
if (status["success"]) {
OrganizationMembership organizationMembership =
OrganizationMembership.fromJson(status["data"]);
organizationMemberships.add(organizationMembership);
emit(OrgMembershipAddedState( response: status));
}else{
emit(OrgMembershipAddedState( response: status));
emit(OrgMembershipAddedState(response: status));
} else {
emit(OrgMembershipAddedState(response: status));
}
}catch(e){
} catch (e) {
emit(OrganizationMembershipErrorState(message: e.toString()));
}
});
////DELETE ORGMEMBERSHIP
on<DeleteOrgMemberShip>((event,emit)async{
on<DeleteOrgMemberShip>((event, emit) async {
emit(OrgmembershipLoadingState());
try{
final bool success = await OrganizationMembershipServices.instance.delete(agency: event.org.agency!, profileId: event.profileId, token: event.token);
if(success){
organizationMemberships.removeWhere((element) => element.agency!.id == event.org.agency!.id );
try {
final bool success = await OrganizationMembershipServices.instance
.delete(
agency: event.org.agency!,
profileId: event.profileId,
token: event.token);
if (success) {
organizationMemberships.removeWhere(
(element) => element.agency!.id == event.org.agency!.id);
emit(OrgMembershipDeletedState(success: success));
} else {
emit(OrgMembershipDeletedState(success: success));
}else{
emit(OrgMembershipDeletedState(success: success));
}
}catch(e){
} catch (e) {
emit(OrganizationMembershipErrorState(message: e.toString()));
}
});
@@ -2,45 +2,51 @@ part of 'organization_membership_bloc.dart';
abstract class OrganizationMembershipState extends Equatable {
const OrganizationMembershipState();
@override
List<Object> get props => [];
}
class OrganizationMembershipInitial extends OrganizationMembershipState {}
class OrganizationMembershipLoaded extends OrganizationMembershipState{
final List<OrganizationMembership>orgMemberships;
const OrganizationMembershipLoaded({required this.orgMemberships});
@override
class OrganizationMembershipLoaded extends OrganizationMembershipState {
final List<OrganizationMembership> orgMemberships;
final List<Agency> agencies;
final List<Category> agencyCategory;
const OrganizationMembershipLoaded(
{required this.orgMemberships,
required this.agencies,
required this.agencyCategory});
@override
List<Object> get props => [orgMemberships];
}
class OrganizationMembershipErrorState extends OrganizationMembershipState{
class OrganizationMembershipErrorState extends OrganizationMembershipState {
final String message;
const OrganizationMembershipErrorState({required this.message});
@override
@override
List<Object> get props => [message];
}
class OrgmembershipLoadingState extends OrganizationMembershipState{
class OrgmembershipLoadingState extends OrganizationMembershipState {}
}
class OrgMembershipDeletedState extends OrganizationMembershipState{
class OrgMembershipDeletedState extends OrganizationMembershipState {
final bool success;
const OrgMembershipDeletedState({ required this.success});
@override
const OrgMembershipDeletedState({required this.success});
@override
List<Object> get props => [success];
}
class OrgMembershipAddedState extends OrganizationMembershipState{
final Map<dynamic,dynamic> response;
class OrgMembershipAddedState extends OrganizationMembershipState {
final Map<dynamic, dynamic> response;
const OrgMembershipAddedState({required this.response});
@override
@override
List<Object> get props => [response];
}
class AddOrgMembershipState extends OrganizationMembershipState{
final List<Agency> agencies;
final List<Category> agencyCategories;
const AddOrgMembershipState({required this.agencies, required this.agencyCategories});
class AddOrgMembershipState extends OrganizationMembershipState {
final List<Agency> agencies;
final List<Category> agencyCategories;
const AddOrgMembershipState(
{required this.agencies, required this.agencyCategories});
}
@@ -1,22 +1,207 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/bloc/profile/eligibility/eligibility_bloc.dart';
import 'package:unit2/model/location/barangay.dart';
import 'package:unit2/model/location/subdivision.dart';
import 'package:unit2/model/profile/voluntary_works.dart';
import 'package:unit2/sevices/profile/address_service.dart';
import '../../../../model/location/city.dart';
import '../../../../model/location/country.dart';
import '../../../../model/location/provinces.dart';
import '../../../../model/location/region.dart';
import '../../../../model/profile/basic_information/adress.dart';
import '../../../../utils/location_utilities.dart';
part 'address_event.dart';
part 'address_state.dart';
class AddressBloc extends Bloc<AddressEvent, AddressState> {
AddressBloc() : super(AddressInitial()) {
List<MainAdress> addresses = [];
List<Country> globalCountries = [];
List<Region> globalRegions = [];
List<MainAdress> addresses = [];
List<Province> provinces = [];
List<CityMunicipality> cities = [];
List<Barangay> barangays = [];
Region? currentRegion;
Country currentCountry;
Province? currentProvince;
CityMunicipality? currentCity;
Barangay? currentBarangay;
on<GetAddress>((event, emit) {
emit(AddressLoadingState());
try{
addresses = event.addresses;
try {
addresses = event.addresses;
emit(AddressLoadedState(addresses: addresses));
} catch (e) {
emit(AddressErrorState(message: e.toString()));
}
});
////Load
on<LoadAddress>((event, emit) {
emit(AddressLoadedState(addresses: addresses));
}catch(e){
emit(AddressErrorState(message: e.toString()));
}
});
//// show add form
on<ShowAddAddressForm>((event, emit) async {
emit(AddressLoadingState());
try {
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
emit(AddAddressState(
countries: globalCountries, regions: globalRegions));
} catch (e) {
emit(AddressErrorState(message: e.toString()));
}
});
//// Show Edit Form
on<ShowEditAddressForm>((event, emit) async {
try {
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
currentCountry = globalCountries.firstWhere((Country country) =>
event.address.address!.country!.code == country.code);
if (!event.overseas) {
//// if not overseas
currentRegion = globalRegions.firstWhere((Region region) =>
event.address.address!.cityMunicipality!.province!.region!.code ==
region.code);
provinces = await LocationUtils.instance
.getProvinces(regionCode: currentRegion!.code.toString());
currentProvince = provinces.firstWhere((Province province) =>
event.address.address!.cityMunicipality!.province!.code ==
province.code);
cities = await LocationUtils.instance
.getCities(code: currentProvince!.code.toString());
currentCity = cities.firstWhere((CityMunicipality cityMunicipality) =>
event.address.address!.cityMunicipality!.code ==
cityMunicipality.code);
barangays = await LocationUtils.instance
.getBarangay(code: currentCity!.code.toString());
if (event.address.address?.barangay != null) {
currentBarangay = barangays.firstWhere((Barangay barangay) =>
event.address.address?.barangay?.code == barangay.code);
} else {
currentBarangay = null;
}
}
emit(EditAddressState(
countries: globalCountries,
regions: globalRegions,
address: event.address,
baragays: barangays,
cities: cities,
currentCity: currentCity,
currentCountry: currentCountry,
currentProvince: currentProvince,
currentRegion: currentRegion,
overseas: event.overseas,
provinces: provinces,
currentBarangay: currentBarangay));
} catch (e) {
emit(AddressErrorState(message: e.toString()));
}
});
////Add
on<AddAddress>(
(event, emit) async {
try {
Map<String, dynamic> status = await AddressService.instance.add(
address: event.address,
categoryId: event.categoryId,
token: event.token,
details: event.details,
blockNumber: event.blockNumber,
lotNumber: event.lotNumber,
profileId: event.profileId);
if (status['success']) {
AddressClass addressClass = AddressClass.fromJson(status['data']['address']);
Subdivision? subdivision = status['data']['subdivision'] !=null? Subdivision.fromJson(status['data']['subdivision']):null;
MainAdress address = MainAdress(address: addressClass,subdivision: subdivision,id: status['data']['id'],details: status['data']['details']);
addresses.add(address);
emit(AddressAddedState(response: status));
} else {
emit(AddressAddedState(response: status));
}
} catch (e) {
emit(AddressErrorState(message: e.toString()));
}
},
);
////update
on<UpdateAddress>(
(event, emit) async {
try {
Map<String, dynamic> status = await AddressService.instance.update(
address: event.address,
categoryId: event.categoryId,
token: event.token,
details: event.details,
blockNumber: event.blockNumber,
lotNumber: event.lotNumber,
profileId: event.profileId);
if (status['success']) {
AddressClass addressClass = AddressClass.fromJson(status['data']['address']);
Subdivision? subdivision = status['data']['subdivision'] !=null? Subdivision.fromJson(status['data']['subdivision']):null;
MainAdress address = MainAdress(address: addressClass,subdivision: subdivision,id: status['data']['id'],details: status['data']['details']);
addresses.add(address);
addresses.removeWhere((address)=>address.id == event.address.id);
addresses.add(address);
emit(AddressUpdatedState(response: status));
} else {
emit(AddressUpdatedState(response: status));
}
} catch (e) {
emit(AddressErrorState(message: e.toString()));
}
},
);
////Delete
on<DeleteAddress>((event, emit) async {
try {
final bool success = await AddressService.instance.delete(
addressId: event.id,
profileId: int.parse(event.profileId),
token: event.token);
if (success) {
addresses
.removeWhere(((MainAdress element) => element.id == event.id));
emit(AddressDeletedState(
success: success,
));
} else {
emit(AddressDeletedState(success: success));
}
} catch (e) {
emit(AddressErrorState(message: e.toString()));
}
});
////call error state
on<CallErrorState>((event, emit) {
emit(const AddressErrorState(
message: "Something went wrong. Please try again"));
});
}
}
@@ -7,9 +7,78 @@ abstract class AddressEvent extends Equatable {
List<Object> get props => [];
}
class GetAddress extends AddressEvent{
final List<MainAdress> addresses;
const GetAddress({required this.addresses});
@override
class GetAddress extends AddressEvent {
final List<MainAdress> addresses;
const GetAddress({required this.addresses});
@override
List<Object> get props => [addresses];
}
class ShowAddAddressForm extends AddressEvent {}
class ShowEditAddressForm extends AddressEvent {
final bool overseas;
final MainAdress address;
const ShowEditAddressForm({required this.address, required this.overseas});
}
class CallErrorState extends AddressEvent {}
class AddAddress extends AddressEvent {
final AddressClass address;
final int categoryId;
final String? details;
final int? blockNumber;
final int? lotNumber;
final String token;
final int profileId;
const AddAddress(
{required this.address,
required this.profileId,
required this.token,
required this.blockNumber,
required this.categoryId,
required this.details,
required this.lotNumber});
@override
List<Object> get props => [address, token, profileId,categoryId];
}
class UpdateAddress extends AddressEvent {
final AddressClass address;
final int categoryId;
final String? details;
final int? blockNumber;
final int? lotNumber;
final String token;
final int profileId;
const UpdateAddress(
{required this.address,
required this.profileId,
required this.token,
required this.blockNumber,
required this.categoryId,
required this.details,
required this.lotNumber});
@override
List<Object> get props => [address, token, profileId,categoryId];
}
class LoadAddress extends AddressEvent{
}
class DeleteAddress extends AddressEvent {
final String profileId;
final int id;
final String token;
const DeleteAddress(
{
required this.id,
required this.profileId,
required this.token});
@override
List<Object> get props => [ profileId, id, token];
}
@@ -2,26 +2,96 @@ part of 'address_bloc.dart';
abstract class AddressState extends Equatable {
const AddressState();
@override
List<Object> get props => [];
}
class AddressInitial extends AddressState {}
class AddressLoadedState extends AddressState{
final List<MainAdress> addresses;
const AddressLoadedState({required this.addresses});
@override
//// LOADED STATE
class AddressLoadedState extends AddressState {
final List<MainAdress> addresses;
const AddressLoadedState({required this.addresses});
@override
List<Object> get props => [addresses];
}
class AddressErrorState extends AddressState{
////ERROR STATE
class AddressErrorState extends AddressState {
final String message;
const AddressErrorState({required this.message});
@override
@override
List<Object> get props => [message];
}
class AddressLoadingState extends AddressState{
//// LOADING STATE
class AddressLoadingState extends AddressState {}
////ADD ADDRESS STATE
class AddAddressState extends AddressState {
final List<Country> countries;
final List<Region> regions;
const AddAddressState({required this.countries, required this.regions});
@override
List<Object> get props => [
countries,
regions,
];
}
//// DeletedState
class AddressDeletedState extends AddressState {
final bool success;
const AddressDeletedState({required this.success});
@override
List<Object> get props => [success];
}
////AddedState
class AddressAddedState extends AddressState {
final Map<dynamic, dynamic> response;
const AddressAddedState({required this.response});
@override
List<Object> get props => [response];
}
////Edited State
class AddressUpdatedState extends AddressState {
final Map<dynamic, dynamic> response;
const AddressUpdatedState({required this.response});
@override
List<Object> get props => [response];
}
class EditAddressState extends AddressState {
final MainAdress address;
final List<Country> countries;
final List<Region> regions;
final List<Province> provinces;
final List<CityMunicipality> cities;
final List<Barangay> baragays;
final Region? currentRegion;
final Country currentCountry;
final Province? currentProvince;
final CityMunicipality? currentCity;
final Barangay? currentBarangay;
final bool overseas;
const EditAddressState(
{required this.address,
required this.countries,
required this.regions,
required this.baragays,
required this.cities,
required this.currentCity,
required this.currentCountry,
required this.currentProvince,
required this.currentRegion,
required this.overseas,
required this.provinces,
required this.currentBarangay
});
@override
List<Object> get props => [countries, regions, address];
}
@@ -0,0 +1,106 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/location/country.dart';
import 'package:unit2/model/profile/basic_information/citizenship.dart';
import 'package:unit2/sevices/profile/citizenship_services.dart';
import 'package:unit2/utils/location_utilities.dart';
part 'citizenship_event.dart';
part 'citizenship_state.dart';
class CitizenshipBloc extends Bloc<CitizenshipEvent, CitizenshipState> {
List<Citizenship> citizenships = [];
List<Country> countries = [];
CitizenshipBloc() : super(CitizenshipInitial()) {
on<GetCitizenship>((event, emit) async {
emit(CitizenshipLoadingState());
try {
countries = await LocationUtils.instance.getCountries();
citizenships = event.citizenship;
emit(CitizenshipLoaded(
citizenships: event.citizenship, countries: countries));
} catch (e) {
emit(CitizenshipErrorState(message: e.toString()));
}
});
on<LoadCitizenship>((event, emit) {
emit(CitizenshipLoaded(citizenships: citizenships, countries: countries));
});
on<AddCitizenship>((event, emit) async {
try {
emit(CitizenshipLoadingState());
Map<dynamic, dynamic> responseStatus =
await CitizenshipServices.instance.add(
profileId: event.profileId,
token: event.token,
countryId: event.coiuntryId,
naturalBorn: event.naturalBorn);
if (responseStatus['success']) {
Country newCountry =
Country.fromJson(responseStatus['data']['country']);
Citizenship citizenship = Citizenship(
country: newCountry,
naturalBorn: responseStatus['data']['natural_born']);
citizenships.add(citizenship);
emit(CitizenshipAddedState(
responseStatus: responseStatus, citizenships: citizenships));
} else {
emit(CitizenshipAddedState(
responseStatus: responseStatus, citizenships: citizenships));
}
} catch (e) {
emit(CitizenshipErrorState(message: e.toString()));
}
});
on<EditCitizenship>((event, emit) async {
try {
emit(CitizenshipLoadingState());
Map<dynamic, dynamic> responseStatus =
await CitizenshipServices.instance.update(
profileId: event.profileId,
token: event.token,
citizenship: event.citizenship,
oldCountry: event.oldCountryId);
if (responseStatus['success'] != null && responseStatus['success']) {
citizenships.removeWhere((element) =>
element.country!.id == event.citizenship.country!.id &&
element.naturalBorn == event.citizenship.naturalBorn);
Country newCountry =
Country.fromJson(responseStatus['data']['country']);
Citizenship citizenship = Citizenship(
country: newCountry,
naturalBorn: responseStatus['data']['natural_born']);
citizenships.add(citizenship);
emit(CitizenshipEditedState(
responseStatus: responseStatus, citizenships: citizenships));
} else {
emit(CitizenshipEditedState(
responseStatus: responseStatus, citizenships: citizenships));
}
} catch (e) {
emit(CitizenshipErrorState(message: e.toString()));
}
});
on<DeleteCitizenship>((event, emit) async {
emit(CitizenshipLoadingState());
try {
final bool success = await CitizenshipServices.instance.delete(
profileId: event.profileId,
token: event.token,
countryId: event.coiuntryId,
naturalBorn: event.naturalBorn);
if (success) {
citizenships.removeWhere((element) =>
element.country!.id == event.coiuntryId &&
element.naturalBorn == event.naturalBorn);
emit(CitizenshipDeleltedState(succcess: success));
} else {
emit(CitizenshipDeleltedState(succcess: success));
}
} catch (e) {
emit(CitizenshipErrorState(message: e.toString()));
}
});
}
}
@@ -0,0 +1,42 @@
part of 'citizenship_bloc.dart';
abstract class CitizenshipEvent extends Equatable {
const CitizenshipEvent();
@override
List<Object> get props => [];
}
class GetCitizenship extends CitizenshipEvent{
final List<Citizenship> citizenship;
const GetCitizenship({required this.citizenship});
}
class ShowAddCitizenshipForm extends CitizenshipEvent{
const ShowAddCitizenshipForm();
}
class LoadCitizenship extends CitizenshipEvent{
const LoadCitizenship();
}
class EditCitizenship extends CitizenshipEvent{
final Citizenship citizenship;
final int profileId;
final String token;
final int oldCountryId;
const EditCitizenship({required this.citizenship, required this.oldCountryId, required this.profileId, required this.token});
}
class AddCitizenship extends CitizenshipEvent{
final int profileId;
final String token;
final int coiuntryId;
final bool naturalBorn;
const AddCitizenship({required this.coiuntryId, required this.naturalBorn, required this.profileId, required this.token});
}
class DeleteCitizenship extends CitizenshipEvent{
final int profileId;
final String token;
final int coiuntryId;
final bool naturalBorn;
const DeleteCitizenship({required this.coiuntryId, required this.naturalBorn, required this.profileId, required this.token});
}
@@ -0,0 +1,47 @@
part of 'citizenship_bloc.dart';
abstract class CitizenshipState extends Equatable {
const CitizenshipState();
@override
List<Object> get props => [];
}
class CitizenshipInitial extends CitizenshipState {}
class CitizenshipLoaded extends CitizenshipState{
final List<Citizenship> citizenships;
final List<Country> countries;
const CitizenshipLoaded({required this.citizenships,required this.countries});
}
class CitizenshipAddingState extends CitizenshipState{
final List<Country> countries;
const CitizenshipAddingState({required this.countries});
}
class CitizenshipLoadingState extends CitizenshipState{
}
class CitizenshipAddedState extends CitizenshipState{
final Map<dynamic,dynamic> responseStatus;
final List<Citizenship> citizenships;
const CitizenshipAddedState({required this.responseStatus, required this.citizenships});
}
class CitizenshipEditedState extends CitizenshipState{
final Map<dynamic,dynamic> responseStatus;
final List<Citizenship> citizenships;
const CitizenshipEditedState({required this.responseStatus, required this.citizenships});
}
class CitizenshipErrorState extends CitizenshipState{
final String message;
const CitizenshipErrorState({required this.message});
}
class CitizenshipDeleltedState extends CitizenshipState{
final bool succcess;
const CitizenshipDeleltedState({required this.succcess});
@override
List<Object> get props => [succcess];
}
@@ -48,10 +48,6 @@ class ContactAddedState extends ContactState{
@override
List<Object> get props => [response];
}
//// edited state
class ContactEditedState extends ContactState{
@@ -62,7 +58,6 @@ class ContactEditedState extends ContactState{
}
////deleted state
class ContactDeletedState extends ContactState{
final bool succcess;
const ContactDeletedState({required this.succcess});
@override
@@ -1,21 +1,207 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/bloc/profile/primary_information/contact/contact_bloc.dart';
import 'package:unit2/screens/profile/components/basic_information/identification/edit_modal.dart';
import 'package:unit2/sevices/profile/identification_services.dart';
import '../../../../model/location/city.dart';
import '../../../../model/location/country.dart';
import '../../../../model/location/provinces.dart';
import '../../../../model/location/region.dart';
import '../../../../model/profile/basic_information/identification_information.dart';
import '../../../../model/utils/agency.dart';
import '../../../../model/utils/category.dart';
import '../../../../utils/location_utilities.dart';
import '../../../../utils/profile_utilities.dart';
part 'identification_event.dart';
part 'identification_state.dart';
class IdentificationBloc extends Bloc<IdentificationEvent, IdentificationState> {
class IdentificationBloc
extends Bloc<IdentificationEvent, IdentificationState> {
IdentificationBloc() : super(IdentificationInitial()) {
List<Identification> identificationInformations = [];
List<Identification> identificationInformations = [];
List<Agency> agencies = [];
List<Agency> addedAgencies = [];
List<Category> agencyCategory = [];
List<Country> globalCountries = [];
List<Region> globalRegions = [];
List<Province> provinces = [];
List<CityMunicipality> cities = [];
Region? currentRegion;
Country currentCountry;
Province? currentProvince;
CityMunicipality? currentCity;
////get
on<GetIdentifications>((event, emit) {
try{
try {
identificationInformations = event.identificationInformation;
emit(IdentificationLoadedState(identificationInformation: identificationInformations));
}catch(e){
emit(IdentificationLoadedState(
identificationInformation: identificationInformations));
} catch (e) {
emit(IdenficationErrorState(message: e.toString()));
}
});
////load
on<LoadIdentifications>((event, emit) {
emit(IdentificationLoadedState(
identificationInformation: identificationInformations));
});
//// show add form
on<ShowAddIdentificationForm>((event, emit) async {
addedAgencies.clear();
try {
emit(IdentificationLoadingState());
if (identificationInformations.isNotEmpty) {
for (var element in identificationInformations) {
addedAgencies.add(element.agency!);
}
}
/////AGENCIES------------------------------------------
if (agencies.isEmpty) {
List<Agency> newAgencies =
await ProfileUtilities.instance.getAgecies();
agencies = newAgencies;
}
/////Category Agency------------------------------------------
if (agencyCategory.isEmpty) {
List<Category> categoryAgencies =
await ProfileUtilities.instance.agencyCategory();
agencyCategory = categoryAgencies;
}
////regions
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
//// country
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
emit(IdentificationAddingState(
addedAgencies: addedAgencies,
agencyCategory: agencyCategory,
agencies: agencies,
countries: globalCountries,
regions: globalRegions));
} catch (e) {
emit(IdenficationErrorState(message: e.toString()));
}
});
////show edit form
on<ShowEditIdentificationForm>((event, emit) async {
try {
////regions
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
//// country
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
currentCountry = globalCountries.firstWhere((Country country) =>
event.identification.issuedAt!.country!.code == country.code);
if (!event.overseas) {
currentRegion = globalRegions.firstWhere((Region region) =>
event.identification.issuedAt!.cityMunicipality!.province!.region!
.code ==
region.code);
provinces = await LocationUtils.instance
.getProvinces(regionCode: currentRegion!.code.toString());
currentProvince = provinces.firstWhere((Province province) =>
event.identification.issuedAt!.cityMunicipality!.province!.code ==
province.code);
cities = await LocationUtils.instance
.getCities(code: currentProvince!.code.toString());
currentCity = cities.firstWhere((CityMunicipality cityMunicipality) =>
event.identification.issuedAt!.cityMunicipality!.code ==
cityMunicipality.code);
}
emit(IdentificationEditingState(
cities: cities,
countries: globalCountries,
currentCity: currentCity,
currentCountry: currentCountry,
currentProvince: currentProvince,
currentRegion: currentRegion,
identification: event.identification,
overseas: event.overseas,
provinces: provinces,
regions: globalRegions));
} catch (e) {
emit(IdenficationErrorState(message: e.toString()));
}
});
////add
on<AddIdentification>((event, emit) async {
try {
emit(IdentificationLoadingState());
Map<dynamic, dynamic> status = await IdentificationServices.instance
.add(
identification: event.identification,
profileId: event.profileId,
token: event.token);
if (status['success']) {
Identification identification =
Identification.fromJson(status['data']);
identificationInformations.add(identification);
emit(IdentificationAddedState(response: status));
} else {
emit(IdentificationAddedState(response: status));
}
} catch (e) {
emit(IdenficationErrorState(message: e.toString()));
}
});
////update
on<UpdateIdentifaction>((event, emit) async {
try {
emit(IdentificationLoadingState());
Map<dynamic, dynamic> status = await IdentificationServices.instance
.update(
identification: event.identification,
profileId: event.profileId,
token: event.token);
if (status['success']) {
identificationInformations
.removeWhere((element) => element.id == event.identification.id);
Identification identification =
Identification.fromJson(status['data']);
identificationInformations.add(identification);
emit(IdentificationEditedState(response: status));
} else {
emit(IdentificationEditedState(response: status));
}
} catch (e) {
emit(IdenficationErrorState(message: e.toString()));
}
});
////delete
on<DeleteIdentification>((event, emit) async {
try {
final bool success = await IdentificationServices.instance.delete(
identificationId: event.identificationId,
token: event.token,
profileId: event.profileId);
if (success) {
identificationInformations.removeWhere(
(Identification element) => element.id == event.identificationId);
emit(IdentificationDeletedState(success: success));
} else {
emit(IdentificationDeletedState(success: success));
}
} catch (e) {
emit(IdenficationErrorState(message: e.toString()));
}
});
////show error state
on<ShowErrorState>((event, emit) {
emit(IdenficationErrorState(message: event.message));
});
}
}
@@ -6,10 +6,63 @@ abstract class IdentificationEvent extends Equatable {
@override
List<Object> get props => [];
}
////get
class GetIdentifications extends IdentificationEvent{
final List<Identification> identificationInformation;
const GetIdentifications({required this.identificationInformation});
@override
List<Object> get props => [identificationInformation];
}
////load
class LoadIdentifications extends IdentificationEvent{
@override
List<Object> get props => [];
}
////show add form
class ShowAddIdentificationForm extends IdentificationEvent{
}
//// show edit form
class ShowEditIdentificationForm extends IdentificationEvent{
final bool overseas;
final Identification identification;
final int profileId;
final String token;
const ShowEditIdentificationForm({required this.identification, required this.profileId, required this.token, required this.overseas});
@override
List<Object> get props => [identification,profileId,token,overseas];
}
class DeleteIdentification extends IdentificationEvent{
final int identificationId;
final int profileId;
final String token;
const DeleteIdentification({required this.identificationId, required this.profileId, required this.token});
}
//// add
class AddIdentification extends IdentificationEvent{
final Identification identification;
final int profileId;
final String token;
const AddIdentification({required this.identification, required this.profileId, required this.token});
@override
List<Object> get props => [identification,profileId,token];
}
//// update
class UpdateIdentifaction extends IdentificationEvent{
final Identification identification;
final int profileId;
final String token;
const UpdateIdentifaction({required this.identification, required this.profileId, required this.token});
@override
List<Object> get props => [identification,profileId,token];
}
class ShowErrorState extends IdentificationEvent {
final String message;
const ShowErrorState({required this.message});
}
@@ -26,3 +26,49 @@ class IdenficationErrorState extends IdentificationState{
class IdentificationLoadingState extends IdentificationState{
}
class IdentificationDeletedState extends IdentificationState{
final bool success;
const IdentificationDeletedState({required this.success});
@override
List<Object> get props => [success];
}
class IdentificationAddedState extends IdentificationState{
final Map<dynamic,dynamic> response;
const IdentificationAddedState({required this.response});
@override
List<Object> get props => [response];
}
class IdentificationEditedState extends IdentificationState{
final Map<dynamic,dynamic> response;
const IdentificationEditedState({required this.response});
@override
List<Object> get props => [response];
}
class IdentificationAddingState extends IdentificationState{
final List<Agency> agencies;
final List<Agency> addedAgencies;
final List<Country> countries;
final List<Region> regions;
final List<Category> agencyCategory;
const IdentificationAddingState({required this.agencies, required this.countries, required this.regions,required this.agencyCategory, required this.addedAgencies});
@override
List<Object> get props => [agencies,countries,regions,agencyCategory];
}
class IdentificationEditingState extends IdentificationState{
final Identification identification;
final List<Country> countries;
final List<Region> regions;
final List<Province> provinces;
final List<CityMunicipality> cities;
final Region? currentRegion;
final Country currentCountry;
final Province? currentProvince;
final CityMunicipality? currentCity;
final bool overseas;
const IdentificationEditingState({required this.cities,required this.countries, required this.currentCity, required this.currentCountry, required this.currentProvince, required this.currentRegion, required this.identification, required this.overseas, required this.provinces, required this.regions});
}
+115 -4
View File
@@ -1,17 +1,61 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/profile/profileInfomation.dart';
import 'package:unit2/sevices/profile/profile_other_info.dart';
import 'package:unit2/sevices/profile/profile_service.dart';
import '../../model/profile/basic_information/primary-information.dart';
import '../../screens/profile/components/basic_information/profile_other_info.dart';
part 'profile_event.dart';
part 'profile_state.dart';
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
ProfileBloc() : super(ProfileInitial()) {
Profile? currentProfileInformation;
List<ProfileOtherInfo> religions = [];
List<ProfileOtherInfo> ethnicities = [];
List<ProfileOtherInfo> indigencies = [];
List<ProfileOtherInfo> disabilities = [];
List<ProfileOtherInfo> genders = [];
List<String> bloodType = [
"A+",
"B+",
"A-",
"B-",
"AB+",
"AB-",
"O+",
"O-"
];
List<String> nameExtensions = [
"NONE",
"N/A",
"SR.",
"JR.",
"I",
"II",
"III",
"IV",
"V",
"VI",
"VII",
"VIII",
"IX",
"X"
];
List<String> sexes = ["MALE", "FEMALE"];
List<String> civilStatus = [
"NONE",
"SINGLE",
"MARRIED",
"SEPARATED",
"WIDOWED"
];
ProfileInformation? globalProfileInformation;
on<LoadProfile>((event, emit) async {
emit(ProfileLoading());
emit(ProfileLoading());
try {
ProfileInformation? profileInformation =
await ProfileService.instance.getProfile(event.token, event.userID);
globalProfileInformation = profileInformation;
@@ -20,7 +64,74 @@ class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
emit(ProfileErrorState(mesage: e.toString()));
}
});
on<GetPrimaryBasicInfo>((event, emit) {
currentProfileInformation = event.primaryBasicInformation;
emit(BasicInformationProfileLoaded(
primaryBasicInformation: event.primaryBasicInformation));
});
on<LoadBasicPrimaryInfo>((event,emit){
emit(BasicInformationProfileLoaded(
primaryBasicInformation: currentProfileInformation!));
});
on<ShowPrimaryInfoEditForm>((event, emit) async {
try {
emit(BasicPrimaryInformationLoadingState());
if (religions.isEmpty) {
religions = await ProfileOtherInfoServices.instace
.getReligions(token: event.token);
}
if (genders.isEmpty) {
genders = await ProfileOtherInfoServices.instace
.getGenders(token: event.token);
}
if (ethnicities.isEmpty) {
ethnicities = await ProfileOtherInfoServices.instace
.getEthnicity(token: event.token);
}
if (disabilities.isEmpty) {
disabilities = await ProfileOtherInfoServices.instace
.getDisability(token: event.token);
}
if (indigencies.isEmpty) {
indigencies = await ProfileOtherInfoServices.instace
.getIndigency(token: event.token);
}
emit(BasicInformationEditingState(
primaryInformation: currentProfileInformation!,
extensions: nameExtensions,
sexes: sexes,
bloodTypes: bloodType,
genders: genders,
civilStatus: civilStatus,
disability: disabilities,
ethnicity: ethnicities,
indigenous: indigencies,
religion: religions));
} catch (e) {
emit(BasicPrimaryInformationErrorState(message: e.toString()));
}
});
on<EditBasicProfileInformation>((event, emit) async {
try {
Map<dynamic, dynamic> status = await ProfileService.instance
.updateBasicProfileInfo(
token: event.token,
profileId: event.profileId,
profileInfo: event.profileInformation,
genderId: event.genderId,
indigencyId: event.indigencyId,
disabilityId: event.disabilityId,
ethnicityId: event.ethnicityId,
reqligionId: event.religionId);
if (status['success']) {
Profile profile = Profile.fromJson(status['data']);
currentProfileInformation = profile;
emit(BasicProfileInfoEditedState(response: status));
}
emit(BasicProfileInfoEditedState(response: status));
} catch (e) {
emit(BasicPrimaryInformationErrorState(message: e.toString()));
}
});
}
}
+23
View File
@@ -19,6 +19,29 @@ class LoadProfileInformation extends ProfileEvent {
@override
List<Object> get props => [];
}
class GetPrimaryBasicInfo extends ProfileEvent{
final Profile primaryBasicInformation;
const GetPrimaryBasicInfo({required this.primaryBasicInformation});
}
class LoadBasicPrimaryInfo extends ProfileEvent{
}
class ShowPrimaryInfoEditForm extends ProfileEvent{
final String token;
const ShowPrimaryInfoEditForm({required this.token});
}
class EditBasicProfileInformation extends ProfileEvent{
final Profile profileInformation;
final int profileId;
final String token;
final int? genderId;
final int? indigencyId;
final int? disabilityId;
final int? religionId;
final int? ethnicityId;
const EditBasicProfileInformation({required this.disabilityId,required this.ethnicityId, required this.genderId, required this.indigencyId, required this.profileId,required this.profileInformation,required this.religionId,required this.token});
}
+33
View File
@@ -22,6 +22,39 @@ class ProfileErrorState extends ProfileState {
@override
List<Object> get props => [mesage];
}
class BasicInformationEditingState extends ProfileState{
final Profile primaryInformation;
final List<ProfileOtherInfo> religion;
final List<ProfileOtherInfo> ethnicity;
final List<ProfileOtherInfo> disability;
final List<ProfileOtherInfo> indigenous;
final List<ProfileOtherInfo> genders;
final List<String>sexes;
final List<String> bloodTypes;
final List<String> civilStatus;
final List<String> extensions;
const BasicInformationEditingState( {required this.genders, required this.extensions, required this.primaryInformation, required this.sexes, required this.bloodTypes, required this.civilStatus, required this.disability,required this.ethnicity,required this.indigenous,required this.religion});
}
////Edited State
class BasicProfileInfoEditedState extends ProfileState{
final Map<dynamic,dynamic> response;
const BasicProfileInfoEditedState({required this.response});
@override
List<Object> get props => [response];
}
class BasicInformationProfileLoaded extends ProfileState{
final Profile primaryBasicInformation;
const BasicInformationProfileLoaded({required this.primaryBasicInformation});
}
class BasicPrimaryInformationLoadingState extends ProfileState{
}
class BasicPrimaryInformationErrorState extends ProfileState{
final String message;
const BasicPrimaryInformationErrorState({required this.message});
}
class ProfileLoading extends ProfileState {}
@@ -23,19 +23,19 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
on<GetReferences>((event, emit) async {
emit(ReferencesLoadingState());
try {
if(references.isEmpty){
if (references.isEmpty) {
List<PersonalReference> refs = await ReferencesServices.instace
.getRefences(event.profileId, event.token);
references = refs;
emit(ReferencesLoadedState(references: references));
}else{
emit(ReferencesLoadedState(references: references));
}
.getRefences(event.profileId, event.token);
references = refs;
emit(ReferencesLoadedState(references: references));
}
} catch (e) {
ReferencesErrorState(message: e.toString());
emit( ReferencesErrorState(message: e.toString()));
}
});
////SHOW FORM FOR ADDING REFERENCES
});
on<ShowAddReferenceForm>((event, emit) async {
emit(ReferencesLoadingState());
try {
@@ -85,7 +85,10 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
//// checck if address is overseas
bool overseas =
event.personalReference.address!.country!.id! != 175 ? true : false;
selectedCategory = globalCategories.firstWhere((AddressCategory element) => event.personalReference.address!.addressCategory!.id == element.id);
selectedCategory = globalCategories.firstWhere(
(AddressCategory element) =>
event.personalReference.address!.addressCategory!.id ==
element.id);
////if address is not overseas set initial values for address
if (!overseas) {
selectedRegion = globalRegions.firstWhere((Region element) =>
@@ -103,12 +106,15 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
selectedCity = cities.firstWhere((CityMunicipality city) =>
event.personalReference.address!.cityMunicipality!.code ==
city.code);
List<Barangay> barangays = await LocationUtils.instance.getBarangay(code: selectedCity.code.toString());
if(event.personalReference.address?.barangay!=null){
selectedBarangay = barangays.firstWhere((Barangay barangay)=>event.personalReference.address?.barangay?.code == barangay.code);
}else{
selectedBarangay = null;
}
List<Barangay> barangays = await LocationUtils.instance
.getBarangay(code: selectedCity.code.toString());
if (event.personalReference.address?.barangay != null) {
selectedBarangay = barangays.firstWhere((Barangay barangay) =>
event.personalReference.address?.barangay?.code ==
barangay.code);
} else {
selectedBarangay = null;
}
emit(EditReferenceState(
selectedRegion: selectedRegion,
ref: event.personalReference,
@@ -122,14 +128,14 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
cities: cities,
selectedCity: selectedCity,
selectedCategory: selectedCategory,
selectedBarangay: selectedBarangay
));
selectedBarangay: selectedBarangay));
} else {
//// if address is overseas set initial value for country
selectedCountry = globalCountries.firstWhere((Country element) => event.personalReference.address!.country!.id == element.id);
selectedCountry = globalCountries.firstWhere((Country element) =>
event.personalReference.address!.country!.id == element.id);
emit(EditReferenceState(
selectedCountry: selectedCountry,
selectedCategory: selectedCategory,
selectedCountry: selectedCountry,
selectedCategory: selectedCategory,
selectedRegion: null,
ref: event.personalReference,
countries: globalCountries,
@@ -147,19 +153,19 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
emit(const ReferencesErrorState(
message: "Something went wrong. Please try again"));
//// EDIT REFERENCES EVENT
});on<EditReference>((event,emit)async{
Map<dynamic,dynamic> status =await ReferencesServices.instace.update(ref: event.reference, token: event.token, profileId: event.profileId);
if (status['success']) {
PersonalReference ref = PersonalReference.fromJson(status['data']);
references.removeWhere((PersonalReference element)=>element.id == event.reference.id);
references.add(ref);
emit(
ReferenceEditedState( response: status));
} else {
emit(
ReferenceEditedState( response: status));
}
});
on<EditReference>((event, emit) async {
Map<dynamic, dynamic> status = await ReferencesServices.instace.update(
ref: event.reference, token: event.token, profileId: event.profileId);
if (status['success']) {
PersonalReference ref = PersonalReference.fromJson(status['data']);
references.removeWhere(
(PersonalReference element) => element.id == event.reference.id);
references.add(ref);
emit(ReferenceEditedState(response: status));
} else {
emit(ReferenceEditedState(response: status));
}
});
//// add reference event
@@ -173,11 +179,9 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
if (status['success']) {
PersonalReference ref = PersonalReference.fromJson(status['data']);
references.add(ref);
emit(
ReferencesAddedState( response: status));
emit(ReferencesAddedState(response: status));
} else {
emit(
ReferencesAddedState( response: status));
emit(ReferencesAddedState(response: status));
}
} catch (e) {
emit(ReferencesErrorState(message: e.toString()));
@@ -187,9 +191,8 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
on<LoadReferences>((event, emit) {
emit(ReferencesLoadingState());
emit(ReferencesLoadedState(references: references));
});
////DELETE REFERENCE
////DELETE REFERENCE
on<DeleteReference>((event, emit) async {
try {
final bool success = await ReferencesServices.instace.delete(
@@ -198,7 +201,7 @@ class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
event.references.removeWhere(
(PersonalReference element) => element.id == event.refId);
references = event.references;
emit(DeleteReferenceState( success: success));
emit(DeleteReferenceState(success: success));
} else {
emit(DeleteReferenceState(success: success));
}
@@ -1,8 +1,19 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:unit2/sevices/profile/volunatary_services.dart';
import 'package:unit2/utils/profile_utilities.dart';
import '../../../model/location/city.dart';
import '../../../model/location/country.dart';
import '../../../model/location/provinces.dart';
import '../../../model/location/region.dart';
import '../../../model/profile/voluntary_works.dart';
import '../../../model/utils/agency.dart';
import '../../../model/utils/category.dart';
import '../../../model/utils/position.dart';
import '../../../utils/location_utilities.dart';
part 'voluntary_work_event.dart';
part 'voluntary_work_state.dart';
@@ -10,15 +21,233 @@ part 'voluntary_work_state.dart';
class VoluntaryWorkBloc extends Bloc<VoluntaryWorkEvent, VoluntaryWorkState> {
VoluntaryWorkBloc() : super(VoluntaryWorkInitial()) {
List<VoluntaryWork> voluntaryWorks = [];
on<GetVoluntarWorks>((event, emit) async{
List<Country> globalCountries = [];
List<Category> agencyCategory = [];
List<Region> globalRegions = [];
List<Position> agencyPositions = [];
List<Agency> agencies = [];
List<Province> provinces = [];
List<CityMunicipality> cities = [];
///// current
Position currentPosition;
Agency currentAgency;
Region? currentRegion;
Country currentCountry;
Province? currentProvince;
CityMunicipality? currentCity;
////Get Voluntary Works
on<GetVoluntarWorks>((event, emit) async {
emit(VoluntaryWorkLoadingState());
try{
List<VoluntaryWork> works = await VoluntaryService.instance.getVoluntaryWorks(event.profileId, event.token);
voluntaryWorks = works;
emit(VoluntaryWorkLoadedState(voluntaryWorks: voluntaryWorks));
}catch(e){
emit(VoluntaryWorkErrorState(message: e.toString()));
try {
if(voluntaryWorks.isEmpty){
List<VoluntaryWork> works = await VoluntaryService.instance
.getVoluntaryWorks(event.profileId, event.token);
voluntaryWorks = works;
}
emit(VoluntaryWorkLoadedState(voluntaryWorks: voluntaryWorks));
} catch (e) {
emit(VoluntaryWorkErrorState(message: e.toString()));
}
});
//// Load
on<LoadVoluntaryWorks>((event, emit) {
emit(VoluntaryWorkLoadedState(voluntaryWorks: voluntaryWorks));
});
//// Show Add form Event
on<ShowAddVoluntaryWorks>((event, emit) async {
try {
emit(VoluntaryWorkLoadingState());
//// POSITIONS
if (agencyPositions.isEmpty) {
List<Position> positions =
await ProfileUtilities.instance.getAgencyPosition();
agencyPositions = positions;
}
/////AGENCIES------------------------------------------
if (agencies.isEmpty) {
List<Agency> newAgencies =
await ProfileUtilities.instance.getAgecies();
agencies = newAgencies;
}
/////Category Agency------------------------------------------
if (agencyCategory.isEmpty) {
List<Category> categoryAgencies =
await ProfileUtilities.instance.agencyCategory();
agencyCategory = categoryAgencies;
}
////regions
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
//// country
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
emit(AddVoluntaryWorkState(
agencies: agencies,
positions: agencyPositions,
agencyCategory: agencyCategory,
regions: globalRegions,
countries: globalCountries));
} catch (e) {
emit(VoluntaryWorkErrorState(message: e.toString()));
}
});
on<ShowErrorState>((event, emit) {
emit(VoluntaryWorkErrorState(message: event.message));
});
//// Add Voluntary Work
on<AddVoluntaryWork>((event, emit) async {
try {
Map<dynamic, dynamic> status = await VoluntaryService.instance.add(
voluntaryWork: event.work,
profileId: event.profileId,
token: event.token);
if (status['success']) {
VoluntaryWork work = VoluntaryWork.fromJson(status['data']);
voluntaryWorks.add(work);
emit(VoluntaryWorkAddedState(response: status));
} else {
emit(VoluntaryWorkAddedState(response: status));
}
} catch (e) {
emit(VoluntaryWorkErrorState(message: e.toString()));
}
});
////Update
on<UpdateVolunataryWork>((event, emit) async {
final DateFormat formatter = DateFormat('yyyy-MM-dd');
try{
Map<dynamic, dynamic> status = await VoluntaryService.instance.update(
voluntaryWork: event.work,
profileId: event.profileId,
token: event.token,
oldPosId: event.oldPosId,
oldAgencyId: event.oldAgencyId,
oldFromDate: formatter.format(DateTime.parse(event.oldFromDate)));
if (status['success']) {
VoluntaryWork work = VoluntaryWork.fromJson(status['data']);
voluntaryWorks.removeWhere((VoluntaryWork element) =>
element.position!.id == event.oldPosId &&
element.agency!.id == event.oldAgencyId &&
element.fromDate.toString() == event.oldFromDate.toString());
voluntaryWorks.add(work);
emit(VoluntaryWorkEditedState(response: status));
} else {
emit(VoluntaryWorkEditedState(response: status));
}
}catch(e){
emit(VoluntaryWorkErrorState(message: e.toString()));
}
});
/////SHOW EDIT FORM
on<ShowEditVoluntaryWorks>((event, emit) async {
try {
//// POSITIONS
if (agencyPositions.isEmpty) {
List<Position> positions =
await ProfileUtilities.instance.getAgencyPosition();
agencyPositions = positions;
}
currentPosition = event.work.position!;
/////AGENCIES------------------------------------------
if (agencies.isEmpty) {
List<Agency> newAgencies =
await ProfileUtilities.instance.getAgecies();
agencies = newAgencies;
}
currentAgency = event.work.agency!;
/////Category Agency------------------------------------------
if (agencyCategory.isEmpty) {
List<Category> categoryAgencies =
await ProfileUtilities.instance.agencyCategory();
agencyCategory = categoryAgencies;
}
////regions
if (globalRegions.isEmpty) {
List<Region> regions = await LocationUtils.instance.getRegions();
globalRegions = regions;
}
//// country
if (globalCountries.isEmpty) {
List<Country> countries = await LocationUtils.instance.getCountries();
globalCountries = countries;
}
currentCountry = globalCountries.firstWhere((Country country) =>
event.work.address!.country!.code == country.code);
////If overseas
if (!event.isOverseas) {
//// if not overseas
currentRegion = globalRegions.firstWhere((Region region) =>
event.work.address!.cityMunicipality!.province!.region!.code ==
region.code);
provinces = await LocationUtils.instance
.getProvinces(regionCode: currentRegion!.code.toString());
currentProvince = provinces.firstWhere((Province province) =>
event.work.address!.cityMunicipality!.province!.code ==
province.code);
cities = await LocationUtils.instance
.getCities(code: currentProvince!.code.toString());
currentCity = cities.firstWhere((CityMunicipality cityMunicipality) =>
event.work.address!.cityMunicipality!.code ==
cityMunicipality.code);
}
emit(EditVoluntaryWorks(
overseas: event.isOverseas,
agencies: agencies,
agencyCategory: agencyCategory,
cities: cities,
countries: globalCountries,
positions: agencyPositions,
provinces: provinces,
regions: globalRegions,
work: event.work,
currentAgency: currentAgency,
currentCity: currentCity,
currentCountry: currentCountry,
currentPosition: currentPosition,
currentProvince: currentProvince,
currentRegion: currentRegion));
} catch (e) {
emit(VoluntaryWorkErrorState(message: e.toString()));
}
});
//// Delete
on<DeleteVoluntaryWork>((event, emit) async {
try {
final DateFormat formatter = DateFormat('yyyy-MM-dd');
final bool success = await VoluntaryService.instance.delete(
agencyId: event.work.agency!.id!,
positionId: event.work.position!.id!,
fromDate: formatter.format(event.work.fromDate!),
token: event.token,
profileId: event.profileId);
if (success) {
voluntaryWorks.removeWhere((VoluntaryWork element) =>
element.position!.id == event.work.position!.id &&
element.agency!.id == event.work.agency!.id &&
element.fromDate == event.work.fromDate);
emit(VoluntaryWorkDeletedState(success: success));
} else {
emit(VoluntaryWorkDeletedState(success: success));
}
} catch (e) {
emit(VoluntaryWorkErrorState(message: e.toString()));
}
});
}
}
@@ -7,10 +7,68 @@ abstract class VoluntaryWorkEvent extends Equatable {
List<Object> get props => [];
}
class GetVoluntarWorks extends VoluntaryWorkEvent{
class GetVoluntarWorks extends VoluntaryWorkEvent {
final int profileId;
final String token;
const GetVoluntarWorks({required this.profileId, required this.token});
@override
List<Object> get props => [profileId,token];
@override
List<Object> get props => [profileId, token];
}
class ShowAddVoluntaryWorks extends VoluntaryWorkEvent {}
class ShowEditVoluntaryWorks extends VoluntaryWorkEvent {
final VoluntaryWork work;
final int profileId;
final String token;
final bool isOverseas;
// final int oldPosId;
// final int oldAgencyId;
// final String oldFromDate;
const ShowEditVoluntaryWorks(
{required this.profileId,
required this.token,
required this.work,
// required this.oldAgencyId,
// required this.oldFromDate,
// required this.oldPosId,
required this.isOverseas});
@override
List<Object> get props => [profileId, token, work];
}
class LoadVoluntaryWorks extends VoluntaryWorkEvent {}
class ShowErrorState extends VoluntaryWorkEvent {
final String message;
const ShowErrorState({required this.message});
}
class UpdateVolunataryWork extends VoluntaryWorkEvent{
final int oldPosId;
final int oldAgencyId;
final String oldFromDate;
final VoluntaryWork work;
final int profileId;
final String token;
const UpdateVolunataryWork({required this.oldAgencyId, required this.oldFromDate, required this.oldPosId, required this.profileId, required this.token, required this.work});
}
class AddVoluntaryWork extends VoluntaryWorkEvent {
final int profileId;
final String token;
final VoluntaryWork work;
const AddVoluntaryWork(
{required this.profileId, required this.token, required this.work});
@override
List<Object> get props => [profileId, token, work];
}
class DeleteVoluntaryWork extends VoluntaryWorkEvent {
final String token;
final int profileId;
final VoluntaryWork work;
const DeleteVoluntaryWork(
{required this.profileId, required this.token, required this.work});
@override
List<Object> get props => [profileId, token, work];
}
@@ -8,20 +8,73 @@ abstract class VoluntaryWorkState extends Equatable {
}
class VoluntaryWorkInitial extends VoluntaryWorkState {}
////Loaded State
class VoluntaryWorkLoadedState extends VoluntaryWorkState{
final List<VoluntaryWork> voluntaryWorks;
const VoluntaryWorkLoadedState({required this.voluntaryWorks});
@override
List<Object> get props => [voluntaryWorks];
}
////Error State
class VoluntaryWorkErrorState extends VoluntaryWorkState{
final String message;
const VoluntaryWorkErrorState({required this.message});
@override
List<Object> get props => [message];
}
////Loading State
class VoluntaryWorkLoadingState extends VoluntaryWorkState{
}
////Added State
class VoluntaryWorkAddedState extends VoluntaryWorkState{
final Map<dynamic,dynamic> response;
const VoluntaryWorkAddedState({required this.response});
@override
List<Object> get props => [response];
}
////Edited State
class VoluntaryWorkEditedState extends VoluntaryWorkState{
final Map<dynamic,dynamic> response;
const VoluntaryWorkEditedState({required this.response});
@override
List<Object> get props => [response];
}
class EditVoluntaryWorks extends VoluntaryWorkState{
final VoluntaryWork work;
final List<Position> positions;
final List<Agency> agencies;
final List<Category> agencyCategory;
final List<Country> countries;
final List<Region> regions;
final List<Province> provinces;
final List<CityMunicipality> cities;
final Position currentPosition;
final Agency currentAgency;
final Region? currentRegion;
final Country currentCountry;
final Province? currentProvince;
final CityMunicipality? currentCity;
final bool overseas;
const EditVoluntaryWorks({required this.agencies, required this.agencyCategory, required this.cities, required this.countries,required this.positions, required this.provinces, required this.regions, required this.work, required this.currentAgency, required this.currentCity,required this.currentCountry, required this.currentPosition, required this.currentProvince, required this.currentRegion,required this.overseas});
}
////Adding State
class AddVoluntaryWorkState extends VoluntaryWorkState{
final List<Position> positions;
final List<Agency> agencies;
final List<Category> agencyCategory;
final List<Country> countries;
final List<Region> regions;
const AddVoluntaryWorkState({required this.agencies,required this.countries, required this.positions, required this.regions,required this.agencyCategory});
@override
List<Object> get props => [positions,agencies,countries,regions];
}
//// Deleted State
class VoluntaryWorkDeletedState extends VoluntaryWorkState{
final bool success;
const VoluntaryWorkDeletedState({required this.success});
@override
List<Object> get props => [success];
}
@@ -26,10 +26,9 @@ class WorkHistoryBloc extends Bloc<WorkHistorytEvent, WorkHistoryState> {
try {
if (workExperiences.isEmpty) {
List<WorkHistory> works = await WorkHistoryService.instance
.getWorkExperiences(event.profileId!, event.token!);
.getWorkExperiences(event.profileId, event.token);
workExperiences = works;
}
emit(WorkHistoryLoaded(workExperiences: workExperiences));
} catch (e) {
emit(WorkHistoryErrorState(message: e.toString()));
+21 -5
View File
@@ -21,12 +21,14 @@ class UserBloc extends Bloc<UserEvent, UserState> {
VersionInfo? _versionInfo;
String? _apkVersion;
bool save = false;
String? uuid;
UserBloc() : super(UserInitial()) {
//// this event is called when opening the app to check if
//// there is new app version
on<GetApkVersion>((event, emit) async {
try {
emit(SplashScreen());
save = false;
if (_versionInfo == null) {
VersionInfo versionInfo = await AuthService.instance.getVersionInfo();
_versionInfo = versionInfo;
@@ -36,8 +38,6 @@ class UserBloc extends Bloc<UserEvent, UserState> {
final String? saved = CREDENTIALS?.get('saved');
final String? username = CREDENTIALS?.get('username');
final String? password = CREDENTIALS?.get('password');
debugPrint(username);
debugPrint(password);
if (saved != null) {
save = true;
add(UserLogin(username: username, password: password));
@@ -89,9 +89,22 @@ class UserBloc extends Bloc<UserEvent, UserState> {
});
on<UuidLogin>((event, emit) async {
try {
UserData? userData = await AuthService.instance
Map<dynamic,dynamic> response = await AuthService.instance
.qrLogin(uuid: event.uuid, password: event.password);
_userData = userData;
if (response['status'] == true) {
UserData userData = UserData.fromJson(response['data']);
emit(UserLoggedIn(
userData: userData,
success: true,
message: response['message'],
savedCredentials: save));
} else {
emit(UserLoggedIn(
userData: null,
success: false,
message: response['message'],
savedCredentials: save));
}
emit(UserLoggedIn(userData: _userData, savedCredentials: save));
} on TimeoutException catch (_) {
emit(InternetTimeout(message: timeoutError));
@@ -107,8 +120,11 @@ class UserBloc extends Bloc<UserEvent, UserState> {
on<GetUuid>((event, emit) async {
ScanResult result = await QRCodeBarCodeScanner.instance.scanner();
if (result.rawContent.toString().isNotEmpty) {
emit(UuidLoaded(uuid: result.rawContent.toString()));
uuid = result.rawContent.toString();
emit(UuidLoaded(uuid: uuid!));
}
});on<LoadUuid>((event,emit){
emit(UuidLoaded(uuid: uuid!));
});
}
}
+3
View File
@@ -26,6 +26,9 @@ class LoadLoggedInUser extends UserEvent {
class GetUuid extends UserEvent {
GetUuid();
}
class LoadUuid extends UserEvent{
LoadUuid();
}
class LoadVersion extends UserEvent {
+5
View File
@@ -1,3 +1,5 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:device_preview/device_preview.dart';
@@ -15,6 +17,8 @@ import 'package:path_provider/path_provider.dart' as path_provider;
import './utils/router.dart';
import './utils/global.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
var appDirectory = await path_provider.getApplicationDocumentsDirectory();
@@ -88,3 +92,4 @@ class MyApp extends StatelessWidget {
);
}
}
+207
View File
@@ -0,0 +1,207 @@
// To parse this JSON data, do
//
// final document = documentFromJson(jsonString);
class Document {
Document({
required this.id,
required this.sk,
required this.dsk,
required this.slug,
required this.files,
required this.title,
required this.agency,
required this.office,
required this.subject,
required this.fileType,
required this.isPublic,
required this.createdAt,
required this.createdBy,
required this.validatedAt,
required this.validatedBy,
required this.documentType,
required this.documentRoutes,
required this.alternateMobile,
required this.attachedDocument,
required this.enableNotification,
required this.createdByPersonId,
});
final int? id;
final String? sk;
final String? dsk;
final String? slug;
final List<FileElement>? files;
final String? title;
final String? agency;
final String? office;
final String? subject;
final FileType? fileType;
final bool? isPublic;
final String? createdAt;
final String? createdBy;
final String? validatedAt;
final String? validatedBy;
final DocumentType? documentType;
final dynamic documentRoutes;
final AlternateMobile? alternateMobile;
final dynamic attachedDocument;
final bool? enableNotification;
final int? createdByPersonId;
factory Document.fromJson(Map<String, dynamic> json) => Document(
id: json["id"],
sk: json["sk"],
dsk: json["dsk"],
slug: json["slug"],
files: List<FileElement>.from(json["files"].map((x) => FileElement.fromJson(x))),
title: json["title"],
agency: json["agency"],
office: json["office"],
subject: json["subject"],
fileType: FileType.fromJson(json["file_type"]),
isPublic: json["is_public"],
createdAt: json["created_at"],
createdBy: json["created_by"],
validatedAt: json["validated_at"],
validatedBy: json["validated_by"],
documentType: DocumentType.fromJson(json["document_type"]),
documentRoutes: json["document_routes"],
alternateMobile: AlternateMobile.fromJson(json["alternate_mobile"]),
attachedDocument: json["attached_document"],
enableNotification: json["enable_notification"],
createdByPersonId: json["created_by_person_id"],
);
Map<String, dynamic> toJson() => {
"id": id,
"sk": sk,
"dsk": dsk,
"slug": slug,
"files": List<dynamic>.from(files!.map((x) => x.toJson())),
"title": title,
"agency": agency,
"office": office,
"subject": subject,
"file_type": fileType?.toJson(),
"is_public": isPublic,
"created_at": createdAt,
"created_by": createdBy,
"validated_at": validatedAt,
"validated_by": validatedBy,
"document_type": documentType?.toJson(),
"document_routes": documentRoutes,
"alternate_mobile": alternateMobile?.toJson(),
"attached_document": attachedDocument,
"enable_notification": enableNotification,
"created_by_person_id": createdByPersonId,
};
}
class AlternateMobile {
AlternateMobile({
required this.id,
required this.mobileNo,
required this.documentId,
});
final dynamic id;
final dynamic mobileNo;
final dynamic documentId;
factory AlternateMobile.fromJson(Map<String, dynamic> json) => AlternateMobile(
id: json["id"],
mobileNo: json["mobile_no"],
documentId: json["document_id"],
);
Map<String, dynamic> toJson() => {
"id": id,
"mobile_no": mobileNo,
"document_id": documentId,
};
}
class DocumentType {
DocumentType({
required this.id,
required this.name,
required this.slug,
required this.categoryId,
required this.priorityNumber,
});
final int id;
final String name;
final dynamic slug;
final int categoryId;
final dynamic priorityNumber;
factory DocumentType.fromJson(Map<String, dynamic> json) => DocumentType(
id: json["id"],
name: json["name"],
slug: json["slug"],
categoryId: json["category_id"],
priorityNumber: json["priority_number"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"slug": slug,
"category_id": categoryId,
"priority_number": priorityNumber,
};
}
class FileType {
FileType({
required this.id,
required this.name,
required this.isActive,
required this.extensions,
});
final int id;
final String name;
final bool isActive;
final List<String> extensions;
factory FileType.fromJson(Map<String, dynamic> json) => FileType(
id: json["id"],
name: json["name"],
isActive: json["is_active"],
extensions: List<String>.from(json["extensions"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"is_active": isActive,
"extensions": List<dynamic>.from(extensions.map((x) => x)),
};
}
class FileElement {
FileElement({
required this.path,
required this.extnsn,
required this.dateTime,
});
final String path;
final String extnsn;
final String dateTime;
factory FileElement.fromJson(Map<String, dynamic> json) => FileElement(
path: json["path"],
extnsn: json["extnsn"],
dateTime: json["date_time"],
);
Map<String, dynamic> toJson() => {
"path": path,
"extnsn": extnsn,
"date_time": dateTime,
};
}
@@ -1,4 +1,7 @@
import 'package:unit2/model/login_data/employee_info/office.dart';
import 'package:unit2/model/profile/profileInfomation.dart';
import '../../profile/basic_information/primary-information.dart';
class EmployeeInfo {
EmployeeInfo({
@@ -35,103 +38,4 @@ class EmployeeInfo {
"profile": profile!.toJson(),
};
}
class Profile {
Profile({
this.id,
this.sex,
this.gender,
this.deceased,
this.heightM,
this.birthdate,
this.esigPath,
this.fullName,
this.lastName,
this.weightKg,
this.bloodType,
this.firstName,
this.photoPath,
this.maidenName,
this.middleName,
this.uuidQrcode,
this.civilStatus,
this.titlePrefix,
this.titleSuffix,
this.showTitleId,
this.lastFullName,
this.nameExtension,
});
int? id;
String? sex;
String? gender;
bool? deceased;
double? heightM;
DateTime? birthdate;
String? esigPath;
String? fullName;
String? lastName;
int? weightKg;
String? bloodType;
String? firstName;
String? photoPath;
String? maidenName;
String? middleName;
String? uuidQrcode;
String? civilStatus;
String? titlePrefix;
String? titleSuffix;
bool? showTitleId;
String? lastFullName;
String? nameExtension;
factory Profile.fromJson(Map<String, dynamic> json) => Profile(
id: json["id"],
sex: json["sex"],
gender: json["gender"],
deceased: json["deceased"],
heightM: json["height_m"].toDouble(),
birthdate: DateTime.parse(json["birthdate"]),
esigPath: json["esig_path"],
fullName: json["full_name"],
lastName: json["last_name"],
weightKg: json["weight_kg"],
bloodType: json["blood_type"],
firstName: json["first_name"],
photoPath: json["photo_path"],
maidenName: json["maiden_name"],
middleName: json["middle_name"],
uuidQrcode: json["uuid_qrcode"],
civilStatus: json["civil_status"],
titlePrefix: json["title_prefix"],
titleSuffix: json["title_suffix"],
showTitleId: json["show_title_id"],
lastFullName: json["last_full_name"],
nameExtension: json["name_extension"],
);
Map<String, dynamic> toJson() => {
"id": id,
"sex": sex,
"gender": gender,
"deceased": deceased,
"height_m": heightM,
"birthdate":
"${birthdate!.year.toString().padLeft(4, '0')}-${birthdate!.month.toString().padLeft(2, '0')}-${birthdate!.day.toString().padLeft(2, '0')}",
"esig_path": esigPath,
"full_name": fullName,
"last_name": lastName,
"weight_kg": weightKg,
"blood_type": bloodType,
"first_name": firstName,
"photo_path": photoPath,
"maiden_name": maidenName,
"middle_name": middleName,
"uuid_qrcode": uuidQrcode,
"civil_status": civilStatus,
"title_prefix": titlePrefix,
"title_suffix": titleSuffix,
"show_title_id": showTitleId,
"last_full_name": lastFullName,
"name_extension": nameExtension,
};
}
+1 -2
View File
@@ -5,11 +5,10 @@ import 'package:unit2/model/profile/basic_information/identification_information
import 'package:unit2/model/profile/basic_information/primary-information.dart';
class BasicInfo{
PrimaryInformation? primaryInformation;
List<ContactInfo> contactInformation;
List<Identification> identifications;
List<Citizenship> citizenships;
List<MainAdress> addresses;
BasicInfo({required this.addresses, required this.contactInformation, required this.primaryInformation,required this.identifications,required this.citizenships});
BasicInfo({required this.addresses, required this.contactInformation,required this.identifications,required this.citizenships});
}
@@ -1,83 +1,106 @@
// To parse this JSON data, do
//
// final primaryInformation = primaryInformationFromJson(jsonString);
import 'package:meta/meta.dart';
import 'dart:convert';
class PrimaryInformation {
PrimaryInformation({
required this.id,
required this.lastName,
required this.firstName,
required this.middleName,
required this.nameExtension,
required this.sex,
required this.birthdate,
required this.civilStatus,
required this.bloodType,
required this.heightM,
required this.weightKg,
required this.photoPath,
required this.esigPath,
required this.maidenName,
required this.deceased,
required this.gender,
required this.uuidQrcode,
required this.titlePrefix,
required this.titleSuffix,
required this.showTitleId,
});
import 'package:unit2/model/profile/family_backround.dart';
int? id;
String? lastName;
String? firstName;
String? middleName;
String? nameExtension;
String? sex;
DateTime? birthdate;
String? civilStatus;
String? bloodType;
double? heightM;
double? weightKg;
String? photoPath;
String? esigPath;
String? maidenName;
bool? deceased;
String? gender;
String? uuidQrcode;
String? titlePrefix;
String? titleSuffix;
bool? showTitleId;
import '../../../screens/profile/components/basic_information/profile_other_info.dart';
factory PrimaryInformation.fromJson(Map<String, dynamic> json) =>
PrimaryInformation(
Profile primaryInformationFromJson(String str) => Profile.fromJson(json.decode(str));
String primaryInformationToJson(Profile data) => json.encode(data.toJson());
class Profile {
int? id;
String? lastName;
String? firstName;
String? middleName;
String? nameExtension;
String? sex;
DateTime? birthdate;
String? civilStatus;
String? bloodType;
double? heightM;
double? weightKg;
String? photoPath;
String? esigPath;
MaidenName? maidenName;
bool? deceased;
String? uuidQrcode;
String? titlePrefix;
String? titleSuffix;
bool? showTitleId;
String? ethnicity;
String? disability;
String? gender;
String? religion;
String? ip;
Profile({
required this.id,
required this.lastName,
required this.firstName,
required this.middleName,
required this.nameExtension,
required this.sex,
required this.birthdate,
required this.civilStatus,
required this.bloodType,
required this.heightM,
required this.weightKg,
required this.photoPath,
required this.esigPath,
required this.maidenName,
required this.deceased,
required this.uuidQrcode,
required this.titlePrefix,
required this.titleSuffix,
required this.showTitleId,
required this.ethnicity,
required this.disability,
required this.gender,
required this.religion,
required this.ip,
});
factory Profile.fromJson(Map<String, dynamic> json) => Profile(
id: json["id"],
lastName: json["last_name"],
firstName: json["first_name"],
middleName: json["middle_name"],
nameExtension: json["name_extension"],
sex: json["sex"],
birthdate: json['birthdate']==null?null:DateTime.parse(json["birthdate"]),
birthdate: DateTime.parse(json["birthdate"]),
civilStatus: json["civil_status"],
bloodType: json["blood_type"],
heightM: json["height_m"]?.toDouble(),
weightKg: json["weight_kg"],
weightKg: json["weight_kg"]?.toDouble(),
photoPath: json["photo_path"],
esigPath: json["esig_path"],
maidenName: json["maiden_name"],
maidenName: json["maiden_name"]==null?null:MaidenName.fromJson(json["maiden_name"]),
deceased: json["deceased"],
gender: json["gender"],
uuidQrcode: json["uuid_qrcode"],
titlePrefix: json["title_prefix"],
titleSuffix: json["title_suffix"],
showTitleId: json["show_title_id"],
);
ethnicity: json["ethnicity"]== null?null:json["ethnicity"]['name'],
disability: json["disability"] == null?null:json['disability']['name'],
gender: json["gender"] == null?null:json['gender']['name'],
religion: json["religion"] == null?null:json['religion']['name'],
ip: json["ip"]==null?null:json['ip']['name'],
);
Map<String, dynamic> toJson() => {
Map<String, dynamic> toJson() => {
"id": id,
"last_name": lastName,
"first_name": firstName,
"middle_name": middleName,
"name_extension": nameExtension,
"sex": sex,
"birthdate":
"${birthdate!.year.toString().padLeft(4, '0')}-${birthdate!.month.toString().padLeft(2, '0')}-${birthdate!.day.toString().padLeft(2, '0')}",
"birthdate": "${birthdate?.year.toString().padLeft(4, '0')}-${birthdate?.month.toString().padLeft(2, '0')}-${birthdate?.day.toString().padLeft(2, '0')}",
"civil_status": civilStatus,
"blood_type": bloodType,
"height_m": heightM,
@@ -86,10 +109,14 @@ class PrimaryInformation {
"esig_path": esigPath,
"maiden_name": maidenName,
"deceased": deceased,
"gender": gender,
"uuid_qrcode": uuidQrcode,
"title_prefix": titlePrefix,
"title_suffix": titleSuffix,
"show_title_id": showTitleId,
};
"ethnicity": ethnicity,
"disability": disability,
"gender": gender,
"religion": religion,
"ip": ip,
};
}
@@ -26,7 +26,7 @@ class EducationalBackground {
final String? periodTo;
final dynamic attachments;
final String? periodFrom;
final dynamic unitsEarned;
final int? unitsEarned;
final String? yearGraduated;
factory EducationalBackground.fromJson(Map<String, dynamic> json) => EducationalBackground(
+177 -132
View File
@@ -8,105 +8,122 @@ import 'dart:ffi';
import '../utils/category.dart';
import '../utils/position.dart';
FamilyBackground familyBackgroundFromJson(String str) => FamilyBackground.fromJson(json.decode(str));
FamilyBackground familyBackgroundFromJson(String str) =>
FamilyBackground.fromJson(json.decode(str));
String familyBackgroundToJson(FamilyBackground data) => json.encode(data.toJson());
String familyBackgroundToJson(FamilyBackground data) =>
json.encode(data.toJson());
class FamilyBackground {
FamilyBackground({
this.company,
this.position,
this.relationship,
this.relatedPerson,
this.companyAddress,
this.emergencyContact,
this.incaseOfEmergency,
this.companyContactNumber,
});
FamilyBackground({
this.company,
this.position,
this.relationship,
this.relatedPerson,
this.companyAddress,
this.emergencyContact,
this.incaseOfEmergency,
this.companyContactNumber,
});
final Company? company;
final Position? position;
final Relationship? relationship;
final RelatedPerson? relatedPerson;
final String? companyAddress;
final List<EmergencyContact>? emergencyContact;
final bool? incaseOfEmergency;
final String? companyContactNumber;
final Company? company;
final Position? position;
final Relationship? relationship;
final RelatedPerson? relatedPerson;
final String? companyAddress;
final List<EmergencyContact>? emergencyContact;
final bool? incaseOfEmergency;
final String? companyContactNumber;
factory FamilyBackground.fromJson(Map<String, dynamic> json) => FamilyBackground(
company: json["company"] == null ? null : Company.fromJson(json["company"]),
position: json["position"] == null ? null : Position.fromJson(json["position"]),
relationship: json["relationship"] == null ? null : Relationship.fromJson(json["relationship"]),
relatedPerson: json["related_person"] == null ? null : RelatedPerson.fromJson(json["related_person"]),
factory FamilyBackground.fromJson(Map<String, dynamic> json) =>
FamilyBackground(
company:
json["company"] == null ? null : Company.fromJson(json["company"]),
position: json["position"] == null
? null
: Position.fromJson(json["position"]),
relationship: json["relationship"] == null
? null
: Relationship.fromJson(json["relationship"]),
relatedPerson: json["related_person"] == null
? null
: RelatedPerson.fromJson(json["related_person"]),
companyAddress: json["company_address"],
emergencyContact: json["emergency_contact"] == null ? [] : List<EmergencyContact>.from(json["emergency_contact"]!.map((x) => EmergencyContact.fromJson(x))),
emergencyContact: json["emergency_contact"] == null
? []
: List<EmergencyContact>.from(json["emergency_contact"]!
.map((x) => EmergencyContact.fromJson(x))),
incaseOfEmergency: json["incase_of_emergency"],
companyContactNumber: json["company_contact_number"],
);
);
Map<String, dynamic> toJson() => {
Map<String, dynamic> toJson() => {
"company": company?.toJson(),
"position": position?.toJson(),
"relationship": relationship?.toJson(),
"related_person": relatedPerson?.toJson(),
"company_address": companyAddress,
"emergency_contact": emergencyContact == null ? [] : List<dynamic>.from(emergencyContact!.map((x) => x.toJson())),
"emergency_contact": emergencyContact == null
? []
: List<dynamic>.from(emergencyContact!.map((x) => x.toJson())),
"incase_of_emergency": incaseOfEmergency,
"company_contact_number": companyContactNumber,
};
};
}
class Company {
Company({
this.id,
this.name,
this.category,
this.privateEntity,
});
Company({
this.id,
this.name,
this.category,
this.privateEntity,
});
final int? id;
final String? name;
final Category? category;
final bool? privateEntity;
final int? id;
final String? name;
final Category? category;
final bool? privateEntity;
factory Company.fromJson(Map<String, dynamic> json) => Company(
factory Company.fromJson(Map<String, dynamic> json) => Company(
id: json["id"],
name: json["name"],
category: json["category"] == null ? null : Category.fromJson(json["category"]),
category: json["category"] == null
? null
: Category.fromJson(json["category"]),
privateEntity: json["private_entity"],
);
);
Map<String, dynamic> toJson() => {
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"category": category?.toJson(),
"private_entity": privateEntity,
};
};
}
class EmergencyContact {
EmergencyContact({
this.telco,
this.isactive,
this.provider,
this.isprimary,
this.numbermail,
this.serviceType,
this.contactinfoid,
this.commServiceId,
});
EmergencyContact({
this.telco,
this.isactive,
this.provider,
this.isprimary,
this.numbermail,
this.serviceType,
this.contactinfoid,
this.commServiceId,
});
final String? telco;
final bool? isactive;
final int? provider;
final bool? isprimary;
final String? numbermail;
final int? serviceType;
final int? contactinfoid;
final int? commServiceId;
final String? telco;
final bool? isactive;
final int? provider;
final bool? isprimary;
final String? numbermail;
final int? serviceType;
final int? contactinfoid;
final int? commServiceId;
factory EmergencyContact.fromJson(Map<String, dynamic> json) => EmergencyContact(
factory EmergencyContact.fromJson(Map<String, dynamic> json) =>
EmergencyContact(
telco: json["telco"],
isactive: json["isactive"],
provider: json["provider"],
@@ -115,9 +132,9 @@ class EmergencyContact {
serviceType: json["service_type"],
contactinfoid: json["contactinfoid"],
commServiceId: json["comm_service_id"],
);
);
Map<String, dynamic> toJson() => {
Map<String, dynamic> toJson() => {
"telco": telco,
"isactive": isactive,
"provider": provider,
@@ -126,69 +143,76 @@ class EmergencyContact {
"service_type": serviceType,
"contactinfoid": contactinfoid,
"comm_service_id": commServiceId,
};
};
}
class RelatedPerson {
RelatedPerson({
this.id,
this.sex,
this.gender,
this.deceased,
this.heightM,
this.birthdate,
this.esigPath,
this.lastName,
this.weightKg,
this.bloodType,
this.firstName,
this.photoPath,
this.maidenName,
this.middleName,
this.uuidQrcode,
this.civilStatus,
this.titlePrefix,
this.titleSuffix,
this.showTitleId,
this.nameExtension,
});
RelatedPerson({
required this.id,
required this.gender,
required this.sex,
required this.deceased,
required this.heightM,
required this.birthdate,
required this.esigPath,
required this.lastName,
required this.weightKg,
required this.bloodType,
required this.firstName,
required this.photoPath,
required this.maidenName,
required this.middleName,
required this.uuidQrcode,
required this.civilStatus,
required this.titlePrefix,
required this.titleSuffix,
required this.showTitleId,
required this.nameExtension,
});
final int? id;
final String? sex;
final String? gender;
final bool? deceased;
final double? heightM;
final DateTime? birthdate;
final String? esigPath;
final String? lastName;
final double? weightKg;
final String? bloodType;
final String? firstName;
final String? photoPath;
final dynamic maidenName;
final String? middleName;
final String? uuidQrcode;
final String? civilStatus;
final String? titlePrefix;
final String? titleSuffix;
final bool? showTitleId;
final String? nameExtension;
final int? id;
final String? sex;
final bool? deceased;
final String? gender;
final double? heightM;
final DateTime? birthdate;
final String? esigPath;
final String? lastName;
final double? weightKg;
final String? bloodType;
final String? firstName;
final String? photoPath;
final MaidenName? maidenName;
final String? middleName;
final String? uuidQrcode;
final String? civilStatus;
final String? titlePrefix;
final String? titleSuffix;
final bool? showTitleId;
final String? nameExtension;
factory RelatedPerson.fromJson(Map<String, dynamic> json) => RelatedPerson(
factory RelatedPerson.fromJson(Map<String, dynamic> json) => RelatedPerson(
id: json["id"],
sex: json["sex"],
gender: json["gender"],
deceased: json["deceased"],
heightM: json["height_m"] == null?null:double.parse(json["height_m"].toString()),
birthdate: json["birthdate"] == null ? null : DateTime.parse(json["birthdate"]),
heightM: json["height_m"] == null
? null
: double.parse(json["height_m"].toString()),
birthdate: json["birthdate"] == null
? null
: DateTime.parse(json["birthdate"]),
esigPath: json["esig_path"],
lastName: json["last_name"],
weightKg: json["weight_kg"] == null? null:double.parse(json["weight_kg"].toString()) ,
weightKg: json["weight_kg"] == null
? null
: double.parse(json["weight_kg"].toString()),
bloodType: json["blood_type"],
firstName: json["first_name"],
photoPath: json["photo_path"],
maidenName: json["maiden_name"],
maidenName: json["maiden_name"] == null
? null
: MaidenName.fromJson(json['maiden_name']),
middleName: json["middle_name"],
uuidQrcode: json["uuid_qrcode"],
civilStatus: json["civil_status"],
@@ -196,15 +220,16 @@ class RelatedPerson {
titleSuffix: json["title_suffix"],
showTitleId: json["show_title_id"],
nameExtension: json["name_extension"],
);
);
Map<String, dynamic> toJson() => {
Map<String, dynamic> toJson() => {
"id": id,
"sex": sex,
"gender": gender,
"deceased": deceased,
"height_m": heightM,
"birthdate": "${birthdate!.year.toString().padLeft(4, '0')}-${birthdate!.month.toString().padLeft(2, '0')}-${birthdate!.day.toString().padLeft(2, '0')}",
"birthdate":
"${birthdate!.year.toString().padLeft(4, '0')}-${birthdate!.month.toString().padLeft(2, '0')}-${birthdate!.day.toString().padLeft(2, '0')}",
"esig_path": esigPath,
"last_name": lastName,
"weight_kg": weightKg,
@@ -219,29 +244,49 @@ class RelatedPerson {
"title_suffix": titleSuffix,
"show_title_id": showTitleId,
"name_extension": nameExtension,
};
};
}
class Relationship {
Relationship({
this.id,
this.type,
this.category,
});
Relationship({
this.id,
this.type,
this.category,
});
final int? id;
final String? type;
final String? category;
final int? id;
final String? type;
final String? category;
factory Relationship.fromJson(Map<String, dynamic> json) => Relationship(
factory Relationship.fromJson(Map<String, dynamic> json) => Relationship(
id: json["id"],
type: json["type"],
category: json["category"],
);
);
Map<String, dynamic> toJson() => {
Map<String, dynamic> toJson() => {
"id": id,
"type": type,
"category": category,
};
};
}
class MaidenName {
final String? lastName;
final String? middleName;
MaidenName({
required this.lastName,
required this.middleName,
});
factory MaidenName.fromJson(Map<String, dynamic> json) => MaidenName(
lastName: json["last_name"],
middleName: json["middle_name"],
);
Map<String, dynamic> toJson() => {
"last_name": lastName,
"middle_name": middleName,
};
}
+11 -60
View File
@@ -4,8 +4,11 @@
import 'dart:convert';
import 'package:unit2/model/location/barangay.dart';
import '../location/city.dart';
import '../location/country.dart';
import '../utils/agency.dart';
import '../utils/industry_class.dart';
LearningDevelopement learningDevelopementFromJson(String str) => LearningDevelopement.fromJson(json.decode(str));
@@ -21,13 +24,13 @@ class LearningDevelopement {
});
final dynamic attachments;
final EdBy? sponsoredBy;
final Agency? sponsoredBy;
final ConductedTraining? conductedTraining;
final double? totalHoursAttended;
factory LearningDevelopement.fromJson(Map<String, dynamic> json) => LearningDevelopement(
attachments: json["attachments"],
sponsoredBy: json["sponsored_by"] == null ? null : EdBy.fromJson(json["sponsored_by"]),
sponsoredBy: json["sponsored_by"] == null ? null : Agency.fromJson(json["sponsored_by"]),
conductedTraining: json["conducted_training"] == null ? null : ConductedTraining.fromJson(json["conducted_training"]),
totalHoursAttended: json["total_hours_attended"],
);
@@ -62,8 +65,8 @@ class ConductedTraining {
final bool? locked;
final DateTime? toDate;
final DateTime? fromDate;
final int? totalHours;
final EdBy? conductedBy;
final double? totalHours;
final Agency? conductedBy;
final List<dynamic>? sessionsAttended;
final LearningDevelopmentType? learningDevelopmentType;
@@ -75,8 +78,8 @@ class ConductedTraining {
locked: json["locked"],
toDate: json["to_date"] == null ? null : DateTime.parse(json["to_date"]),
fromDate: json["from_date"] == null ? null : DateTime.parse(json["from_date"]),
totalHours: json["total_hours"],
conductedBy: json["conducted_by"] == null ? null : EdBy.fromJson(json["conducted_by"]),
totalHours: double.parse(json["total_hours"].toString()),
conductedBy: json["conducted_by"] == null ? null : Agency.fromJson(json["conducted_by"]),
sessionsAttended: json["sessions_attended"] == null ? [] : List<dynamic>.from(json["sessions_attended"]!.map((x) => x)),
learningDevelopmentType: json["learning_development_type"] == null ? null : LearningDevelopmentType.fromJson(json["learning_development_type"]),
);
@@ -96,58 +99,6 @@ class ConductedTraining {
};
}
class EdBy {
EdBy({
this.id,
this.name,
this.category,
this.privateEntity,
});
final int? id;
final String? name;
final SponsoredByCategory? category;
final bool? privateEntity;
factory EdBy.fromJson(Map<String, dynamic> json) => EdBy(
id: json["id"],
name: json["name"],
category: json["category"] == null ? null : SponsoredByCategory.fromJson(json["category"]),
privateEntity: json["private_entity"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"category": category?.toJson(),
"private_entity": privateEntity,
};
}
class SponsoredByCategory {
SponsoredByCategory({
this.id,
this.name,
this.industryClass,
});
final int? id;
final String? name;
final IndustryClass? industryClass;
factory SponsoredByCategory.fromJson(Map<String, dynamic> json) => SponsoredByCategory(
id: json["id"],
name: json["name"],
industryClass: json["industry_class"] == null ? null : IndustryClass.fromJson(json["industry_class"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"industry_class": industryClass?.toJson(),
};
}
class LearningDevelopmentType {
LearningDevelopmentType({
@@ -181,7 +132,7 @@ class Venue {
final int? id;
final Country? country;
final dynamic barangay;
final Barangay? barangay;
final VenueCategory? category;
final dynamic areaClass;
final CityMunicipality? cityMunicipality;
@@ -189,7 +140,7 @@ class Venue {
factory Venue.fromJson(Map<String, dynamic> json) => Venue(
id: json["id"],
country: json["country"] == null ? null : Country.fromJson(json["country"]),
barangay: json["barangay"],
barangay:json["barangay"] == null ? null : Barangay.fromJson(json["country"]),
category: json["category"] == null ? null : VenueCategory.fromJson(json["category"]),
areaClass: json["area_class"],
cityMunicipality: json["city_municipality"] == null ? null : CityMunicipality.fromJson(json["city_municipality"]),
+2 -2
View File
@@ -29,12 +29,12 @@ class VoluntaryWork {
final DateTime? toDate;
final Position? position;
final DateTime? fromDate;
final int? totalHours;
final double? totalHours;
factory VoluntaryWork.fromJson(Map<String, dynamic> json) => VoluntaryWork(
agency: json["agency"] == null ? null : Agency.fromJson(json["agency"]),
address: json["address"] == null ? null : Address.fromJson(json["address"]),
toDate: json["to_date"] == null? null : DateTime.parse(json['to_data']),
toDate: json["to_date"] == null? null : DateTime.parse(json['to_date']),
position: json["position"] == null ? null : Position.fromJson(json["position"]),
fromDate: json["from_date"] == null ? null : DateTime.parse(json["from_date"]),
totalHours: json["total_hours"],
@@ -9,10 +9,10 @@ import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/costum_divider.dart';
import 'package:unit2/widgets/text_icon.dart';
import '../../test_data.dart';
import '../../theme-data.dart/btn-style.dart';
import '../../theme-data.dart/form-style.dart';
import '../../utils/global.dart';
import '../../../test_data.dart';
import '../../../theme-data.dart/btn-style.dart';
import '../../../theme-data.dart/form-style.dart';
import '../../../utils/global.dart';
class RequetAutoReceipt extends StatefulWidget {
RequetAutoReceipt({super.key});
@@ -124,7 +124,7 @@ class _RequetAutoReceiptState extends State<RequetAutoReceipt> {
height: screenHeight * .06,
child: ElevatedButton(
style: secondaryBtnStyle(
second, Colors.transparent, Colors.white54),
primary, Colors.transparent, Colors.white54),
child: const Text(
requestAutoReceipt,
style: TextStyle(color: Colors.white),
+52
View File
@@ -0,0 +1,52 @@
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:unit2/bloc/docsms/docsms_bloc.dart';
import 'package:unit2/screens/docsms/components/request_receipt.dart';
import 'package:unit2/widgets/error_state.dart';
class AutoReceiveDocument extends StatefulWidget {
const AutoReceiveDocument({super.key});
@override
State<AutoReceiveDocument> createState() => _AutoReceiveDocumentState();
}
class _AutoReceiveDocumentState extends State<AutoReceiveDocument> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ProgressHUD(
padding: const EdgeInsets.all(24),
backgroundColor: Colors.black87,
indicatorWidget: const SpinKitFadingCircle(
color: Colors.white,
),
child: BlocConsumer<DocsmsBloc, DocsmsState>(
listener: (context, state) {
if (state is DocSmsLoadingState) {
final progress = ProgressHUD.of(context);
progress!.showWithText("Please wait...");
}
if (state is DocSmsErrorState || state is DocumentLoaded) {
final progress = ProgressHUD.of(context);
progress!.dismiss();
}
},
builder: (context, state) {
if (state is DocumentLoaded) {
return RequetAutoReceipt();
}if(state is DocSmsErrorState){
return SomethingWentWrong(message: state.message.toString(), onpressed: (){});
}
return Container();
},
),
),
);
}
}
@@ -0,0 +1,528 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:unit2/bloc/profile/primary_information/address/address_bloc.dart';
import 'package:unit2/model/location/address_category.dart';
import 'package:unit2/model/profile/basic_information/adress.dart';
import 'package:unit2/utils/global.dart';
import '../../../../../model/location/barangay.dart';
import '../../../../../model/location/city.dart';
import '../../../../../model/location/country.dart';
import '../../../../../model/location/provinces.dart';
import '../../../../../model/location/region.dart';
import '../../../../../theme-data.dart/btn-style.dart';
import '../../../../../theme-data.dart/colors.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../utils/location_utilities.dart';
import '../../../../../utils/text_container.dart';
import '../../../../../utils/validators.dart';
class AddAddressScreen extends StatefulWidget {
final int profileId;
final String token;
const AddAddressScreen(
{super.key, required this.profileId, required this.token});
@override
State<AddAddressScreen> createState() => _AddAddressScreenState();
}
class _AddAddressScreenState extends State<AddAddressScreen> {
////boolean
bool hasLotandBlock = false;
bool overseas = false;
bool provinceCall = false;
bool cityCall = false;
bool barangayCall = false;
////selected
AddressCategory? selectedAddressCategory;
String? selectedAreaClass;
Region? selectedRegion;
Province? selectedProvince;
CityMunicipality? selectedMunicipality;
Barangay? selectedBarangay;
Country? selectedCountry;
////Lists
final List<Area> areaClass = [
const Area(value: "Rural Area", group: 0),
const Area(value: "Sitio", group: 1),
const Area(value: "Village", group: 1),
const Area(value: "Urban Area", group: 0),
const Area(value: "Town", group: 1),
const Area(value: "City", group: 1),
const Area(value: "Metropolis", group: 1),
const Area(value: "Megacity", group: 1),
];
final List<AddressCategory> category = [
AddressCategory(id: 1, name: "Permanent", type: "home"),
AddressCategory(id: 2, name: "Residential", type: "home"),
AddressCategory(id: 3, name: "Birthplace", type: "home")
];
List<Province>? provinces;
List<CityMunicipality>? citymuns;
List<Barangay>? barangays;
final formKey = GlobalKey<FormBuilderState>();
@override
Widget build(BuildContext context) {
return BlocBuilder<AddressBloc, AddressState>(
builder: (context, state) {
if (state is AddAddressState) {
return FormBuilder(
key: formKey,
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 32, horizontal: 24),
child: SizedBox(
height: screenHeight * 88,
child: Column(
children: [
Flexible(
child: ListView(
children: [
//// category
FormBuilderDropdown(
validator: FormBuilderValidators.required(
errorText: "This field is required"),
decoration:
normalTextFieldStyle("Category*", "Category"),
name: "category",
onChanged: (AddressCategory? category) {
selectedAddressCategory = category;
},
items: category
.map<DropdownMenuItem<AddressCategory>>(
(AddressCategory category) {
return DropdownMenuItem(
value: category, child: Text(category.name!));
}).toList()),
const SizedBox(
height: 12,
),
////Area Class
FormBuilderDropdown(
decoration: normalTextFieldStyle(
"Area class *", "Area class"),
name: "area_class",
onChanged: (Area? area) {
selectedAreaClass = area!.value;
},
items: areaClass
.map<DropdownMenuItem<Area>>((Area area) {
return area.group == 0
? DropdownMenuItem(
enabled: false,
value: area,
child: Text(area.value.toUpperCase(),
style: const TextStyle(
color: Colors.black38)))
: DropdownMenuItem(
value: area,
enabled: true,
child: Text(
" ${area.value.toUpperCase()}"));
}).toList()),
const SizedBox(
height: 12,
),
////stateful builder
StatefulBuilder(builder: (context, setState) {
return Column(
children: [
////with block & Lot Switch
FormBuilderSwitch(
initialValue: hasLotandBlock,
activeColor: second,
onChanged: (value) {
setState(() {
hasLotandBlock = value!;
});
},
decoration: normalTextFieldStyle(
"With Lot and Block?", 'Graduated?'),
name: 'graudated',
title: Text(hasLotandBlock ? "YES" : "NO"),
),
SizedBox(
height: hasLotandBlock ? 12 : 0,
),
SizedBox(
width: screenWidth,
child: hasLotandBlock
? Row(
children: [
////block #
Flexible(
flex: 1,
child: FormBuilderTextField(
validator: FormBuilderValidators
.compose([numericRequired]),
keyboardType:
TextInputType.number,
name: "block_number",
decoration:
normalTextFieldStyle(
"Block #*", "Block #"),
)),
const SizedBox(
width: 8,
),
//// lot #
Flexible(
flex: 1,
child: FormBuilderTextField(
validator: FormBuilderValidators
.compose([numericRequired]),
name: "lot_number",
keyboardType:
TextInputType.number,
decoration:
normalTextFieldStyle(
"Lot #*", "Lot #"),
)),
],
)
: Container(),
),
],
);
}),
const SizedBox(
height: 12,
),
//// Address Line
FormBuilderTextField(
name: "address_line",
decoration: normalTextFieldStyle(
"Address Line ", "Address Line"),
),
const SizedBox(
height: 12,
),
StatefulBuilder(builder: (context, setState) {
return Column(
children: [
FormBuilderSwitch(
initialValue: overseas,
activeColor: second,
onChanged: (value) {
setState(() {
overseas = value!;
});
},
decoration: normalTextFieldStyle(
"Overseas Address?", ''),
name: 'overseas',
title: Text(overseas ? "YES" : "NO"),
),
SizedBox(
height: overseas == true ? 8 : 0,
),
SizedBox(
child: overseas == false
? Column(
children: [
const SizedBox(
height: 12,
),
////REGION DROPDOWN
FormBuilderDropdown<Region?>(
autovalidateMode: AutovalidateMode
.onUserInteraction,
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
onChanged: (Region? region) async {
if (selectedRegion != region) {
setState(() {
provinceCall = true;
});
selectedRegion = region;
getProvinces();
}
},
initialValue: null,
decoration: normalTextFieldStyle(
"Region*", "Region"),
name: 'region',
items: state.regions
.map<DropdownMenuItem<Region>>(
(Region region) {
return DropdownMenuItem<Region>(
value: region,
child: Text(
region.description!));
}).toList(),
),
const SizedBox(
height: 8,
),
//// PROVINCE DROPDOWN
SizedBox(
height: 60,
child: ModalProgressHUD(
color: Colors.transparent,
inAsyncCall: provinceCall,
child: DropdownButtonFormField<
Province?>(
autovalidateMode:
AutovalidateMode
.onUserInteraction,
validator: (value) =>
value == null
? 'required'
: null,
isExpanded: true,
value: selectedProvince,
onChanged:
(Province? province) {
if (selectedProvince !=
province) {
setState(() {
cityCall = true;
});
selectedProvince =
province;
getCities();
}
},
items: provinces == null
? []
: provinces!.map<
DropdownMenuItem<
Province>>(
(Province province) {
return DropdownMenuItem(
value: province,
child: FittedBox(
child: Text(province
.description!),
));
}).toList(),
decoration:
normalTextFieldStyle(
"Province*",
"Province")),
),
),
////CITY MUNICIPALITY
SizedBox(
height: 60,
child: ModalProgressHUD(
color: Colors.white,
inAsyncCall: cityCall,
child: DropdownButtonFormField<
CityMunicipality>(
validator: FormBuilderValidators
.required(
errorText:
"This field is required"),
isExpanded: true,
onChanged:
(CityMunicipality? city) {
if (selectedMunicipality !=
city) {
setState(() {
barangayCall = true;
});
selectedMunicipality = city;
getBarangays();
}
},
decoration:
normalTextFieldStyle(
"Municipality*",
"Municipality"),
value: selectedMunicipality,
items: citymuns == null
? []
: citymuns!.map<
DropdownMenuItem<
CityMunicipality>>(
(CityMunicipality c) {
return DropdownMenuItem(
value: c,
child: Text(c
.description!));
}).toList(),
),
),
),
//// BARANGAY
SizedBox(
height: 60,
child: ModalProgressHUD(
color: Colors.white,
inAsyncCall: barangayCall,
child: DropdownButtonFormField<
Barangay>(
isExpanded: true,
onChanged: (Barangay? baragay) {
selectedBarangay = baragay;
},
decoration:
normalTextFieldStyle(
"Barangay*",
"Barangay"),
value: selectedBarangay,
items: barangays == null
? []
: barangays!.map<
DropdownMenuItem<
Barangay>>(
(Barangay barangay) {
return DropdownMenuItem(
value: barangay,
child: Text(barangay
.description!));
}).toList(),
),
),
),
],
)
//// COUNTRY DROPDOWN
: SizedBox(
height: 60,
child: FormBuilderDropdown<Country>(
initialValue: null,
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
items: state.countries
.map<DropdownMenuItem<Country>>(
(Country country) {
return DropdownMenuItem<Country>(
value: country,
child: FittedBox(
child:
Text(country.name!)));
}).toList(),
name: 'country',
decoration: normalTextFieldStyle(
"Country*", "Country"),
onChanged: (Country? value) {
selectedCountry = value;
},
),
),
),
],
);
}),
////sumit button
],
),
),
SizedBox(
width: double.infinity,
height: 60,
child: ElevatedButton(
style:
mainBtnStyle(primary, Colors.transparent, second),
onPressed: () {
if (formKey.currentState!.saveAndValidate()) {
String? lotNumber;
String? blockNumber;
String? addressLine;
Country country = selectedCountry ??= Country(
id: 175, name: 'Philippines', code: 'PH');
AddressClass address = AddressClass(
barangay: selectedBarangay,
id: null,
category: null,
areaClass: selectedAreaClass,
cityMunicipality: selectedMunicipality,
country: country);
if (hasLotandBlock) {
lotNumber =
formKey.currentState!.value['lot_number'];
blockNumber =
formKey.currentState!.value['block_number'];
}
addressLine =
formKey.currentState?.value['address_line'];
final progress = ProgressHUD.of(context);
progress!.showWithText("Loading...");
context.read<AddressBloc>().add(AddAddress(
address: address,
profileId: widget.profileId,
token: widget.token,
blockNumber: blockNumber != null
? int.parse(blockNumber)
: null,
categoryId: selectedAddressCategory!.id!,
details: addressLine,
lotNumber: lotNumber != null
? int.parse(lotNumber)
: null));
}
},
child: const Text(submit)),
),
],
),
),
));
}
return Placeholder();
},
);
}
Future<void> getProvinces() async {
try {
List<Province> newProvinces = await LocationUtils.instance
.getProvinces(regionCode: selectedRegion!.code.toString());
setState(() {
provinces = newProvinces;
selectedProvince = provinces![0];
provinceCall = false;
cityCall = true;
getCities();
});
} catch (e) {
context.read<AddressBloc>().add(CallErrorState());
}
}
Future<void> getCities() async {
try {
List<CityMunicipality> newCities = await LocationUtils.instance
.getCities(code: selectedProvince!.code.toString());
citymuns = newCities;
setState(() {
selectedMunicipality = newCities[0];
cityCall = false;
barangayCall = true;
getBarangays();
});
} catch (e) {
context.read<AddressBloc>().add(CallErrorState());
}
}
Future<void> getBarangays() async {
try {
List<Barangay> newBarangays = await LocationUtils.instance
.getBarangay(code: selectedMunicipality!.code.toString());
barangays = newBarangays;
setState(() {
selectedBarangay = newBarangays[0];
barangayCall = false;
});
} catch (e) {
context.read<AddressBloc>().add(CallErrorState());
}
}
}
class Area {
final int group;
final String value;
const Area({required this.group, required this.value});
}
@@ -0,0 +1,677 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:unit2/bloc/profile/primary_information/address/address_bloc.dart';
import 'package:unit2/model/location/address_category.dart';
import 'package:unit2/model/profile/basic_information/adress.dart';
import 'package:unit2/utils/global.dart';
import '../../../../../model/location/barangay.dart';
import '../../../../../model/location/city.dart';
import '../../../../../model/location/country.dart';
import '../../../../../model/location/provinces.dart';
import '../../../../../model/location/region.dart';
import '../../../../../theme-data.dart/btn-style.dart';
import '../../../../../theme-data.dart/colors.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../utils/location_utilities.dart';
import '../../../../../utils/text_container.dart';
import '../../../../../utils/validators.dart';
class EditAddressScreen extends StatefulWidget {
final int profileId;
final String token;
const EditAddressScreen(
{super.key, required this.profileId, required this.token});
@override
State<EditAddressScreen> createState() => _EditAddressScreenState();
}
class _EditAddressScreenState extends State<EditAddressScreen> {
////boolean
bool hasLotandBlock = false;
bool overseas = false;
bool provinceCall = false;
bool cityCall = false;
bool barangayCall = false;
////selected
AddressCategory? selectedAddressCategory;
Area? selectedAreaClass;
Region? selectedRegion;
Province? selectedProvince;
CityMunicipality? selectedMunicipality;
Barangay? selectedBarangay;
Country? selectedCountry;
////Lists
final List<Area> areaClass = [
const Area(value: "Rural Area", group: 0),
const Area(value: "Sitio", group: 1),
const Area(value: "Village", group: 1),
const Area(value: "Urban Area", group: 0),
const Area(value: "Town", group: 1),
const Area(value: "City", group: 1),
const Area(value: "Metropolis", group: 1),
const Area(value: "Megacity", group: 1),
];
final List<AddressCategory> category = [
AddressCategory(id: 1, name: "Permanent", type: "home"),
AddressCategory(id: 2, name: "Residential", type: "home"),
AddressCategory(id: 3, name: "Birthplace", type: "home")
];
List<Province>? provinces;
List<CityMunicipality>? citymuns;
List<Barangay>? barangays;
final formKey = GlobalKey<FormBuilderState>();
@override
Widget build(BuildContext context) {
return BlocBuilder<AddressBloc, AddressState>(
builder: (context, state) {
if (state is EditAddressState) {
overseas = state.overseas;
if (!overseas) {
selectedRegion = state.currentRegion;
provinces = state.provinces;
selectedProvince = state.currentProvince;
citymuns = state.cities;
selectedMunicipality = state.currentCity;
barangays = state.baragays;
selectedBarangay = state.currentBarangay;
selectedCountry = state.currentCountry;
} else {
selectedCountry = state.currentCountry;
}
selectedAddressCategory = category.firstWhere(
(AddressCategory category) =>
category.id == state.address.address!.category!.id);
if (state.address.address?.areaClass != null) {
selectedAreaClass = areaClass.firstWhere((Area area) =>
area.value.toLowerCase() ==
state.address.address!.areaClass!.toLowerCase());
} else {
selectedAreaClass = null;
}
if (state.address.subdivision != null) {
hasLotandBlock = true;
} else {
hasLotandBlock = false;
}
return FormBuilder(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 32, horizontal: 24),
child: SizedBox(
height: screenHeight * 88,
child: Column(
children: [
Flexible(
child: ListView(
children: [
//// category
FormBuilderDropdown(
initialValue: selectedAddressCategory,
validator: FormBuilderValidators.required(
errorText: "This field is required"),
decoration:
normalTextFieldStyle("Category*", "Category"),
name: "category",
onChanged: (AddressCategory? category) {
selectedAddressCategory = category;
},
items: category
.map<DropdownMenuItem<AddressCategory>>(
(AddressCategory category) {
return DropdownMenuItem(
value: category, child: Text(category.name!));
}).toList()),
const SizedBox(
height: 12,
),
////Area Class
FormBuilderDropdown(
initialValue: selectedAreaClass,
decoration: normalTextFieldStyle(
"Area class *", "Area class"),
name: "area_class",
onChanged: (Area? area) {
selectedAreaClass = area;
},
items: areaClass
.map<DropdownMenuItem<Area>>((Area area) {
return area.group == 0
? DropdownMenuItem(
enabled: false,
value: area,
child: Text(area.value.toUpperCase(),
style: const TextStyle(
color: Colors.black38)))
: DropdownMenuItem(
value: area,
enabled: true,
child: Text(
" ${area.value.toUpperCase()}"));
}).toList()),
const SizedBox(
height: 12,
),
////stateful builder
StatefulBuilder(builder: (context, setState) {
return Column(
children: [
////with block & Lot Switch
FormBuilderSwitch(
initialValue: hasLotandBlock,
activeColor: second,
onChanged: (value) {
setState(() {
hasLotandBlock = value!;
});
},
decoration: normalTextFieldStyle(
"With Lot and Block?", 'Graduated?'),
name: 'graudated',
title: Text(hasLotandBlock ? "YES" : "NO"),
),
SizedBox(
height: hasLotandBlock ? 12 : 0,
),
SizedBox(
width: screenWidth,
child: hasLotandBlock
? Row(
children: [
////block #
Flexible(
flex: 1,
child: FormBuilderTextField(
initialValue: state.address
.subdivision?.blockNo
?.toString(),
validator: FormBuilderValidators
.compose([numericRequired]),
keyboardType:
TextInputType.number,
name: "block_number",
decoration:
normalTextFieldStyle(
"Block #*", "Block #"),
)),
const SizedBox(
width: 8,
),
//// lot #
Flexible(
flex: 1,
child: FormBuilderTextField(
initialValue: state
.address.subdivision?.lotNo
?.toString(),
validator: FormBuilderValidators
.compose([numericRequired]),
name: "lot_number",
keyboardType:
TextInputType.number,
decoration:
normalTextFieldStyle(
"Lot #*", "Lot #"),
)),
],
)
: Container(),
),
],
);
}),
const SizedBox(
height: 12,
),
//// Address Line
FormBuilderTextField(
initialValue: state.address.details,
name: "address_line",
decoration: normalTextFieldStyle(
"Address Line *", "Address Line"),
),
const SizedBox(
height: 12,
),
StatefulBuilder(builder: (context, setState) {
return Column(
children: [
FormBuilderSwitch(
initialValue: overseas,
activeColor: second,
onChanged: (value) {
setState(() {
overseas = value!;
});
},
decoration: normalTextFieldStyle(
"Overseas Address?", ''),
name: 'overseas',
title: Text(overseas ? "YES" : "NO"),
),
SizedBox(
height: overseas == true ? 8 : 0,
),
SizedBox(
child: overseas == false
? Column(
children: [
const SizedBox(
height: 12,
),
////REGION DROPDOWN
DropdownButtonFormField<Region?>(
isExpanded: true,
value: selectedRegion,
autovalidateMode: AutovalidateMode
.onUserInteraction,
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
onChanged: (Region? region) async {
if (selectedRegion != region) {
setState(() {
provinceCall = true;
});
selectedRegion = region;
//// GET PROVINCES
provinces = await LocationUtils
.instance
.getProvinces(
regionCode:
selectedRegion!.code
.toString());
selectedProvince =
provinces![0];
setState(() {
provinceCall = false;
cityCall = true;
});
//// GET CITIES
citymuns = await LocationUtils
.instance
.getCities(
code: selectedProvince!
.code!);
selectedMunicipality =
citymuns![0];
setState(() {
cityCall = false;
barangayCall = true;
});
//// GET BARANGAY
barangays = await LocationUtils
.instance
.getBarangay(
code:
selectedMunicipality!
.code!);
selectedBarangay =
barangays![0];
setState(() {
barangayCall = false;
});
////GET CITY MUNICIPALITY
citymuns = await LocationUtils
.instance
.getCities(
code: selectedProvince!
.code!);
selectedMunicipality =
citymuns![0];
setState(() {
cityCall = false;
barangayCall = true;
});
//// GET BARANGAYS
barangays = await LocationUtils
.instance
.getBarangay(
code:
selectedMunicipality!
.code!);
selectedBarangay =
barangays![0];
setState(() {
barangayCall = false;
});
}
},
decoration: normalTextFieldStyle(
"Region*", "Region"),
items: state.regions
.map<DropdownMenuItem<Region>>(
(Region region) {
return DropdownMenuItem<Region>(
value: region,
child: Text(
region.description!));
}).toList(),
),
const SizedBox(
height: 8,
),
//// PROVINCE DROPDOWN
SizedBox(
height: 60,
child: ModalProgressHUD(
color: Colors.transparent,
inAsyncCall: provinceCall,
child: DropdownButtonFormField<
Province?>(
autovalidateMode:
AutovalidateMode
.onUserInteraction,
validator: (value) =>
value == null
? 'required'
: null,
isExpanded: true,
value: selectedProvince,
onChanged: (Province?
province) async {
if (selectedProvince !=
province) {
selectedProvince =
province;
setState(() {
cityCall = true;
});
//// GET CITIES
citymuns = await LocationUtils
.instance
.getCities(
code:
selectedProvince!
.code!);
selectedMunicipality =
citymuns![0];
setState(() {
cityCall = false;
barangayCall = true;
});
//// GET BARANGAY
barangays = await LocationUtils
.instance
.getBarangay(
code:
selectedMunicipality!
.code!);
selectedBarangay =
barangays![0];
setState(() {
barangayCall = false;
});
}
},
items: provinces == null
? []
: provinces!.map<
DropdownMenuItem<
Province>>(
(Province province) {
return DropdownMenuItem(
value: province,
child: FittedBox(
child: Text(province
.description!),
));
}).toList(),
decoration:
normalTextFieldStyle(
"Province*",
"Province")),
),
),
////CITY MUNICIPALITY
SizedBox(
height: 60,
child: ModalProgressHUD(
color: Colors.white,
inAsyncCall: cityCall,
child: DropdownButtonFormField<
CityMunicipality>(
validator: FormBuilderValidators
.required(
errorText:
"This field is required"),
isExpanded: true,
onChanged: (CityMunicipality?
city) async {
if (selectedMunicipality !=
city) {
setState(() {
barangayCall = true;
});
selectedMunicipality = city;
selectedMunicipality = city;
//// GET BARANGAYS
barangays = await LocationUtils
.instance
.getBarangay(
code:
selectedMunicipality!
.code!);
selectedBarangay =
barangays![0];
setState(() {
barangayCall = false;
});
}
},
decoration:
normalTextFieldStyle(
"Municipality*",
"Municipality"),
value: selectedMunicipality,
items: citymuns == null
? []
: citymuns!.map<
DropdownMenuItem<
CityMunicipality>>(
(CityMunicipality c) {
return DropdownMenuItem(
value: c,
child: Text(c
.description!));
}).toList(),
),
),
),
//// BARANGAY
SizedBox(
height: 60,
child: ModalProgressHUD(
color: Colors.white,
inAsyncCall: barangayCall,
child: DropdownButtonFormField<
Barangay>(
isExpanded: true,
onChanged: (Barangay? baragay) {
selectedBarangay = baragay;
},
decoration:
normalTextFieldStyle(
"Barangay*",
"Barangay"),
value: selectedBarangay,
items: barangays == null
? []
: barangays!.map<
DropdownMenuItem<
Barangay>>(
(Barangay barangay) {
return DropdownMenuItem(
value: barangay,
child: Text(barangay
.description!));
}).toList(),
),
),
),
],
)
//// COUNTRY DROPDOWN
: SizedBox(
height: 60,
child: FormBuilderDropdown<Country>(
initialValue:selectedCountry!.id == 175?null:selectedCountry,
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
items: state.countries
.map<DropdownMenuItem<Country>>(
(Country country) {
return DropdownMenuItem<Country>(
value: country,
child: FittedBox(
child:
Text(country.name!)));
}).toList(),
name: 'country',
decoration: normalTextFieldStyle(
"Country*", "Country"),
onChanged: (Country? value) {
setState((){
selectedCountry = value;
});
},
),
),
),
],
);
}),
],
),
),
SizedBox(
width: double.infinity,
height: 60,
child: ElevatedButton(
style: mainBtnStyle(
primary, Colors.transparent, second),
onPressed: () {
if (formKey.currentState!.saveAndValidate()) {
String? lotNumber;
String? blockNumber;
String? addressLine;
if (overseas) {
selectedCountry = selectedCountry;
} else {
selectedCountry = Country(
id: 175,
name: 'Philippines',
code: 'PH');
}
AddressClass address = AddressClass(
barangay:
overseas ? null : selectedBarangay,
id: state.address.id,
category: null,
areaClass: selectedAreaClass?.value,
cityMunicipality: overseas
? null
: selectedMunicipality,
country: selectedCountry);
if (hasLotandBlock) {
lotNumber = formKey
.currentState!.value['lot_number'];
blockNumber = formKey
.currentState!.value['block_number'];
}
addressLine = formKey
.currentState?.value['address_line'];
final progress = ProgressHUD.of(context);
progress!.showWithText("Loading...");
context.read<AddressBloc>().add(UpdateAddress(
address: address,
profileId: widget.profileId,
token: widget.token,
blockNumber: blockNumber != null
? int.parse(blockNumber)
: null,
categoryId: selectedAddressCategory!.id!,
details: addressLine,
lotNumber: lotNumber != null
? int.parse(lotNumber)
: null));
}
},
child: const Text(submit)),
),
],
),
),
));
}
return Placeholder();
},
);
}
Future<void> getProvinces() async {
try {
List<Province> newProvinces = await LocationUtils.instance
.getProvinces(regionCode: selectedRegion!.code.toString());
setState(() {
provinces = newProvinces;
selectedProvince = provinces![0];
provinceCall = false;
cityCall = true;
getCities();
});
} catch (e) {
context.read<AddressBloc>().add(CallErrorState());
}
}
Future<void> getCities() async {
try {
List<CityMunicipality> newCities = await LocationUtils.instance
.getCities(code: selectedProvince!.code.toString());
citymuns = newCities;
setState(() {
selectedMunicipality = newCities[0];
cityCall = false;
barangayCall = true;
getBarangays();
});
} catch (e) {
context.read<AddressBloc>().add(CallErrorState());
}
}
Future<void> getBarangays() async {
try {
List<Barangay> newBarangays = await LocationUtils.instance
.getBarangay(code: selectedMunicipality!.code.toString());
barangays = newBarangays;
setState(() {
selectedBarangay = newBarangays[0];
barangayCall = false;
});
} catch (e) {
context.read<AddressBloc>().add(CallErrorState());
}
}
}
class Area {
final int group;
final String value;
const Area({required this.group, required this.value});
}
@@ -1,35 +1,56 @@
import 'package:app_popup_menu/app_popup_menu.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:unit2/bloc/profile/primary_information/address/address_bloc.dart';
import 'package:unit2/bloc/profile/profile_bloc.dart';
import 'package:unit2/bloc/user/user_bloc.dart';
import 'package:unit2/model/profile/basic_information/adress.dart';
import 'package:unit2/screens/profile/components/basic_information/address/add_modal.dart';
import 'package:unit2/screens/profile/components/basic_information/address/edit_modal.dart';
import 'package:unit2/theme-data.dart/box_shadow.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/utils/global.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/Leadings/add_leading.dart';
import 'package:unit2/widgets/Leadings/close_leading.dart';
import 'package:unit2/widgets/empty_data.dart';
import 'package:unit2/widgets/error_state.dart';
class AddressScreen extends StatelessWidget {
import '../../../../utils/alerts.dart';
class AddressScreen extends StatelessWidget {
const AddressScreen({super.key});
@override
Widget build(BuildContext context) {
int? profileId;
String? token;
return Scaffold(
appBar: AppBar(
title: const Text(adressScreenTitle),
title: context.watch<AddressBloc>().state is AddAddressState?const Text("Add Address"):context.watch<AddressBloc>().state is EditAddressState?const Text("Edit Address"):const Text("Addresses"),
centerTitle: true,
backgroundColor: primary,
actions: [AddLeading(onPressed: () {})],
actions:(context.watch<AddressBloc>().state is AddressLoadedState)?[
AddLeading(onPressed: () {
context.read<AddressBloc>().add(ShowAddAddressForm());
})
]:(context.watch<AddressBloc>().state is AddAddressState || context.watch<AddressBloc>().state is EditAddressState)?[
CloseLeading(onPressed:() {
context.read<AddressBloc>().add(LoadAddress());
})
]:[]
),
body: ProgressHUD(
padding: const EdgeInsets.all(24),
indicatorWidget: const SpinKitFadingCircle(
color: Colors.white,
),
backgroundColor: Colors.black87,
child: BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
if (state is UserLoggedIn) {
token = state.userData!.user!.login!.token;
profileId = state.userData!.user!.login!.user!.profileId;
return BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
if (state is ProfileLoaded) {
@@ -40,15 +61,71 @@ class AddressScreen extends StatelessWidget {
progress!.showWithText("Please wait...");
}
if (state is AddressLoadedState ||
state is AddressErrorState) {
state is AddressErrorState ||
state is AddAddressState ||
state is EditAddressState ||
state is AddressAddedState || state is EditAddressState || state is AddressUpdatedState) {
final progress = ProgressHUD.of(context);
progress!.dismiss();
}
////Added State
if (state is AddressAddedState) {
if (state.response['success']) {
successAlert(context, "Adding Successfull!",
state.response['message'], () {
Navigator.of(context).pop();
context.read<AddressBloc>().add(LoadAddress());
});
} else {
errorAlert(context, "Adding Failed",
state.response['message'], () {
Navigator.of(context).pop();
context.read<AddressBloc>().add(LoadAddress());
});
}
}
////updated State
if (state is AddressUpdatedState) {
if (state.response['success']) {
successAlert(context, "Update Successfull!",
state.response['message'], () {
Navigator.of(context).pop();
context.read<AddressBloc>().add(LoadAddress());
});
} else {
errorAlert(context, "Update Failed",
state.response['message'], () {
Navigator.of(context).pop();
context.read<AddressBloc>().add(LoadAddress());
});
}
}
//// Deleted
if (state is AddressDeletedState) {
if (state.success) {
successAlert(context, "Delete Successfull",
"Address has been deleted successfully", () {
Navigator.of(context).pop();
context.read<AddressBloc>().add(LoadAddress());
});
} else {
errorAlert(context, "Deletion Failed",
"Error deleting Address", () {
Navigator.of(context).pop();
context.read<AddressBloc>().add(LoadAddress());
});
}
}
},
builder: (context, state) {
if (state is AddressLoadedState) {
bool overseas;
String? cityMunicipality;
String? province;
String? region;
String? barangay;
if (state.addresses.isNotEmpty) {
return ListView.builder(
return ListView.builder(
padding: const EdgeInsets.symmetric(
vertical: 8, horizontal: 10),
itemCount: state.addresses.length,
@@ -56,31 +133,38 @@ class AddressScreen extends StatelessWidget {
(BuildContext context, int index) {
String? subdivision =
state.addresses[index].details ?? '';
String category = state.addresses[index]
.address!
.category!
.name!;
String? barangay = state.addresses[index]
.address!
.barangay !=
null
? '${state.addresses[index].address!.barangay!.description!.toUpperCase()},'
: '';
String cityMunicipality = state.addresses[index]
.address!
.cityMunicipality!
.description!;
String province = state.addresses[index]
.address!
.cityMunicipality!
.province!
.description!;
String region = state.addresses[index]
.address!
.cityMunicipality!
.province!
.region!
.description!;
String? category = state.addresses[index]
.address?.category?.name??'';
if (state.addresses[index].address?.cityMunicipality != null) {
barangay = state.addresses[index].address!
.barangay !=
null
? '${state.addresses[index].address!.barangay!.description!.toUpperCase()},'
: '';
cityMunicipality = state
.addresses[index]
.address!
.cityMunicipality!
.description!;
province = state
.addresses[index]
.address!
.cityMunicipality!
.province!
.description!;
region = state
.addresses[index]
.address!
.cityMunicipality!
.province!
.region!
.description!;
overseas = false;
} else {
overseas = true;
}
return Column(
children: [
Column(
@@ -94,46 +178,137 @@ class AddressScreen extends StatelessWidget {
child: Row(children: [
Expanded(
child: Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
subdivision,
style:
Theme.of(context)
.textTheme
.titleMedium,
),
const SizedBox(
width: 5,
),
Text(
category,
style:
Theme.of(context)
.textTheme
.bodySmall,
)
],
SizedBox(
width: screenWidth,
child: Row(
children: [
Flexible(
child: Text(
subdivision,
style:
Theme.of(context)
.textTheme
.titleMedium!.copyWith(color: primary,fontWeight: FontWeight.w600),
),
),
SizedBox(
width: subdivision.isEmpty? 0: 24,
),
Flexible(
child: Text(
category,
style:
Theme.of(context)
.textTheme
.bodySmall,
),
)
],
),
),
const Divider(),
const SizedBox(
height: 5,
),
Text(
"$barangay $cityMunicipality, $province, $region",
style: Theme.of(context)
.textTheme
.labelLarge,
height: 8,
),
Container(
child: overseas
? Text(
"COUNTRY: ${state.addresses[index].address?.country?.name?.toUpperCase()}",
textAlign:
TextAlign
.start,
style: Theme.of(
context)
.textTheme
.titleSmall,
)
: Text(
"$barangay $cityMunicipality, $province, $region",
style: Theme.of(
context)
.textTheme
.titleSmall,
)),
],
)),
IconButton(
onPressed: () {},
icon: const Icon(
Icons.more_vert,
color: Colors.grey,
))
AppPopupMenu<int>(
offset:
const Offset(-10, -10),
elevation: 3,
onSelected: (value) {
////delete eligibilty-= = = = = = = = =>>
if (value == 2) {
confirmAlert(context, () {
final progress =
ProgressHUD.of(
context);
progress!.showWithText(
"Loading...");
context
.read<AddressBloc>()
.add(DeleteAddress(
id: state
.addresses[
index]
.id!,
profileId: profileId
.toString(),
token: token!));
}, "Delete?",
"Confirm Delete?");
}
if (value == 1) {
bool overseas;
////edit eligibilty-= = = = = = = = =>>
final progress =
ProgressHUD.of(
context);
progress!.showWithText(
"Loading...");
if (state
.addresses[index]
.address
?.cityMunicipality ==
null) {
overseas = true;
} else {
overseas = false;
}
context
.read<AddressBloc>()
.add(ShowEditAddressForm(
overseas:
overseas,
address: state
.addresses[
index]));
}
},
menuItems: [
popMenuItem(
text: "Update",
value: 1,
icon: Icons.edit),
popMenuItem(
text: "Remove",
value: 2,
icon: Icons.delete),
],
icon: const Icon(
Icons.more_vert,
color: Colors.grey,
),
tooltip: "Options",
)
]),
),
],
@@ -145,11 +320,23 @@ class AddressScreen extends StatelessWidget {
);
});
} else {
const EmptyData(
return const EmptyData(
message:
"You don't have address added. Please click + to add.");
}
}
if (state is AddressErrorState) {
return SomethingWentWrong(
message: state.message, onpressed: () {context.read<AddressBloc>().add(LoadAddress());});
}
if (state is AddAddressState) {
return AddAddressScreen(
profileId: profileId!, token: token!);
}
if (state is EditAddressState) {
return EditAddressScreen(
profileId: profileId!, token: token!);
}
return Container();
},
);
@@ -163,4 +350,23 @@ class AddressScreen extends StatelessWidget {
),
));
}
PopupMenuItem<int> popMenuItem({String? text, int? value, IconData? icon}) {
return PopupMenuItem(
value: value,
child: Row(
children: [
Icon(
icon,
),
const SizedBox(
width: 10,
),
Text(
text!,
),
],
),
);
}
}
@@ -0,0 +1,16 @@
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}
@@ -0,0 +1,37 @@
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class CitizenshipLoading extends StatelessWidget {
const CitizenshipLoading({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 120,
width: 120,
decoration: const BoxDecoration(
color: Colors.black87,
borderRadius: BorderRadius.all(Radius.circular(8))),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
SpinKitFadingCircle(size: 42, color: Colors.white),
SizedBox(
height: 12,
),
Text(
"Please wait..",
style: TextStyle(color: Colors.white),
),
],
),
),
),
);
}
}
@@ -1,46 +1,450 @@
import 'package:app_popup_menu/app_popup_menu.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttericon/font_awesome5_icons.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:unit2/bloc/profile/primary_information/citizenship/citizenship_bloc.dart';
import 'package:unit2/model/profile/basic_information/citizenship.dart';
import 'package:unit2/screens/profile/components/basic_information/citizenship/loading.dart';
import 'package:unit2/theme-data.dart/btn-style.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/utils/global.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/Leadings/add_leading.dart';
import 'package:unit2/widgets/error_state.dart';
import '../../../../model/location/country.dart';
import '../../../../theme-data.dart/form-style.dart';
import '../../../../utils/alerts.dart';
class CitizenShipScreen extends StatefulWidget {
final List<Citizenship> citizenships;
const CitizenShipScreen({super.key, required this.citizenships});
final int profileId;
final String token;
const CitizenShipScreen(
{super.key, required this.profileId, required this.token});
@override
State<CitizenShipScreen> createState() => _CitizenShipScreenState();
}
List<Country> countries = [];
bool naturalBorn = false;
Country? selectedCountry;
final formKey = GlobalKey<FormBuilderState>();
class _CitizenShipScreenState extends State<CitizenShipScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(citizenshipScreenTitle),centerTitle: true,
backgroundColor: primary,
final bloc = BlocProvider.of<CitizenshipBloc>(context);
return ProgressHUD(
padding: const EdgeInsets.all(24),
indicatorWidget: const SpinKitFadingCircle(
color: Colors.white,
),
body: widget.citizenships.isEmpty?
Container(
width: screenWidth,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: const BorderRadius.all(Radius.circular(12))),
backgroundColor: Colors.black87,
child: BlocConsumer<CitizenshipBloc, CitizenshipState>(
listener: (context, state) {
if (state is CitizenshipAddedState) {
if (state.responseStatus['success']) {
successAlert(
context, "Add Successfull!", state.responseStatus['message'],
() {
Navigator.of(context).pop();
context.read<CitizenshipBloc>().add(const LoadCitizenship());
});
} else {
errorAlert(context, "Adding Failed",
"Something went wrong. Please try again.", () {
Navigator.of(context).pop();
context.read<CitizenshipBloc>().add(const LoadCitizenship());
});
}
}
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Philippines",style: Theme.of(context).textTheme.titleLarge,),
Text("Filipino",style: Theme.of(context).textTheme.titleSmall,)
],
if (state is CitizenshipEditedState) {
if (state.responseStatus['success']) {
successAlert(context, "Update Successfull!",
state.responseStatus['message'], () {
Navigator.of(context).pop();
context.read<CitizenshipBloc>().add(const LoadCitizenship());
});
} else {
errorAlert(context, "Update Failed",
state.responseStatus['message'], () {
Navigator.of(context).pop();
context.read<CitizenshipBloc>().add(const LoadCitizenship());
});
}
}
////DELETED STATE
if (state is CitizenshipDeleltedState) {
if (state.succcess) {
successAlert(context, "Deletion Successfull",
"Contact Info has been deleted successfully", () {
Navigator.of(context).pop();
context.read<CitizenshipBloc>().add(const LoadCitizenship());
});
} else {
errorAlert(
context, "Deletion Failed", "Error deleting Contact Info",
() {
Navigator.of(context).pop();
context.read<CitizenshipBloc>().add(const LoadCitizenship());
});
}
}
},
builder: (context, state) {
if (state is CitizenshipLoaded) {
return Scaffold(
appBar: AppBar(
title: const Text(citizenshipScreenTitle),
centerTitle: true,
backgroundColor: primary,
actions: [
AddLeading(onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text("Add Citizenship"),
content: FormBuilder(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FormBuilderDropdown<Country>(
initialValue: null,
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
items: state.countries
.map<DropdownMenuItem<Country>>(
(Country country) {
return DropdownMenuItem<Country>(
value: country,
child: FittedBox(
child: Text(country.name!)));
}).toList(),
name: 'country',
decoration: normalTextFieldStyle(
"Country*", "Country"),
onChanged: (Country? value) {
selectedCountry = value;
},
),
const SizedBox(
height: 12,
),
FormBuilderSwitch(
initialValue: naturalBorn,
activeColor: second,
onChanged: (value) {
setState(() {
naturalBorn = value!;
});
},
decoration: normalTextFieldStyle(
"Natural Born?", 'Natural Born?'),
name: 'graudated',
title: Text(naturalBorn ? "YES" : "NO"),
),
const SizedBox(
height: 12,
),
SizedBox(
width: double.infinity,
height: 60,
child: ElevatedButton(
style: mainBtnStyle(primary,
Colors.transparent, second),
onPressed: () {
if (formKey.currentState!
.saveAndValidate()) {
Navigator.pop(context);
bloc.add(AddCitizenship(
coiuntryId:
selectedCountry!.id!,
naturalBorn: naturalBorn,
profileId: widget.profileId,
token: widget.token));
}
},
child: const Text(submit)),
)
]),
),
);
});
})
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 24,
),
child: SizedBox(
width: screenWidth,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Philippines",
style: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(
fontWeight: FontWeight.w600,
color: primary),
),
const SizedBox(
height: 3,
),
Text(
"Filipino",
style: Theme.of(context).textTheme.bodyMedium,
),
]),
),
),
ListTile(
leading: const Icon(FontAwesome5.exclamation_circle),
title: Text(
"Your Filipino citizenship is added by default",
style: Theme.of(context).textTheme.bodySmall,
),
),
const Divider(
height: 2,
thickness: 1,
),
SizedBox(
child: state.citizenships.isEmpty
? Padding(
padding: const EdgeInsets.all(24),
child: Text(
"If you have citizenships other than Filipino, kindly add in this section",
textAlign: TextAlign.center,
style:
Theme.of(context).textTheme.bodySmall,
),
)
: SizedBox(
height: screenHeight * .70,
width: double.infinity,
child: ListView(
children: state.citizenships
.map((e) => Card(
child: Row(
children: [
Expanded(
child: ListTile(
dense: true,
title: Text(
e.country!.name!,
style: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(
fontWeight:
FontWeight
.w600,
color: primary),
),
subtitle: Text(
e.naturalBorn!
? "Natural Born"
: "Naturalized"),
),
),
AppPopupMenu<int>(
offset:
const Offset(-10, -10),
elevation: 3,
onSelected: (value) {
////delete contact-= = = = = = = = =>>
if (value == 2) {
confirmAlert(context,
() {
context
.read<
CitizenshipBloc>()
.add(DeleteCitizenship(
coiuntryId: e
.country!
.id!,
naturalBorn:
e
.naturalBorn!,
profileId: widget
.profileId,
token: widget
.token));
}, "Delete?",
"Are you sure you want to delete this contact info?");
}
if (value == 1) {
////edit contact-= = = = = = = = =>>
),
):Container()
,
showDialog(
context: context,
builder: (context) {
selectedCountry = state
.countries
.firstWhere((element) =>
element
.id ==
e.country!
.id);
return AlertDialog(
title: const Text(
"Add Citizenship"),
content:
FormBuilder(
key: formKey,
child: Column(
mainAxisSize:
MainAxisSize
.min,
children: [
DropdownButtonFormField<
Country>(
isExpanded:
true,
value:
selectedCountry,
validator:
FormBuilderValidators.required(errorText: "This field is required"),
items: state
.countries
.map<DropdownMenuItem<Country>>((Country country) {
return DropdownMenuItem<Country>(
value: country,
child: FittedBox(child: Text(country.name!)));
}).toList(),
decoration: normalTextFieldStyle(
"Country*",
"Country"),
onChanged:
(Country? value) {
selectedCountry =
value;
},
),
const SizedBox(
height:
12,
),
FormBuilderSwitch(
initialValue:
e.naturalBorn,
activeColor:
second,
onChanged:
(value) {
setState(() {
naturalBorn = value!;
});
},
decoration: normalTextFieldStyle(
"Natural Born?",
'Natural Born?'),
name:
'graudated',
title: Text(naturalBorn
? "YES"
: "NO"),
),
const SizedBox(
height:
12,
),
SizedBox(
width:
double.infinity,
height:
60,
child: ElevatedButton(
style: mainBtnStyle(primary, Colors.transparent, second),
onPressed: () {
Citizenship newCitizenship = Citizenship(country: selectedCountry, naturalBorn: naturalBorn);