implemented crud operation API for personal references screen

feature/passo/PASSO-#1-Sync-data-from-device-to-postgre-and-vice-versa
PGAN-MIS 2023-03-24 14:46:17 +08:00
parent 54aa42ec21
commit 12bc51335d
12 changed files with 2005 additions and 204 deletions

View File

@ -1,25 +1,209 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/location/address_category.dart';
import 'package:unit2/model/location/barangay.dart';
import 'package:unit2/model/location/city.dart';
import 'package:unit2/model/location/country.dart';
import 'package:unit2/model/location/region.dart';
import 'package:unit2/sevices/profile/references_services.dart';
import '../../../model/location/provinces.dart';
import '../../../model/profile/references.dart';
import '../../../utils/location_utilities.dart';
part 'references_event.dart';
part 'references_state.dart';
class ReferencesBloc extends Bloc<ReferencesEvent, ReferencesState> {
List<PersonalReference> references = [];
List<Country> globalCountries = [];
List<Region> globalRegions = [];
List<AddressCategory> globalCategories = [];
ReferencesBloc() : super(ReferencesInitial()) {
on<GetReferences>((event, emit) async{
on<GetReferences>((event, emit) async {
emit(ReferencesLoadingState());
try{
List<PersonalReference> refs = await ReferencesServices.instace.getRefences(event.profileId, event.token);
try {
if(references.isEmpty){
List<PersonalReference> refs = await ReferencesServices.instace
.getRefences(event.profileId, event.token);
references = refs;
emit(ReferencesLoadedState(references: references));
}catch(e){
}else{
emit(ReferencesLoadedState(references: references));
}
} catch (e) {
ReferencesErrorState(message: e.toString());
}
////SHOW FORM FOR ADDING REFERENCES
});
on<ShowAddReferenceForm>((event, emit) async {
emit(ReferencesLoadingState());
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;
}
if (globalCategories.isEmpty) {
List<AddressCategory> categories =
await LocationUtils.instance.getAddressCategory();
globalCategories = categories;
}
emit(AddReferenceState(
countries: globalCountries,
regions: globalRegions,
categories: globalCategories));
} catch (e) {
emit(ReferencesErrorState(message: e.toString()));
}
////SHOW EDIT FORM
});
on<ShowEditReferenceForm>((event, emit) async {
Region? selectedRegion;
Province? selectedProvince;
CityMunicipality? selectedCity;
AddressCategory? selectedCategory;
Country selectedCountry;
Barangay? selectedBarangay;
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;
}
if (globalCategories.isEmpty) {
List<AddressCategory> categories =
await LocationUtils.instance.getAddressCategory();
globalCategories = categories;
}
//// 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);
////if address is not overseas set initial values for address
if (!overseas) {
selectedRegion = globalRegions.firstWhere((Region element) =>
event.personalReference.address!.cityMunicipality!.province!
.region!.code ==
element.code);
List<Province> provinces = await LocationUtils.instance
.getProvinces(regionCode: selectedRegion.code.toString());
selectedProvince = provinces.firstWhere((Province province) =>
event.personalReference.address!.cityMunicipality!.province!
.code ==
province.code);
List<CityMunicipality> cities = await LocationUtils.instance
.getCities(code: selectedProvince.code!);
selectedCity = cities.firstWhere((CityMunicipality city) =>
event.personalReference.address!.cityMunicipality!.code ==
city.code);
List<Barangay> barangays = await LocationUtils.instance.getBarangay(code: selectedCity.code.toString());
selectedBarangay = barangays.firstWhere((Barangay barangay)=>event.personalReference.address!.barangay!.code == barangay.code);
emit(EditReferenceState(
selectedRegion: selectedRegion,
ref: event.personalReference,
countries: globalCountries,
regions: globalRegions,
barangays: barangays,
categories: globalCategories,
isOverseas: overseas,
provinces: provinces,
selectedProvince: selectedProvince,
cities: cities,
selectedCity: selectedCity,
selectedCategory: selectedCategory,
selectedBarangay: selectedBarangay
));
} else {
//// if address is overseas set initial value for country
selectedCountry = globalCountries.firstWhere((Country element) => event.personalReference.address!.country!.id == element.id);
emit(EditReferenceState(
selectedCountry: selectedCountry,
selectedCategory: selectedCategory,
selectedRegion: null,
ref: event.personalReference,
countries: globalCountries,
regions: globalRegions,
categories: globalCategories,
isOverseas: overseas));
}
} catch (e) {
emit(ReferencesErrorState(message: e.toString()));
}
});
//// CALL THE ERROR STATE EVEN T
on<CallErrorState>((event, emit) async {
emit(const ReferencesErrorState(
message: "Something went wrong. Please try again"));
//// ADD REFERENCES EVENT
});on<EditReference>((event,emit)async{
emit(ReferencesLoadingState());
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(personalRefs: references, response: status));
} else {
emit(
ReferenceEditedState(personalRefs: references, response: status));
}
});
//// add reference event
on<AddReference>((event, emit) async {
try {
emit(ReferencesLoadingState());
Map<dynamic, dynamic> status = await ReferencesServices.instace
.addReference(
ref: event.reference,
token: event.token,
profileId: event.profileId);
if (status['success']) {
PersonalReference ref = PersonalReference.fromJson(status['data']);
references.add(ref);
emit(
ReferencesAddedState(personalRefs: references, response: status));
} else {
emit(
ReferencesAddedState(personalRefs: references, response: status));
}
} catch (e) {
emit(ReferencesErrorState(message: e.toString()));
}
});
////LOAD REFERENCE
on<LoadReferences>((event, emit) {
emit(ReferencesLoadingState());
references = event.references;
emit(ReferencesLoadedState(references: references));
});
////DELETE REFERENCE
on<DeleteReference>((event, emit) async {
try {
final bool success = await ReferencesServices.instace.delete(
profileId: event.profileId, token: event.token, id: event.refId);
if (success) {
event.references.removeWhere(
(PersonalReference element) => element.id == event.refId);
references = event.references;
emit(DeleteReferenceState(references: references, success: success));
} else {
emit(DeleteReferenceState(references: references, success: success));
}
} catch (e) {
emit(ReferencesErrorState(message: e.toString()));
}
});
}
}

View File

@ -14,3 +14,56 @@ class GetReferences extends ReferencesEvent{
@override
List<Object> get props => [profileId,token];
}
class ShowAddReferenceForm extends ReferencesEvent{
}
class ShowEditReferenceForm extends ReferencesEvent{
final PersonalReference personalReference;
const ShowEditReferenceForm({required this.personalReference});
@override
List<Object> get props => [personalReference];
}
class CallErrorState extends ReferencesEvent{
}
class AddReference extends ReferencesEvent{
final PersonalReference reference;
final String token;
final int profileId;
const AddReference({required this.profileId, required this.reference,required this.token});
@override
List<Object> get props => [profileId,token,reference];
}
class EditReference extends ReferencesEvent{
final PersonalReference reference;
final String token;
final int profileId;
const EditReference({required this.profileId, required this.reference,required this.token});
@override
List<Object> get props => [profileId,token,reference];
}
class DeleteReference extends ReferencesEvent{
final List<PersonalReference>references;
final int profileId;
final String token;
final int refId;
const DeleteReference({required this.profileId, required this.refId, required this.references, required this.token});
@override
List<Object> get props => [profileId,token,refId,references];
}
class LoadReferences extends ReferencesEvent{
final List<PersonalReference> references;
const LoadReferences({required this.references});
@override
List<Object> get props => [references];
}

View File

@ -2,28 +2,94 @@ part of 'references_bloc.dart';
abstract class ReferencesState extends Equatable {
const ReferencesState();
@override
List<Object> get props => [];
}
class ReferencesInitial extends ReferencesState {}
class ReferencesLoadedState extends ReferencesState{
class ReferencesLoadedState extends ReferencesState {
final List<PersonalReference> references;
const ReferencesLoadedState({required this.references});
@override
List<Object> get props => [references];
}
class ReferencesErrorState extends ReferencesState{
class ReferencesErrorState extends ReferencesState {
final String message;
const ReferencesErrorState({required this.message});
@override
List<Object> get props => [message];
}
class ReferencesLoadingState extends ReferencesState{
class ReferencesLoadingState extends ReferencesState {}
class ReferencesAddedState extends ReferencesState {
final List<PersonalReference> personalRefs;
final Map<dynamic, dynamic> response;
const ReferencesAddedState(
{required this.personalRefs, required this.response});
@override
List<Object> get props => [personalRefs, response];
}
class ReferenceEditedState extends ReferencesState {
final List<PersonalReference> personalRefs;
final Map<dynamic, dynamic> response;
const ReferenceEditedState(
{required this.personalRefs, required this.response});
@override
List<Object> get props => [personalRefs, response];
}
class EditReferenceState extends ReferencesState {
final List<Region> regions;
final List<Country> countries;
final List<AddressCategory> categories;
final List<Province>? provinces;
final List<CityMunicipality>? cities;
final List<Barangay>? barangays;
final PersonalReference ref;
final bool isOverseas;
final Region? selectedRegion;
final Province? selectedProvince;
final CityMunicipality? selectedCity;
final AddressCategory selectedCategory;
final Barangay? selectedBarangay;
final Country? selectedCountry;
const EditReferenceState(
{ this.barangays,
this.selectedBarangay,
required this.selectedCategory,
this.cities,
this.selectedCity,
this.provinces,
this.selectedProvince,
this.selectedRegion,
this.selectedCountry,
required this.isOverseas,
required this.ref,
required this.categories,
required this.countries,
required this.regions});
@override
List<Object> get props => [regions, countries, categories, isOverseas];
}
class AddReferenceState extends ReferencesState {
final List<Region> regions;
final List<Country> countries;
final List<AddressCategory> categories;
const AddReferenceState(
{required this.categories,
required this.countries,
required this.regions});
}
class DeleteReferenceState extends ReferencesState {
final List<PersonalReference> references;
final bool success;
const DeleteReferenceState({required this.references, required this.success});
}

View File

@ -32,7 +32,6 @@ class AddEligibilityScreen extends StatefulWidget {
class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
final formKey = GlobalKey<FormBuilderState>();
final provinceKey = GlobalKey<FormBuilderState>();
bool? overseas;
DateFormat dteFormat2 = DateFormat.yMMMMd('en_US');
Region? selectedRegion;
@ -52,12 +51,12 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
String? license;
@override
Widget build(BuildContext context) {
//USERBLOC
////USERBLOC
return BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
//LOGGED IN USER STATE
////LOGGED IN USER STATE
if (state is UserLoggedIn) {
//PROFIILE BLOC
////PROFIILE BLOC
token = state.userData!.user!.login!.token;
profileId = state.userData!.user!.login!.user!.profileId.toString();
return BlocBuilder<ProfileBloc, ProfileState>(
@ -69,7 +68,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
return false;
},
builder: (context, state) {
//EDIT ELIGIBILITY STATE
////ADD ELIGIBILITY STATE
if (state is AddEligibilityState) {
return ProgressHUD(
child: Center(
@ -82,7 +81,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//ELIGIBILITIES DROPDOWN
////ELIGIBILITIES DROPDOWN
FormBuilderDropdown<Eligibility>(
onChanged: (Eligibility? eligibility) {
selectedEligibility = eligibility;
@ -109,7 +108,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
width: screenWidth,
child: Row(
children: [
//LICENSE NUMBER
////LICENSE NUMBER
Flexible(
flex: 1,
child: FormBuilderTextField(
@ -125,7 +124,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
const SizedBox(
width: 12,
),
//RATING
////RATING
Flexible(
flex: 1,
child: FormBuilderTextField(
@ -149,7 +148,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
width: screenWidth,
child: Row(
children: [
//EXAM DATE
////EXAM DATE
Flexible(
flex: 1,
child: DateTimePicker(
@ -175,7 +174,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
const SizedBox(
width: 12,
),
//VALIDITY DATE
////VALIDITY DATE
Flexible(
flex: 1,
child: DateTimePicker(
@ -211,7 +210,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
const SizedBox(
height: 12,
),
//OVERSEAS ADDRESS SWITCH
////OVERSEAS ADDRESS SWITCH
Column(
children: [
FormBuilderSwitch(
@ -231,15 +230,12 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
const SizedBox(
height: 20,
),
//COUNTRY DROPDOWN
////COUNTRY DROPDOWN
SizedBox(
child: overseas == true
? FormBuilderDropdown<Country>(
initialValue: null,
validator: (value) =>
value == null
? 'required'
: null,
validator: FormBuilderValidators.required(errorText: "This field is required"),
items: state.countries.map<
DropdownMenuItem<
Country>>(
@ -264,16 +260,14 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
)
: Column(
children: [
//REGION DROPDOWN
////REGION DROPDOWN
FormBuilderDropdown<
Region?>(
autovalidateMode:
AutovalidateMode
.onUserInteraction,
validator: (value) =>
value == null
? 'required'
: null,
validator: FormBuilderValidators.required(errorText: "This field is required"),
//// region onchange
onChanged: (Region?
region) async {
setState(() {
@ -304,7 +298,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
const SizedBox(
height: 20,
),
//PROVINCE DROPDOWN
////PROVINCE DROPDOWN
SizedBox(
height: 70,
child: ModalProgressHUD(
@ -358,7 +352,7 @@ class _AddEligibilityScreenState extends State<AddEligibilityScreen> {
),
),
// CityMunicipalities dropdown
//// CityMunicipalities dropdown
SizedBox(
height: 70,
child: ModalProgressHUD(

View File

@ -86,7 +86,7 @@ class EligibiltyScreen extends StatelessWidget {
final progress = ProgressHUD.of(context);
progress!.dismiss();
}
//DELETED STATE
////DELETED STATE
if (state is DeletedState) {
if (state.success) {
successAlert(context, "Deletion Successfull",
@ -105,7 +105,7 @@ class EligibiltyScreen extends StatelessWidget {
});
}
}
//ADDED STATE
////ADDED STATE
if (state is EligibilityAddedState) {
if (state.response['success']) {
successAlert(context, "Adding Successfull!",
@ -124,7 +124,7 @@ class EligibiltyScreen extends StatelessWidget {
});
}
}
//UPDATED STATE
////UPDATED STATE
if (state is EligibilityEditedState) {
if (state.response['success']) {
successAlert(context, "Update Successfull!",

View File

@ -0,0 +1,548 @@
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/profile_bloc.dart';
import 'package:unit2/bloc/profile/references/references_bloc.dart';
import 'package:unit2/bloc/user/user_bloc.dart';
import 'package:unit2/model/location/address_category.dart';
import 'package:unit2/model/location/barangay.dart';
import 'package:unit2/model/profile/references.dart';
import 'package:unit2/theme-data.dart/btn-style.dart';
import 'package:unit2/theme-data.dart/form-style.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/colors.dart';
import '../../../../utils/location_utilities.dart';
import '../../../../utils/text_container.dart';
class AddReferenceScreen extends StatefulWidget {
const AddReferenceScreen({super.key});
@override
State<AddReferenceScreen> createState() => _AddReferenceScreenState();
}
class _AddReferenceScreenState extends State<AddReferenceScreen> {
final formKey = GlobalKey<FormBuilderState>();
String? token;
String? profileId;
bool provinceCall = false;
bool cityCall = false;
bool barangayCall = false;
bool overseas = false;
List<Province>? provinces;
List<CityMunicipality>? citymuns;
List<Barangay>? barangays;
List<String> category = ['Permanent', "Residential", "Birthplace"];
////seletected
Region? selectedRegion;
Province? selectedProvince;
CityMunicipality? selectedMunicipality;
Barangay? selectedBarangay;
Country? selectedCountry;
AddressCategory? selectedCategory;
@override
Widget build(BuildContext context) {
return BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
if (state is UserLoggedIn) {
token = state.userData!.user!.login!.token;
profileId = state.userData!.user!.login!.user!.profileId.toString();
return BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
if (state is ProfileLoaded) {
return BlocBuilder<ReferencesBloc, ReferencesState>(
builder: (context, state) {
if (state is AddReferenceState) {
return ProgressHUD(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 25, horizontal: 18),
child: FormBuilder(
key: formKey,
child: Column(
children: [
const SizedBox(height: 25),
Row(
children: [
////LAST NAME
Flexible(
flex: 1,
child: FormBuilderTextField(
decoration: normalTextFieldStyle(
"Last name *", "Last name *"),
name: "lastname",
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
),
),
const SizedBox(
width: 5,
),
////FIRST NAME
Flexible(
flex: 1,
child: FormBuilderTextField(
decoration: normalTextFieldStyle(
"First name *", "First name *"),
name: "firstname",
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
),
),
],
),
const SizedBox(
height: 8,
),
Row(
children: [
Flexible(
flex: 1,
child: FormBuilderTextField(
decoration: normalTextFieldStyle(
"Middle name *", "Midlle name *"),
name: "middlename",
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
),
),
const SizedBox(
width: 5,
),
////CATEGORY
Flexible(
flex: 1,
child: FormBuilderDropdown<
AddressCategory>(
name: 'category',
validator:
FormBuilderValidators.required(
errorText: ""),
decoration: normalTextFieldStyle(
"Category", "Category"),
items: state.categories.map<
DropdownMenuItem<
AddressCategory>>(
(AddressCategory cat) {
return DropdownMenuItem<
AddressCategory>(
value: cat,
child: Text(cat.name!),
);
}).toList(),
onChanged: (value) {
setState(() {
selectedCategory = value;
});
},
),
),
],
),
const SizedBox(
height: 8,
),
////OVERSEAS ADDRESS
FormBuilderSwitch(
initialValue: overseas,
activeColor: second,
onChanged: (value) {
setState(() {
overseas = value!;
});
},
decoration: normalTextFieldStyle("", ''),
name: 'overseas',
title: const Text("Overseas Address?"),
),
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 {
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) {
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) {
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>(
validator: FormBuilderValidators
.required(
errorText:
"This field is required"),
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;
},
),
),
),
FormBuilderTextField(
name: "mobile",
decoration: normalTextFieldStyle(
"Tel./Mobile *", "Tel./Mobile"),
validator: FormBuilderValidators.required(
errorText: "This field is required"),
),
const Expanded(
child: SizedBox(),
),
SizedBox(
width: double.infinity,
height: 60,
child: ElevatedButton(
style: mainBtnStyle(
primary, Colors.transparent, second),
child: const Text(submit),
onPressed: () {
PersonalReference? personalReference;
if (formKey.currentState!
.saveAndValidate()) {
String lastname = formKey
.currentState!.value['lastname'];
String firstname = formKey
.currentState!.value['firstname'];
String middlename = formKey
.currentState!
.value['middlename'];
String mobile = formKey
.currentState!.value['mobile'];
Region? region = selectedRegion;
Province? province = Province(
code: selectedProvince?.code,
description:
selectedProvince?.description,
region: region,
psgcCode:
selectedProvince?.psgcCode,
shortname:
selectedProvince?.shortname);
CityMunicipality? city =
CityMunicipality(
code: selectedMunicipality
?.code,
description:
selectedMunicipality
?.description,
province: province,
psgcCode: selectedMunicipality
?.psgcCode,
zipcode: selectedMunicipality
?.zipcode);
Address address = Address(
id: null,
addressCategory: selectedCategory,
country: selectedCountry,
barangay: selectedBarangay,
addressClass: null,
cityMunicipality: city);
if (selectedCountry != null) {
personalReference =
PersonalReference(
id: null,
address: Address(
id: null,
addressCategory:
selectedCategory,
country: selectedCountry,
barangay: null,
cityMunicipality: null,
addressClass: null),
lastName: lastname,
contactNo: mobile,
firstName: firstname,
middleName: middlename);
} else {
personalReference =
PersonalReference(
id: null,
address: address,
lastName: lastname,
contactNo: mobile,
firstName: firstname,
middleName: middlename);
}
context.read<ReferencesBloc>().add(
AddReference(
profileId:
int.parse(profileId!),
reference: personalReference,
token: token!));
}
},
),
),
const SizedBox(
height: 20,
),
],
)),
),
);
}
return Container();
},
);
}
return Container();
},
);
}
return Container();
},
);
}
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<ReferencesBloc>().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<ReferencesBloc>().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<ReferencesBloc>().add(CallErrorState());
}
}
}

View File

@ -0,0 +1,637 @@
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 '../../../../bloc/profile/profile_bloc.dart';
import '../../../../bloc/profile/references/references_bloc.dart';
import '../../../../bloc/user/user_bloc.dart';
import '../../../../model/location/address_category.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 '../../../../model/profile/references.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';
class EditReferenceScreen extends StatefulWidget {
const EditReferenceScreen({super.key});
@override
State<EditReferenceScreen> createState() => _EditReferenceScreenState();
}
class _EditReferenceScreenState extends State<EditReferenceScreen> {
final formKey = GlobalKey<FormBuilderState>();
String? token;
String? profileId;
bool provinceCall = false;
bool cityCall = false;
bool barangayCall = false;
bool overseas = false;
List<Province>? provinces;
List<CityMunicipality>? citymuns;
List<Barangay>? barangays;
////seletected
Region? selectedRegion;
Province? selectedProvince;
CityMunicipality? selectedMunicipality;
Barangay? selectedBarangay;
Country? selectedCountry;
AddressCategory? selectedCategory;
@override
Widget build(BuildContext context) {
return BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
if (state is UserLoggedIn) {
token = state.userData!.user!.login!.token;
profileId = state.userData!.user!.login!.user!.profileId.toString();
return BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
if (state is ProfileLoaded) {
return BlocBuilder<ReferencesBloc, ReferencesState>(
buildWhen: (previous, current) => false,
builder: (context, state) {
if (state is EditReferenceState) {
overseas = state.isOverseas;
selectedCategory = state.selectedCategory;
////if not overseas address
//// set initial values
if (!overseas) {
selectedRegion = state.selectedRegion;
provinces = state.provinces;
selectedProvince = state.selectedProvince;
citymuns = state.cities;
selectedMunicipality = state.selectedCity;
barangays = state.barangays;
selectedBarangay = state.selectedBarangay;
} else {
selectedCountry = state.selectedCountry;
}
return ProgressHUD(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 25, horizontal: 18),
child: FormBuilder(
key: formKey,
child: Column(
children: [
const SizedBox(height: 25),
Row(
children: [
////LAST NAME
Flexible(
flex: 1,
child: FormBuilderTextField(
initialValue: state.ref.lastName,
decoration: normalTextFieldStyle(
"Last name *", "Last name *"),
name: "lastname",
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
),
),
const SizedBox(
width: 5,
),
////FIRST NAME
Flexible(
flex: 1,
child: FormBuilderTextField(
initialValue: state.ref.firstName,
decoration: normalTextFieldStyle(
"First name *", "First name *"),
name: "firstname",
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
),
),
],
),
const SizedBox(
height: 8,
),
Row(
children: [
Flexible(
flex: 1,
child: FormBuilderTextField(
initialValue: state.ref.middleName,
decoration: normalTextFieldStyle(
"Middle name *", "Midlle name *"),
name: "middlename",
validator:
FormBuilderValidators.required(
errorText:
"This field is required"),
),
),
const SizedBox(
width: 5,
),
////CATEGORY
Flexible(
flex: 1,
child: FormBuilderDropdown<
AddressCategory>(
name: 'category',
validator:
FormBuilderValidators.required(
errorText: ""),
decoration: normalTextFieldStyle(
"Category", "Category"),
items: state.categories.map<
DropdownMenuItem<
AddressCategory>>(
(AddressCategory cat) {
return DropdownMenuItem<
AddressCategory>(
value: cat,
child: Text(cat.name!),
);
}).toList(),
initialValue: selectedCategory,
onChanged: (value) {
selectedCategory = value;
},
),
),
],
),
const SizedBox(
height: 8,
),
////OVERSEAS ADDRESS
StatefulBuilder(builder: (context, setState) {
return Column(
children: [
FormBuilderSwitch(
initialValue: overseas,
activeColor: second,
onChanged: (value) {
setState(() {
overseas = value!;
});
},
decoration:
normalTextFieldStyle("", ''),
name: 'overseas',
title:
const Text("Overseas Address?"),
),
SizedBox(
height: overseas == true ? 8 : 0,
),
SizedBox(
child: overseas == false
? Column(
children: [
const SizedBox(
height: 12,
),
////REGION DROPDOWN
DropdownButtonFormField<
Region?>(
isExpanded: true,
autovalidateMode:
AutovalidateMode
.onUserInteraction,
validator:
FormBuilderValidators
.required(
errorText:
"This field is required"),
onChanged: (Region?
region) async {
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 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;
});
},
value: selectedRegion,
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,
onChanged: (Province?
province) async {
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;
});
},
value:
selectedProvince,
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 {
setState(() {
barangayCall =
true;
});
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>(
validator:
FormBuilderValidators
.required(
errorText:
"This field is required"),
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:
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"),
//// country dropdown
onChanged:
(Country? value) {
selectedCountry = value;
},
),
),
),
],
);
}),
FormBuilderTextField(
initialValue: state.ref.contactNo,
name: "mobile",
decoration: normalTextFieldStyle(
"Tel./Mobile *", "Tel./Mobile"),
validator: FormBuilderValidators.required(
errorText: "This field is required"),
),
const Expanded(
child: SizedBox(),
),
SizedBox(
width: double.infinity,
height: 60,
child: ElevatedButton(
style: mainBtnStyle(
primary, Colors.transparent, second),
child: const Text(submit),
onPressed: () {
PersonalReference? personalReference;
if (formKey.currentState!
.saveAndValidate()) {
String lastname = formKey
.currentState!.value['lastname'];
String firstname = formKey
.currentState!.value['firstname'];
String middlename = formKey
.currentState!
.value['middlename'];
String mobile = formKey
.currentState!.value['mobile'];
Region? region = selectedRegion;
Province? province = Province(
code: selectedProvince?.code,
description:
selectedProvince?.description,
region: region,
psgcCode:
selectedProvince?.psgcCode,
shortname:
selectedProvince?.shortname);
CityMunicipality? city =
CityMunicipality(
code: selectedMunicipality
?.code,
description:
selectedMunicipality
?.description,
province: province,
psgcCode: selectedMunicipality
?.psgcCode,
zipcode: selectedMunicipality
?.zipcode);
////IF IS OVERSEAS
if (overseas) {
personalReference =
PersonalReference(
id: state.ref.id,
address: Address(
id: state
.ref.address!.id,
addressCategory:
selectedCategory,
country:
selectedCountry,
barangay: null,
cityMunicipality: null,
addressClass: null),
lastName: lastname,
contactNo: mobile,
firstName: firstname,
middleName: middlename);
} else {
//// IF NOT OVERSEAS
personalReference =
PersonalReference(
id: state.ref.id,
address: Address(
id: state
.ref.address!.id,
addressCategory:
selectedCategory,
country: Country(
id: 175,
code: null,
name: null),
barangay:
selectedBarangay,
cityMunicipality: city,
addressClass: state
.ref
.address
?.addressClass),
lastName: lastname,
contactNo: mobile,
firstName: firstname,
middleName: middlename);
}
context.read<ReferencesBloc>().add(
EditReference(
profileId:
int.parse(profileId!),
reference: personalReference,
token: token!));
}
},
),
),
const SizedBox(
height: 20,
),
],
)),
),
);
}
return Container();
},
);
}
return Container();
},
);
}
return Container();
},
);
}
}

View File

@ -1,40 +1,60 @@
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_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttericon/font_awesome_icons.dart';
import 'package:unit2/bloc/profile/profile_bloc.dart';
import 'package:unit2/bloc/user/user_bloc.dart';
import 'package:unit2/model/profile/references.dart';
import 'package:unit2/screens/profile/components/reference/add_modal.dart';
import 'package:unit2/screens/profile/components/reference/edit_modal.dart';
import 'package:unit2/theme-data.dart/box_shadow.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/Leadings/add_leading.dart';
import 'package:unit2/widgets/empty_data.dart';
import 'package:unit2/widgets/Leadings/close_leading.dart';
import 'package:unit2/widgets/error_state.dart';
import '../../../bloc/profile/references/references_bloc.dart';
import '../../../utils/alerts.dart';
class ReferencesScreen extends StatelessWidget {
const ReferencesScreen({super.key});
@override
Widget build(BuildContext context) {
int? profileId;
String? token;
return Scaffold(
appBar: AppBar(
title: const Text(referencesScreenTitle),
title: context.watch<ReferencesBloc>().state is AddReferenceState?const Text("Add Personal Reference"):context.watch<ReferencesBloc>().state is EditReferenceState?const Text("Edit Personal Reference"):const Text("Personal References"),
centerTitle: true,
backgroundColor: primary,
actions: [AddLeading(onPressed: () {})],
////if state is adding or editing state show close button
actions: (context.watch<ReferencesBloc>().state is AddReferenceState || context.watch<ReferencesBloc>().state is EditReferenceState)?
[
//// close button
CloseLeading(onPressed: (){
context.read<ReferencesBloc>().add(GetReferences(profileId: profileId!, token: token!));
}),
]:
//// if state is loaded state show add button
context.watch<ReferencesBloc>().state is ReferencesLoadedState?[
AddLeading(onPressed: (){
context.read<ReferencesBloc>().add(ShowAddReferenceForm());
}),
]:[]
),
body: ProgressHUD(
padding: const EdgeInsets.all(24),
backgroundColor: Colors.black87,
indicatorWidget: const SpinKitFadingCircle(
color: Colors.white),
padding: const EdgeInsets.all(24),
backgroundColor: Colors.black87,
indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
child: BlocBuilder<UserBloc, UserState>(
builder: (context, state) {
//userbloc
if (state is UserLoggedIn) {
token = state.userData!.user!.login!.token;
profileId = state.userData!.user!.login!.user!.profileId;
return BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
//profilebloc
@ -42,13 +62,82 @@ class ReferencesScreen extends StatelessWidget {
return BlocConsumer<ReferencesBloc, ReferencesState>(
//listener
listener: (context, state) {
if(state is ReferencesLoadingState){
final progress = ProgressHUD.of(context);
progress!.showWithText("Please wait...");
if (state is ReferencesLoadingState) {
final progress = ProgressHUD.of(context);
progress!.showWithText("Please wait...");
}
if(state is ReferencesLoadedState || state is ReferencesErrorState){
final progress = ProgressHUD.of(context);
progress!.dismiss();
if (state is ReferencesLoadedState ||
state is AddReferenceState ||
state is ReferencesErrorState ||
state is DeleteReferenceState ||
state is ReferencesAddedState ||
state is EditReferenceState) {
final progress = ProgressHUD.of(context);
progress!.dismiss();
}
////ADDED STATE
if (state is ReferencesAddedState) {
if (state.response['success']) {
successAlert(context, "Adding Successfull!",
state.response['message'], () {
Navigator.of(context).pop();
context.read<ReferencesBloc>().add(
LoadReferences(
references: state.personalRefs));
});
} else {
errorAlert(context, "Adding Failed",
"Something went wrong. Please try again.",
() {
Navigator.of(context).pop();
context.read<ReferencesBloc>().add(
LoadReferences(
references: state.personalRefs));
});
}
}
////EDIT REFERENCE STATE
if (state is ReferenceEditedState) {
if (state.response['success']) {
successAlert(context, "Update Successfull!",
state.response['message'], () {
Navigator.of(context).pop();
context.read<ReferencesBloc>().add(
LoadReferences(
references: state.personalRefs));
});
} else {
errorAlert(context, "Update Failed",
"Something went wrong. Please try again.",
() {
Navigator.of(context).pop();
context.read<ReferencesBloc>().add(
LoadReferences(
references: state.personalRefs));
});
}
}
////DELETED STATE
if (state is DeleteReferenceState) {
if (state.success) {
successAlert(context, "Deletion Successfull",
"Eligibility has been deleted successfully",
() {
Navigator.of(context).pop();
context.read<ReferencesBloc>().add(
LoadReferences(
references: state.references));
});
} else {
errorAlert(context, "Deletion Failed",
"Error deleting eligibility", () {
Navigator.of(context).pop();
context.read<ReferencesBloc>().add(
LoadReferences(
references: state.references));
});
}
}
},
//builder
@ -56,72 +145,147 @@ class ReferencesScreen extends StatelessWidget {
//references bloc
if (state is ReferencesLoadedState) {
if (state.references.isNotEmpty) {
return ListView.builder(
padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
itemCount: state.references.length,
itemBuilder: (BuildContext context, int index) {
String fullname =
"${state.references[index].firstName} ${state.references[index].middleName} ${state.references[index].lastName}";
String addres =
"${state.references[index].address!.cityMunicipality!.description}, ${state.references[index].address!.cityMunicipality!.province!.description}, ${state.references[0].address!.cityMunicipality!.province!.region!.description}";
String mobile = state.references[index].contactNo.toString();
return Column(
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 8),
decoration: box1(),
child: Row(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(fullname,
style: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(
fontWeight: FontWeight.w500)),
const Divider(),
const SizedBox(
height: 5,
),
Text(addres,
style: Theme.of(context)
.textTheme
.titleSmall!
.copyWith(
fontWeight: FontWeight.w500)),
const SizedBox(
height: 8,
),
Text("${mobileOrPhone.toUpperCase()} : $mobile",
style: Theme.of(context)
.textTheme
.labelMedium!),
],
),
),
IconButton(
onPressed: () {},
icon: const Icon(
Icons.more_vert,
color: Colors.grey,
))
],
),
),
const SizedBox(
height: 5,
),
],
);
});
return ListView.builder(
padding: const EdgeInsets.symmetric(
vertical: 8, horizontal: 10),
itemCount: state.references.length,
itemBuilder:
(BuildContext context, int index) {
String fullname =
"${state.references[index].firstName} ${state.references[index].middleName} ${state.references[index].lastName}";
String addres = state.references[index]
.address!.country?.id !=
175
? "COUNTRY: ${state.references[index].address!.country!.name!.toUpperCase()}"
: "${state.references[index].address?.cityMunicipality?.description}, ${state.references[index].address?.cityMunicipality?.province?.description}, ${state.references[index].address?.cityMunicipality?.province?.region?.description}";
String mobile = state
.references[index].contactNo
.toString();
return Column(
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 8),
decoration: box1(),
child: Row(
children: [
Expanded(
child: Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(fullname.toUpperCase(),
style: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(
fontWeight:
FontWeight
.w500)),
const Divider(),
const SizedBox(
height: 5,
),
Text(addres,
style: Theme.of(context)
.textTheme
.titleSmall!
.copyWith(
fontWeight:
FontWeight
.w500)),
const SizedBox(
height: 8,
),
Text(
"${mobileOrPhone.toUpperCase()} : $mobile",
style: Theme.of(context)
.textTheme
.labelMedium!),
],
),
),
AppPopupMenu<int>(
offset: const Offset(-10, -10),
elevation: 3,
onSelected: (value) {
final progress =
ProgressHUD.of(context);
progress!.showWithText(
"Loading...");
////delete eligibilty-= = = = = = = = =>>
if (value == 2) {
confirmAlert(context, () {
context
.read<
ReferencesBloc>()
.add(DeleteReference(
profileId:
profileId!,
refId: state
.references[
index]
.id!,
references: state
.references,
token: token!));
}, "Delete?",
"Confirm Delete?");
}
if (value == 1) {
////edit reference-= = = = = = = = =>>
context
.read<ReferencesBloc>()
.add(ShowEditReferenceForm(
personalReference:
state.references[
index]));
}
},
menuItems: [
popMenuItem(
text: "Edit",
value: 1,
icon: Icons.edit),
popMenuItem(
text: "Delete",
value: 2,
icon: Icons.delete),
popMenuItem(
text: "Attachment",
value: 3,
icon: FontAwesome.attach)
],
icon: const Icon(
Icons.more_vert,
color: Colors.grey,
),
tooltip: "Options",
)
],
),
),
const SizedBox(
height: 5,
),
],
);
});
}
}
if (state is AddReferenceState) {
return const AddReferenceScreen();
}
if (state is EditReferenceState) {
return const EditReferenceScreen();
}
if (state is ReferencesErrorState) {
return SomethingWentWrong(
message: state.message, onpressed: () {});
}
return Container();
},
);
@ -135,5 +299,23 @@ class ReferencesScreen 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!,
),
],
),
);
}
}

View File

@ -16,7 +16,7 @@ class ReferencesServices{
List<PersonalReference> references = [];
String authToken = "Token $token";
String path = "${Url.instance.getRefences()}$profileId/";
String path = "${Url.instance.reference()}$profileId/";
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authToken
@ -37,4 +37,100 @@ List<PersonalReference> references = [];
}
return references;
}
}
Future<Map<dynamic,dynamic>>addReference({required PersonalReference ref, required String token, required int profileId})async{
String authToken = "Token $token";
String path = "${Url.instance.reference()}$profileId/";
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authToken
};
Map<dynamic,dynamic> responseStatus ={};
bool overseas = ref.address!.country !=null?true:false;
Map body = {
"first_name": ref.firstName,
"middle_name": ref.middleName,
"last_name": ref.lastName,
"contact_no":ref.contactNo,
"_addressCatId": ref.address!.addressCategory!.id,
"_areaClass": "Village",
"_citymunCode": overseas?null: ref.address?.cityMunicipality?.code,
"_brgyCode": overseas?null:ref.address?.barangay?.code,
"_countryId": overseas?ref.address!.country!.id:175
};
try{
http.Response response = await Request.instance.postRequest(path: path,body: body,param: {},headers: headers);
if(response.statusCode == 201){
Map data = jsonDecode(response.body);
responseStatus = data;
}else{
responseStatus.addAll({'success':false});
}
return responseStatus;
}catch(e){
throw e.toString();
}
}
Future<Map<dynamic, dynamic>> update({required PersonalReference ref,required String token, required int profileId})async{
String authToken = "Token $token";
String path = "${Url.instance.reference()}$profileId/";
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authToken
};
Map<dynamic,dynamic> responseStatus ={};
bool overseas = ref.address!.country!.id != 175;
Map body = {
"id":ref.id,
"related_person_id": profileId,
"first_name": ref.firstName,
"middle_name": ref.middleName,
"last_name": ref.lastName,
"contact_no":ref.contactNo,
"_addressCatId": ref.address!.addressCategory!.id,
"_areaClass": "Village",
"_citymunCode": overseas?null: ref.address?.cityMunicipality?.code,
"_brgyCode": overseas?null:ref.address?.barangay?.code,
"_countryId": overseas?ref.address!.country!.id:175
};
// try{
http.Response response = await Request.instance.putRequest(path: path,body: body,param: {},headers: headers);
if(response.statusCode == 200){
Map data = jsonDecode(response.body);
responseStatus = data;
}else{
responseStatus.addAll({'success':false});
}
return responseStatus;
// }catch(e){
// throw e.toString();
// }
}
Future<bool>delete({required int profileId, required String token, required int id })async{
bool? success;
String authtoken = "Token $token";
String path = "${Url.instance.reference()}$profileId/";
Map<String, dynamic> params = {"force_mode": "true"};
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authtoken
};
try{
http.Response response = await Request.instance.deleteRequest(path: path, headers: headers, body: {"id":id}, param: params);
if(response.statusCode == 200){
Map data = jsonDecode(response.body);
success=data['success'];
}else{
success = false;
}
return success!;
}catch(e){
throw e.toString();
}
}
}

View File

@ -24,7 +24,7 @@ class WorkHistoryService {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authToken
};
String path = Url.instance.getWorkHistories() + profileId.toString();
String path = Url.instance.workhistory() + profileId.toString();
try {
http.Response response = await Request.instance
.getRequest(path: path, headers: headers, param: {});
@ -75,7 +75,7 @@ class WorkHistoryService {
bool? success;
Map<String, dynamic> params = {"force_mode": "true"};
String authToken = "Token $token";
String path = "${Url.instance.deleteWorkHistory()}$profileId/";
String path = "${Url.instance.workhistory()}$profileId/";
Map body = {
"id": work.id,
"position_id": work.position!.id,
@ -136,7 +136,7 @@ class WorkHistoryService {
Future<Map<dynamic,dynamic>> update({required WorkHistory oldWorkHistory, required WorkHistory newWorkHistory, required String token, required String profileId})async{
Map<dynamic, dynamic>? statusResponse={};
String authtoken = "Token $token";
String path = '${Url.instance.updateWorkHistories()}$profileId/';
String path = '${Url.instance.workhistory()}$profileId/';
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authtoken
@ -176,7 +176,7 @@ class WorkHistoryService {
//Add work history
Future<Map<dynamic, dynamic>>add({required WorkHistory workHistory, required String token, required int profileId , required bool isPrivate})async{
String authtoken = "Token $token";
String path = '${Url.instance.addWorkHistory()}$profileId/';
String path = '${Url.instance.workhistory()}$profileId/';
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authtoken

View File

@ -1,5 +1,7 @@
import 'dart:convert';
import 'package:unit2/model/location/address_category.dart';
import 'package:unit2/model/location/barangay.dart';
import 'package:unit2/model/location/city.dart';
import 'package:unit2/model/location/country.dart';
import 'package:http/http.dart' as http;
@ -8,95 +10,133 @@ import 'package:unit2/utils/request.dart';
import 'package:unit2/utils/urls.dart';
import '../model/location/region.dart';
class LocationUtils {
static final LocationUtils _instance = LocationUtils();
static LocationUtils get instance => _instance;
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
Future<List<Country>>getCountries()async{
List<Country> countries=[];
Future<List<Country>> getCountries() async {
List<Country> countries = [];
String path = Url.instance.getCounties();
// try{
http.Response response = await Request.instance.getRequest(path: path, param: {},headers: headers);
if(response.statusCode == 200){
Map data = jsonDecode(response.body);
if(data['data'] != null){
data['data'].forEach((var country){
Country newCOuntry = Country.fromJson(country);
countries.add(newCOuntry);
});
}
}
// }catch(e){
// throw(e.toString());
// }
return countries;
}
Future<List<Region>>getRegions()async{
List<Region> regions=[];
String path = Url.instance.getRegions();
// try{
http.Response response = await Request.instance.getRequest(path: path, param: {},headers: headers);
if(response.statusCode == 200){
Map data = jsonDecode(response.body);
if(data['data'] != null){
data['data'].forEach((var region){
Region newRegion = Region.fromJson(region);
regions.add(newRegion);
});
}
}
// }catch(e){
// throw(e.toString());
// }
return regions;
}
Future<List<Province>>getProvinces({required String regionCode})async{
List<Province> provinces = [];
String path = Url.instance.getProvinces()+regionCode;
try{
http.Response response = await Request.instance.getRequest(path: path,param:{},headers: headers);
http.Response response = await Request.instance
.getRequest(path: path, param: {}, headers: headers);
if (response.statusCode == 200) {
Map data = jsonDecode(response.body);
if(data['data'] != null){
data['data'].forEach((var province){
if (data['data'] != null) {
data['data'].forEach((var country) {
Country newCOuntry = Country.fromJson(country);
countries.add(newCOuntry);
});
}
}
}catch(e){
throw(e.toString());
}
return countries;
}
Future<List<Region>> getRegions() async {
List<Region> regions = [];
String path = Url.instance.getRegions();
try{
http.Response response = await Request.instance
.getRequest(path: path, param: {}, headers: headers);
if (response.statusCode == 200) {
Map data = jsonDecode(response.body);
if (data['data'] != null) {
data['data'].forEach((var region) {
Region newRegion = Region.fromJson(region);
regions.add(newRegion);
});
}
}
}catch(e){
throw(e.toString());
}
return regions;
}
Future<List<Province>> getProvinces({required String regionCode}) async {
List<Province> provinces = [];
String path = Url.instance.getProvinces() + regionCode;
try {
http.Response response = await Request.instance
.getRequest(path: path, param: {}, headers: headers);
Map data = jsonDecode(response.body);
if (data['data'] != null) {
data['data'].forEach((var province) {
Province newProvince = Province.fromJson(province);
provinces.add(newProvince);
});
}
}catch(e){
throw(e.toString());
} catch (e) {
throw (e.toString());
}
return provinces;
return provinces;
}
Future<List<CityMunicipality>>getCities({required String code})async{
Future<List<CityMunicipality>> getCities({required String code}) async {
List<CityMunicipality> cities = [];
String path = Url.instance.getCities()+code;
try{
http.Response response = await Request.instance.getRequest(path: path, param: {},headers: headers);
String path = Url.instance.getCities() + code;
try {
http.Response response = await Request.instance
.getRequest(path: path, param: {}, headers: headers);
Map data = jsonDecode(response.body);
if(data['data'] != null){
data['data'].forEach((var city){
if (data['data'] != null) {
data['data'].forEach((var city) {
CityMunicipality cityMun = CityMunicipality.fromJson(city);
cities.add(cityMun);
});
}
}catch(e){
throw(e.toString());
} catch (e) {
throw (e.toString());
}
return cities;
}
}
Future<List<Barangay>> getBarangay({required String code}) async {
List<Barangay> barangays = [];
String path = Url.instance.getBarangays() + code;
try {
http.Response response = await Request.instance
.getRequest(path: path, param: {}, headers: headers);
Map data = jsonDecode(response.body);
if (data['data'] != null) {
data['data'].forEach((var city) {
Barangay barangay = Barangay.fromJson(city);
barangays.add(barangay);
});
}
} catch (e) {
throw (e.toString());
}
return barangays;
}
Future<List<AddressCategory>>getAddressCategory()async{
List<AddressCategory> categories = [];
String path = Url.instance.getAddressCategory();
try{
http.Response response = await Request.instance.getRequest(path: path,param: {},headers:headers );
Map data = jsonDecode(response.body);
if(data['data'] != null){
data['data'].forEach((var cat){
categories.add(AddressCategory.fromJson(cat));
});
}
categories;
return categories;
}catch(e){
throw e.toString();
}
}
}

View File

@ -42,7 +42,7 @@ String updateEligibility(){
return "/api/jobnet_app/profile/pds/eligibility/";
}
//// work history paths
String getWorkHistories(){
String workhistory(){
return "/api/jobnet_app/profile/pds/work/";
}
String getPositions(){
@ -51,19 +51,13 @@ String getPositions(){
String getAgencies(){
return "/api/jobnet_app/agencies/";
}
String updateWorkHistories(){
return "/api/jobnet_app/profile/pds/work/";
}
String addWorkHistory(){
return "/api/jobnet_app/profile/pds/work/";
}
String getAgencyCategory(){
return "api/jobnet_app/agency_categories/";
}
String deleteWorkHistory(){
return "/api/jobnet_app/profile/pds/work/";
}
////educational background paths
String getEducationalBackgrounds(){
@ -77,7 +71,7 @@ String getLearningAndDevelopments(){
}
//// references paths
String getRefences(){
String reference(){
return "/api/jobnet_app/profile/pds/personal_reference/";
}
@ -106,6 +100,7 @@ String getFamilies(){
return "/api/jobnet_app/profile/pds/family/";
}
// location utils path
String getCounties(){
return "/api/jobnet_app/countries/";
@ -119,4 +114,10 @@ String getFamilies(){
String getCities(){
return "/api/web_app/location/citymun/";
}
String getBarangays(){
return "/api/web_app/location/barangay/";
}
String getAddressCategory(){
return "/api/jobnet_app/address_categories/";
}
}