Dart : Convert From Iterable<ActivityModel> To ActivityModel - flutter

I have model Like This :
Model
class ActivityModel {
String idActivity;
String titleActivity;
String dateTimeActivity;
int isDoneActivity;
int codeIconActivity;
String informationActivity;
String createdDateActivity;
ActivityModel({
this.idActivity,
this.titleActivity,
this.dateTimeActivity,
this.isDoneActivity,
this.codeIconActivity,
this.informationActivity,
this.createdDateActivity,
});
ActivityModel.fromSqflite(Map<String, dynamic> map)
: idActivity = map['id_activity'],
titleActivity = map['title_activity'],
dateTimeActivity = map['datetime_activity'],
isDoneActivity = map['is_done_activity'],
codeIconActivity = map['code_icon_activity'],
informationActivity = map['information_activity'],
createdDateActivity = map['created_date'];
Map<String, dynamic> toMapForSqflite() {
return {
'id_activity': this.idActivity,
'title_activity': this.titleActivity,
'datetime_activity': this.dateTimeActivity,
'is_done_activity': this.isDoneActivity,
'code_icon_activity': this.codeIconActivity,
'information_activity': this.informationActivity,
'created_date': this.createdDateActivity,
};
}
I want get data where dateTimeActivity is before than date now, then i update isDoneActivity = 1 with this code :
Source code
final passedDateItem = _selectedActivityItem.where((element) {
DateTime convertStringToDateTime =
DateTime.parse(element.dateTimeActivity);
return convertStringToDateTime.isBefore(DateTime.now());
});
if (passedDateItem != null) {
print('Not Null');
} else {
print('Nulledd');
return null;
}
The problem is , passedDateItem return Iterable[ActivityModel] , it's possible to convert it to ActivityModel? So i can easly update like this ?
if (passedDateItem != null) {
passedDateItem.isDoneActivity = 1; <<<
// return passedDateItem.map((e) => e.isDoneActivity = 1);
// final testtt= passedDateItem.
print('Not Null');
} else {
print('Nulledd');
return null;
}

Iterate through passedDateItem
for (var activityModel in passedDateItem) {
//..conditions
activityModel.isDoneActivity = 1;
}
If you are only interested in the first/last element of passedDateItem
use
passedDateItem.first.isDoneActivity == 1
or
passedDateItem.last.isDoneActivity == 1
make sure passedDateItem is not empty in that case.

Related

In Dart Flutter, if else conditions causing problems

In Dart Flutter if else conditions causing problems.
In this method with if else conditions the forEach loop is not working properly
as it does not allowing the print statement to print each key and value in the map.
Data for map comes from the firestore database
But
when I remove if else conditions , then it is working properly
Please help.
CODE
Future<List<ReviewModel>> getCakeReview(String cakeId) async {
CollectionReference snap = types.doc(cakeId).collection('Reviews');
List<ReviewModel> list = [];
ReviewModel model = ReviewModel("", "", 0, "");
String userName = "";
String userDP = "";
String review = "";
int rating = 0;
await snap.get().then((value) {
for (var result in value.docs) {
Map<String, dynamic> map = result.data() as Map<String, dynamic>;
print(map);
int i = 0;
map.forEach((key, value) {
print(key.toString() + ":" + value.toString());
print(i++);
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating = value;
} else {
review = value.toString();
}
});
model = ReviewModel(userName, userDP, rating, review);
list.add(model);
}
});
print("FS");
return list;
}
Output Image link
replace
map.forEach((key, value) {
print(key.toString() + ":" + value.toString());
print(i++);
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating = value;
} else {
review = value.toString();
}
});
with
userName = map['userName'];
userDP = map['userDP'];
rating = map['rating'];
review = map['review'];
to eliminate the "for-switch" anti-pattern.
Now I got what was the problem,
I try to store the value(which is not integer when returned from firebase I think) into the rating variable which is an integer type
so what I did is,
parsed the value to integer and it worked fine.
Code
map.forEach((key, value) {
print(key.toString() + ":" + value.toString());
print(i++);
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating =int.parse(value);
} else {
review = value.toString();
}
});

my code not complete for where contact number

How to fix code my code flutter and use plugin
filterContacts() {
setState(() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere(
(contact) {
String searchTerm = searchController.text.toLowerCase().trim();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toString().toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
var phone = contact.phones.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, orElse: () => null);
return phone != null;
},
);
contactsFiltered = _contacts;
}
});
}
Flutter code How to fix code my code flutter and use plugin contacts_service,
this image is about a problem
contact.phones can be null, in this you need to check its value 1st then proceed,
you can use contact.phones?.firstWhere to handle this situation or
If you're sure it will have value, you can also do contact.phones!.firstWhere but I don't recommend this. You don't need to use orElse you want to pass null,
Item? phone = contact.phones?.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, );
You can learn more about ?. !...
[how to fix now]
error code not complete
filterContacts() {
setState(() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere(
(contact) {
String searchTerm = searchController.text.toLowerCase().trim();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toString().toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
Item? phone = contact.phones?.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, );
return phone != null;
},
);
contactsFiltered = _contacts;
}
});
}

Exception: type 'String' is not a subtype of type 'int' - Flutter

I am trying to make a Get request in flutter.
I did everything right but it is showing me the error: type 'String' is not a sub-type of type 'int'.
I am getting error thrown on catch block saying at line 394 of Model class footerStyleType is String but i checked the json it is int.
This is my get request:
class FormDataAdp extends ChangeNotifier {
FormListModel formlist;
String formdatahttpcode = "";
resetFormDataAdp() {
formlist = null;
formdatahttpcode = "";
}
refreshdata(String token) {
resetFormDataAdp();
notifyListeners();
getFormList(token);
}
getFormList(String token) async {
try {
final url = Helper.baseURL + "form-manager-owned/10/false/all?page=1";
final client = http.Client();
final response = await client.get(Uri.parse(url), headers: {
'Authorization': 'Bearer $token',
});
print(response.body + response.statusCode.toString());
formdatahttpcode = response.statusCode.toString();
print(formdatahttpcode);
notifyListeners();
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body);
formlist = FormListModel.fromJson(parsed);
notifyListeners();
return formlist;
} else {
throw Exception("Unable to fetch the data.");
}
} catch (e) {
throw Exception(e.toString());
}
}
}
This is my Model Class which i converted into dart from Json.
class FormListModel {
Forms forms;
int totalRecords;
int totalActiveForms;
FormListModel({this.forms, this.totalRecords, this.totalActiveForms});
FormListModel.fromJson(Map<String, dynamic> json) {
forms = json['forms'] != null ? new Forms.fromJson(json['forms']) : null;
totalRecords = json['total_records'];
totalActiveForms = json['total_active_forms'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.forms != null) {
data['forms'] = this.forms.toJson();
}
data['total_records'] = this.totalRecords;
data['total_active_forms'] = this.totalActiveForms;
return data;
}
}
class Forms {
int currentPage;
List<Data> data;
String firstPageUrl;
int from;
int lastPage;
String lastPageUrl;
List<Links> links;
String nextPageUrl;
String path;
int perPage;
String prevPageUrl;
int to;
int total;
Forms(
{this.currentPage,
this.data,
this.firstPageUrl,
this.from,
this.lastPage,
this.lastPageUrl,
this.links,
this.nextPageUrl,
this.path,
this.perPage,
this.prevPageUrl,
this.to,
this.total});
Forms.fromJson(Map<String, dynamic> json) {
currentPage = json['current_page'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
firstPageUrl = json['first_page_url'];
from = json['from'];
lastPage = json['last_page'];
lastPageUrl = json['last_page_url'];
if (json['links'] != null) {
links = <Links>[];
json['links'].forEach((v) {
links.add(new Links.fromJson(v));
});
}
nextPageUrl = json['next_page_url'];
path = json['path'];
perPage = json['per_page'];
prevPageUrl = json['prev_page_url'];
to = json['to'];
total = json['total'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['current_page'] = this.currentPage;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
data['first_page_url'] = this.firstPageUrl;
data['from'] = this.from;
data['last_page'] = this.lastPage;
data['last_page_url'] = this.lastPageUrl;
if (this.links != null) {
data['links'] = this.links.map((v) => v.toJson()).toList();
}
data['next_page_url'] = this.nextPageUrl;
data['path'] = this.path;
data['per_page'] = this.perPage;
data['prev_page_url'] = this.prevPageUrl;
data['to'] = this.to;
data['total'] = this.total;
return data;
}
}
class Data {
String sId;
bool fieldError;
String validationError;
List<String> rules;
bool ruleApplicable;
bool ruleConditionApplicable;
bool isDisabled;
String group;
String placeholderValue;
bool questionLabelHide;
int formId;
int id;
String label;
String guideLinesForUser;
int visibleTo;
bool isRequired;
int position;
GeneralOptionClass propertyStaticOptions;
List<GeneralOptionClass> visibleToOptions;
int page;
List<GeneralOptionClass> classificationOptions;
int classification;
String fieldName;
int alignment;
List<GeneralOptionClass> alignmentOptions;
bool isHidden;
String controlType;
bool active;
bool editownentry;
bool enableEditAfterReviewPage;
bool submitButtonDisabled;
String isUserAuthenticated;
List<String> payment;
bool enableFormFooter;
int footerType;
int footerPadding;
int footerStyleType;
String footerContent;
List<String> relationships;
List<String> formRules;
bool enableSaveAndResumeLater;
int fieldSize;
int fieldHeight;
bool headerDeleted;
PageNavigator pageNavigator;
bool enableClientLogin;
int entriesCount;
int clientLoginWith;
List<GeneralOptionClass> clientLoginWithOptions;
bool enableReviewPage;
String reviewPageTitle;
String reviewPageDescription;
int buttonStyle;
List<GeneralOptionClass> buttonStyleOptions;
String submitButtonText;
String backButtonText;
String submitButtonImageURL;
String backButtonImageURL;
bool enablePasswordProtection;
String password;
bool enableSpamProtection;
int spamType;
List<GeneralOptionClass> spamTypeOptions;
bool limitOneEntryPerIP;
bool limitOneEntryPerUserId;
bool limitEntries;
int maxEntriesLimit;
bool enableAutomaticScheduling;
int timeOption;
List<GeneralOptionClass> timeOptions;
int formType;
List<GeneralOptionClass> formTypes;
String scheduleFromDate;
String scheduleToDate;
int dateFormat;
List<GeneralOptionClass> footerTypeOptions;
String footerImageUrl;
int footerImageheight;
int footerImagewidth;
List<GeneralOptionClass> footerStyleTypeOptions;
bool isTemplate;
bool redirectionSet;
String redirecturl;
String redirectionMsg;
bool redirectPostConfirmation;
bool showtitledesc;
String createdBy;
String updatedBy;
bool showTimer;
int leftTime;
int notifyBefore;
bool showInternalUsers;
bool showTimerNotification;
String timerNotificationMessage;
bool demandTimerStart;
int demandTimerPage;
bool enableAutoSubmitWithTimer;
String defaultSaveNResumeEmailSubject;
List<FieldRules> fieldRules;
bool negativeMarking;
int negationPercentage;
List<GeneralOptionClass> fieldSizeOptions;
String clientid;
bool published;
String updatedAt;
String createdAt;
String createdByName;
List<Permissions> permissions;
int pendingAprovalCount;
CreatedView createdView;
List<String> sharedWith;
Data(
{this.sId,
this.fieldError,
this.validationError,
this.rules,
this.ruleApplicable,
this.ruleConditionApplicable,
this.isDisabled,
this.group,
this.placeholderValue,
this.questionLabelHide,
this.formId,
this.id,
this.label,
this.guideLinesForUser,
this.visibleTo,
this.isRequired,
this.position,
this.propertyStaticOptions,
this.visibleToOptions,
this.page,
this.classificationOptions,
this.classification,
this.fieldName,
this.alignment,
this.alignmentOptions,
this.isHidden,
this.controlType,
this.active,
this.editownentry,
this.enableEditAfterReviewPage,
this.submitButtonDisabled,
this.isUserAuthenticated,
this.payment,
this.enableFormFooter,
this.footerType,
this.footerPadding,
this.footerStyleType,
this.footerContent,
this.relationships,
this.formRules,
this.enableSaveAndResumeLater,
this.fieldSize,
this.fieldHeight,
this.headerDeleted,
this.pageNavigator,
this.enableClientLogin,
this.entriesCount,
this.clientLoginWith,
this.clientLoginWithOptions,
this.enableReviewPage,
this.reviewPageTitle,
this.reviewPageDescription,
this.buttonStyle,
this.buttonStyleOptions,
this.submitButtonText,
this.backButtonText,
this.submitButtonImageURL,
this.backButtonImageURL,
this.enablePasswordProtection,
this.password,
this.enableSpamProtection,
this.spamType,
this.spamTypeOptions,
this.limitOneEntryPerIP,
this.limitOneEntryPerUserId,
this.limitEntries,
this.maxEntriesLimit,
this.enableAutomaticScheduling,
this.timeOption,
this.timeOptions,
this.formType,
this.formTypes,
this.scheduleFromDate,
this.scheduleToDate,
this.dateFormat,
this.footerTypeOptions,
this.footerImageUrl,
this.footerImageheight,
this.footerImagewidth,
this.footerStyleTypeOptions,
this.isTemplate,
this.redirectionSet,
this.redirecturl,
this.redirectionMsg,
this.redirectPostConfirmation,
this.showtitledesc,
this.createdBy,
this.updatedBy,
this.showTimer,
this.leftTime,
this.notifyBefore,
this.showInternalUsers,
this.showTimerNotification,
this.timerNotificationMessage,
this.demandTimerStart,
this.demandTimerPage,
this.enableAutoSubmitWithTimer,
this.defaultSaveNResumeEmailSubject,
this.fieldRules,
this.negativeMarking,
this.negationPercentage,
this.fieldSizeOptions,
this.clientid,
this.published,
this.updatedAt,
this.createdAt,
this.createdByName,
this.permissions,
this.pendingAprovalCount,
this.createdView,
this.sharedWith});
Data.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
fieldError = json['fieldError'];
validationError = json['validationError'];
if (json['rules'] != null) {
rules = <String>[];
json['rules'].forEach((v) {
rules.add(v);
});
}
ruleApplicable = json['ruleApplicable'];
ruleConditionApplicable = json['ruleConditionApplicable'];
isDisabled = json['isDisabled'];
group = json['group'];
placeholderValue = json['placeholderValue'];
questionLabelHide = json['questionLabelHide'];
formId = json['form_id'];
id = json['id'];
label = json['label'];
guideLinesForUser = json['guideLinesForUser'];
visibleTo = json['visibleTo'];
isRequired = json['isRequired'];
position = json['position'];
propertyStaticOptions = json['propertyStaticOptions'] != null
? new GeneralOptionClass.fromJson(json['propertyStaticOptions'])
: null;
if (json['visibleToOptions'] != null) {
visibleToOptions = <GeneralOptionClass>[];
json['visibleToOptions'].forEach((v) {
visibleToOptions.add(new GeneralOptionClass.fromJson(v));
});
}
page = json['page'];
if (json['classificationOptions'] != null) {
classificationOptions = <GeneralOptionClass>[];
json['classificationOptions'].forEach((v) {
classificationOptions.add(new GeneralOptionClass.fromJson(v));
});
}
classification = json['classification'];
fieldName = json['fieldName'];
alignment = json['alignment'];
if (json['alignmentOptions'] != null) {
alignmentOptions = <GeneralOptionClass>[];
json['alignmentOptions'].forEach((v) {
alignmentOptions.add(new GeneralOptionClass.fromJson(v));
});
}
isHidden = json['isHidden'];
controlType = json['controlType'];
active = json['active'];
editownentry = json['editownentry'];
enableEditAfterReviewPage = json['enableEditAfterReviewPage'];
submitButtonDisabled = json['submitButtonDisabled'];
isUserAuthenticated = json['isUserAuthenticated'];
if (json['payment'] != null) {
payment = <String>[];
json['payment'].forEach((v) {
payment.add(v);
});
}
enableFormFooter = json['enableFormFooter'];
footerType = json['footerType'];
footerPadding = json['footerPadding'];
footerStyleType = json['footerStyleType'];
footerContent = json['footerContent'];
if (json['relationships'] != null) {
relationships = <String>[];
json['relationships'].forEach((v) {
relationships.add(v);
});
}
if (json['formRules'] != null) {
formRules = <String>[];
json['formRules'].forEach((v) {
formRules.add(v);
});
}
enableSaveAndResumeLater = json['enableSaveAndResumeLater'];
fieldSize = json['fieldSize'];
fieldHeight = json['fieldHeight'];
headerDeleted = json['headerDeleted'];
pageNavigator = json['pageNavigator'] != null
? new PageNavigator.fromJson(json['pageNavigator'])
: null;
enableClientLogin = json['enableClientLogin'];
entriesCount = json['entriesCount'];
clientLoginWith = json['clientLoginWith'];
if (json['clientLoginWithOptions'] != null) {
clientLoginWithOptions = <GeneralOptionClass>[];
json['clientLoginWithOptions'].forEach((v) {
clientLoginWithOptions.add(new GeneralOptionClass.fromJson(v));
});
}
enableReviewPage = json['enableReviewPage'];
reviewPageTitle = json['reviewPageTitle'];
reviewPageDescription = json['reviewPageDescription'];
buttonStyle = json['buttonStyle'];
if (json['buttonStyleOptions'] != null) {
buttonStyleOptions = <GeneralOptionClass>[];
json['buttonStyleOptions'].forEach((v) {
buttonStyleOptions.add(new GeneralOptionClass.fromJson(v));
});
}
submitButtonText = json['submitButtonText'];
backButtonText = json['backButtonText'];
submitButtonImageURL = json['submitButtonImageURL'];
backButtonImageURL = json['backButtonImageURL'];
enablePasswordProtection = json['enablePasswordProtection'];
password = json['password'];
enableSpamProtection = json['enableSpamProtection'];
spamType = json['spamType'];
if (json['spamTypeOptions'] != null) {
spamTypeOptions = <GeneralOptionClass>[];
json['spamTypeOptions'].forEach((v) {
spamTypeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
limitOneEntryPerIP = json['limitOneEntryPerIP'];
limitOneEntryPerUserId = json['limitOneEntryPerUserId'];
limitEntries = json['limitEntries'];
maxEntriesLimit = json['maxEntriesLimit'];
enableAutomaticScheduling = json['enableAutomaticScheduling'];
timeOption = json['timeOption'];
if (json['timeOptions'] != null) {
timeOptions = <GeneralOptionClass>[];
json['timeOptions'].forEach((v) {
timeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
formType = json['formType'];
if (json['formTypes'] != null) {
formTypes = <GeneralOptionClass>[];
json['formTypes'].forEach((v) {
formTypes.add(new GeneralOptionClass.fromJson(v));
});
}
scheduleFromDate = json['scheduleFromDate'];
scheduleToDate = json['scheduleToDate'];
dateFormat = json['dateFormat'];
if (json['footerTypeOptions'] != null) {
footerTypeOptions = <GeneralOptionClass>[];
json['footerTypeOptions'].forEach((v) {
footerTypeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
footerImageUrl = json['footerImageUrl'];
footerImageheight = json['footerImageheight'];
footerImagewidth = json['footerImagewidth'];
if (json['footerStyleTypeOptions'] != null) {
footerStyleTypeOptions = <GeneralOptionClass>[];
json['footerStyleTypeOptions'].forEach((v) {
footerStyleTypeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
isTemplate = json['isTemplate'];
redirectionSet = json['redirectionSet'];
redirecturl = json['redirecturl'];
redirectionMsg = json['redirectionMsg'];
redirectPostConfirmation = json['redirectPostConfirmation'];
showtitledesc = json['showtitledesc'];
createdBy = json['createdBy'];
updatedBy = json['updatedBy'];
showTimer = json['showTimer'];
leftTime = json['leftTime'];
notifyBefore = json['notifyBefore'];
showInternalUsers = json['showInternalUsers'];
showTimerNotification = json['showTimerNotification'];
timerNotificationMessage = json['timerNotificationMessage'];
demandTimerStart = json['demandTimerStart'];
demandTimerPage = json['demandTimerPage'];
enableAutoSubmitWithTimer = json['enableAutoSubmitWithTimer'];
defaultSaveNResumeEmailSubject = json['defaultSaveNResumeEmailSubject'];
if (json['fieldRules'] != null) {
fieldRules = <FieldRules>[];
json['fieldRules'].forEach((v) {
fieldRules.add(new FieldRules.fromJson(v));
});
}
negativeMarking = json['negativeMarking'];
negationPercentage = json['negationPercentage'];
if (json['fieldSizeOptions'] != null) {
fieldSizeOptions = <GeneralOptionClass>[];
json['fieldSizeOptions'].forEach((v) {
fieldSizeOptions.add(new GeneralOptionClass.fromJson(v));
});
}
clientid = json['clientid'];
published = json['published'];
updatedAt = json['updated_at'];
createdAt = json['created_at'];
createdByName = json['createdByName'];
if (json['permissions'] != null) {
permissions = <Permissions>[];
json['permissions'].forEach((v) {
permissions.add(new Permissions.fromJson(v));
});
}
pendingAprovalCount = json['pendingAprovalCount'];
createdView = json['created_view'] != null
? new CreatedView.fromJson(json['created_view'])
: null;
sharedWith = json['sharedWith'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['fieldError'] = this.fieldError;
data['validationError'] = this.validationError;
// if (this.rules != null) {
// data['rules'] = this.rules.map((v) => v.toJson()).toList();
// }
data['ruleApplicable'] = this.ruleApplicable;
data['ruleConditionApplicable'] = this.ruleConditionApplicable;
data['isDisabled'] = this.isDisabled;
data['group'] = this.group;
data['placeholderValue'] = this.placeholderValue;
data['questionLabelHide'] = this.questionLabelHide;
data['form_id'] = this.formId;
data['id'] = this.id;
data['label'] = this.label;
data['guideLinesForUser'] = this.guideLinesForUser;
data['visibleTo'] = this.visibleTo;
data['isRequired'] = this.isRequired;
data['position'] = this.position;
if (this.propertyStaticOptions != null) {
data['propertyStaticOptions'] = this.propertyStaticOptions.toJson();
}
if (this.visibleToOptions != null) {
data['visibleToOptions'] =
this.visibleToOptions.map((v) => v.toJson()).toList();
}
data['page'] = this.page;
if (this.classificationOptions != null) {
data['classificationOptions'] =
this.classificationOptions.map((v) => v.toJson()).toList();
}
data['classification'] = this.classification;
data['fieldName'] = this.fieldName;
data['alignment'] = this.alignment;
if (this.alignmentOptions != null) {
data['alignmentOptions'] =
this.alignmentOptions.map((v) => v.toJson()).toList();
}
data['isHidden'] = this.isHidden;
data['controlType'] = this.controlType;
data['active'] = this.active;
data['editownentry'] = this.editownentry;
data['enableEditAfterReviewPage'] = this.enableEditAfterReviewPage;
data['submitButtonDisabled'] = this.submitButtonDisabled;
data['isUserAuthenticated'] = this.isUserAuthenticated;
// if (this.payment != null) {
// data['payment'] = this.payment.map((v) => v.toJson()).toList();
// }
data['enableFormFooter'] = this.enableFormFooter;
data['footerType'] = this.footerType;
data['footerPadding'] = this.footerPadding;
data['footerStyleType'] = this.footerStyleType;
data['footerContent'] = this.footerContent;
// if (this.relationships != null) {
// data['relationships'] =
// this.relationships.map((v) => v.toJson()).toList();
// }
// if (this.formRules != null) {
// data['formRules'] = this.formRules.map((v) => v.toJson()).toList();
// }
data['enableSaveAndResumeLater'] = this.enableSaveAndResumeLater;
data['fieldSize'] = this.fieldSize;
data['fieldHeight'] = this.fieldHeight;
data['headerDeleted'] = this.headerDeleted;
if (this.pageNavigator != null) {
data['pageNavigator'] = this.pageNavigator.toJson();
}
data['enableClientLogin'] = this.enableClientLogin;
data['entriesCount'] = this.entriesCount;
data['clientLoginWith'] = this.clientLoginWith;
if (this.clientLoginWithOptions != null) {
data['clientLoginWithOptions'] =
this.clientLoginWithOptions.map((v) => v.toJson()).toList();
}
data['enableReviewPage'] = this.enableReviewPage;
data['reviewPageTitle'] = this.reviewPageTitle;
data['reviewPageDescription'] = this.reviewPageDescription;
data['buttonStyle'] = this.buttonStyle;
if (this.buttonStyleOptions != null) {
data['buttonStyleOptions'] =
this.buttonStyleOptions.map((v) => v.toJson()).toList();
}
data['submitButtonText'] = this.submitButtonText;
data['backButtonText'] = this.backButtonText;
data['submitButtonImageURL'] = this.submitButtonImageURL;
data['backButtonImageURL'] = this.backButtonImageURL;
data['enablePasswordProtection'] = this.enablePasswordProtection;
data['password'] = this.password;
data['enableSpamProtection'] = this.enableSpamProtection;
data['spamType'] = this.spamType;
if (this.spamTypeOptions != null) {
data['spamTypeOptions'] =
this.spamTypeOptions.map((v) => v.toJson()).toList();
}
data['limitOneEntryPerIP'] = this.limitOneEntryPerIP;
data['limitOneEntryPerUserId'] = this.limitOneEntryPerUserId;
data['limitEntries'] = this.limitEntries;
data['maxEntriesLimit'] = this.maxEntriesLimit;
data['enableAutomaticScheduling'] = this.enableAutomaticScheduling;
data['timeOption'] = this.timeOption;
if (this.timeOptions != null) {
data['timeOptions'] = this.timeOptions.map((v) => v.toJson()).toList();
}
data['formType'] = this.formType;
if (this.formTypes != null) {
data['formTypes'] = this.formTypes.map((v) => v.toJson()).toList();
}
data['scheduleFromDate'] = this.scheduleFromDate;
data['scheduleToDate'] = this.scheduleToDate;
data['dateFormat'] = this.dateFormat;
if (this.footerTypeOptions != null) {
data['footerTypeOptions'] =
this.footerTypeOptions.map((v) => v.toJson()).toList();
}
data['footerImageUrl'] = this.footerImageUrl;
data['footerImageheight'] = this.footerImageheight;
data['footerImagewidth'] = this.footerImagewidth;
if (this.footerStyleTypeOptions != null) {
data['footerStyleTypeOptions'] =
this.footerStyleTypeOptions.map((v) => v.toJson()).toList();
}
data['isTemplate'] = this.isTemplate;
data['redirectionSet'] = this.redirectionSet;
data['redirecturl'] = this.redirecturl;
data['redirectionMsg'] = this.redirectionMsg;
data['redirectPostConfirmation'] = this.redirectPostConfirmation;
data['showtitledesc'] = this.showtitledesc;
data['createdBy'] = this.createdBy;
data['updatedBy'] = this.updatedBy;
data['showTimer'] = this.showTimer;
data['leftTime'] = this.leftTime;
data['notifyBefore'] = this.notifyBefore;
data['showInternalUsers'] = this.showInternalUsers;
data['showTimerNotification'] = this.showTimerNotification;
data['timerNotificationMessage'] = this.timerNotificationMessage;
data['demandTimerStart'] = this.demandTimerStart;
data['demandTimerPage'] = this.demandTimerPage;
data['enableAutoSubmitWithTimer'] = this.enableAutoSubmitWithTimer;
data['defaultSaveNResumeEmailSubject'] =
this.defaultSaveNResumeEmailSubject;
if (this.fieldRules != null) {
data['fieldRules'] = this.fieldRules.map((v) => v.toJson()).toList();
}
data['negativeMarking'] = this.negativeMarking;
data['negationPercentage'] = this.negationPercentage;
if (this.fieldSizeOptions != null) {
data['fieldSizeOptions'] =
this.fieldSizeOptions.map((v) => v.toJson()).toList();
}
data['clientid'] = this.clientid;
data['published'] = this.published;
data['updated_at'] = this.updatedAt;
data['created_at'] = this.createdAt;
data['createdByName'] = this.createdByName;
if (this.permissions != null) {
data['permissions'] = this.permissions.map((v) => v.toJson()).toList();
}
data['pendingAprovalCount'] = this.pendingAprovalCount;
if (this.createdView != null) {
data['created_view'] = this.createdView.toJson();
}
data['sharedWith'] = this.sharedWith;
return data;
}
}
class GeneralOptionClass {
int id;
String option;
GeneralOptionClass({this.id, this.option});
GeneralOptionClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
option = json['option'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['option'] = this.option;
return data;
}
}
}
I debugged also but it is still same. Please help. If you have any questions please ask.

Format string to phone number with (123) 456-6789 pattern using dart

Here is my code
void main() {
String phoneNumber = '123456789';
String formattedPhoneNumber = phoneNumber.replaceFirst("(\d{3})(\d{3})(\d+)", "(\$1) \$2-\$3");
print('Formatted number ${formattedPhoneNumber}');
}
Output:
Formatted number 123456789
I want output as Formatted number (123) 456-6789
Try this
print('1234567890'.replaceAllMapped(RegExp(r'(\d{3})(\d{3})(\d+)'), (Match m) => "(${m[1]}) ${m[2]}-${m[3]}"));
Create a custom Masked class
import 'package:flutter/material.dart';
class MaskedTextController extends TextEditingController {
MaskedTextController({String text, this.mask, Map<String, RegExp> translator})
: super(text: text) {
this.translator = translator ?? MaskedTextController.getDefaultTranslator();
this.addListener(() {
var previous = this._lastUpdatedText;
if (this.beforeChange(previous, this.text)) {
this.updateText(this.text);
this.afterChange(previous, this.text);
} else {
this.updateText(this._lastUpdatedText);
}
});
this.updateText(this.text);
}
String mask;
Map<String, RegExp> translator;
Function afterChange = (String previous, String next) {};
Function beforeChange = (String previous, String next) {
return true;
};
String _lastUpdatedText = '';
void updateText(String text) {
if(text != null){
this.text = this._applyMask(this.mask, text);
}
else {
this.text = '';
}
this._lastUpdatedText = this.text;
}
void updateMask(String mask, {bool moveCursorToEnd = true}) {
this.mask = mask;
this.updateText(this.text);
if (moveCursorToEnd) {
this.moveCursorToEnd();
}
}
void moveCursorToEnd() {
var text = this._lastUpdatedText;
this.selection = new TextSelection.fromPosition(
new TextPosition(offset: (text ?? '').length));
}
#override
void set text(String newText) {
if (super.text != newText) {
super.text = newText;
this.moveCursorToEnd();
}
}
static Map<String, RegExp> getDefaultTranslator() {
return {
'A': new RegExp(r'[A-Za-z]'),
'0': new RegExp(r'[0-9]'),
'#': new RegExp(r'[A-Za-z0-9]'),
'*': new RegExp(r'.*')
};
}
String _applyMask(String mask, String value) {
String result = '';
var maskCharIndex = 0;
var valueCharIndex = 0;
while (true) {
// if mask is ended, break.
if (maskCharIndex == mask.length) {
break;
}
// if value is ended, break.
if (valueCharIndex == value.length) {
break;
}
var maskChar = mask[maskCharIndex];
var valueChar = value[valueCharIndex];
// value equals mask, just set
if (maskChar == valueChar) {
result += maskChar;
valueCharIndex += 1;
maskCharIndex += 1;
continue;
}
// apply translator if match
if (this.translator.containsKey(maskChar)) {
if (this.translator[maskChar].hasMatch(valueChar)) {
result += valueChar;
maskCharIndex += 1;
}
valueCharIndex += 1;
continue;
}
// not masked value, fixed char on mask
result += maskChar;
maskCharIndex += 1;
continue;
}
return result;
}
}
Now call it in your main dart file
var maskedController = MaskedTextController(mask: '(000) 000-0000');
TextField(
controller: maskedController,
style: Styles.textNormalStyle,
maxLines: 1,
),
This solution work for your this specific Question and scenario.
you can achieve using following code.
String formattedPhoneNumber = "(" + phoneNumber.substring(0,3) + ") " +
phoneNumber.substring(3,6) + "-" +phoneNumber.substring(6,phoneNumber.length);
Ricardo pointed to a great library but his answer is half right. Besides the intl_phone_number_input you need to get libphonenumber_plugin installed as well.
intl_phone_number_input: ^0.7.0+2
libphonenumber_plugin:
The method getRegionInfoFromPhoneNumber "discovers" what country the number is from eg +55... it would interpret as it's from Brasil and proceed to format the phone number accordingly. You can also explicitly tell from where the phone number is from passing the country's acronym into the method eg. await PhoneNumber.getRegionInfoFromPhoneNumber(phone, "US"); It'll disregard a country code if it doesn't fit the number you're entering.
String phone = "+19795555555";
PhoneNumber number =
await PhoneNumber.getRegionInfoFromPhoneNumber(phone);
String formattedNumber = await PhoneNumberUtil.formatAsYouType(
number.phoneNumber!,
number.isoCode!,
);
print(formattedNumber); // -> prints: '+1 979-555-5555'
Also you can use: https://pub.dev/packages/intl_phone_number_input/example
String phoneNumber = '+234 500 500 5005';
PhoneNumber number = await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber);
String parsableNumber = number.parseNumber();
`controller reference`.text = parsableNumber

How to store user sql where clause, and how to apply it on a select?

I am using JPA / Eclipselink / PostgreSQL within my application.
I have a model that list some data, and I would like to let the user of the application to create his own where clause parameters.
How can I store theses parameters ? as plain sql string ?
Then how can I apply the where clause ? as a simple string concatenation ? (I don't like this idea at all).
Bests regards.
Ok, so I solved my problem.
For information : I have created a recursive JSON representation of every where clause parameters possibility.
And I have created a query using criteria api by decoding the pojo structure from json.
The json class look like that :
public class JSonSearchCriteria
{
public static enum CriteriaType
{
asc,
desc,
count,
countDistinct,
and,
or,
not,
equal,
notEqual,
between,
gt,
ge,
lt,
le,
like,
notLike;
}
#Expose
public CriteriaType type;
#Expose
public List<JSonSearchCriteria> sub;
#Expose
public String what = null;
#Expose
public List<Integer> integerValue = null;
#Expose
public List<Long> longValue = null;
#Expose
public List<Boolean> booleanValue = null;
#Expose
public List<String> stringValue = null;
#Expose
public List<DateTime> datetimeValue = null;
public JSonSearchCriteria()
{
}
public JSonSearchCriteria(final CriteriaType type)
{
this.type = type;
}
public JSonSearchCriteria(final CriteriaType type, final String what)
{
this(type);
this.what = what;
}
public JSonSearchCriteria(final CriteriaType type, final String what, final String... values)
{
this(type, what);
for(final String value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Long... values)
{
this(type, what);
for(final Long value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Integer... values)
{
this(type, what);
for(final Integer value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final DateTime... values)
{
this(type, what);
for(final DateTime value : values)
{
value(value);
}
}
public void add(final JSonSearchCriteria subCriteria)
{
if(sub == null)
{
sub = new ArrayList<>();
}
sub.add(subCriteria);
}
public void value(final String value)
{
if(stringValue == null)
{
stringValue = new ArrayList<>();
}
stringValue.add(value);
}
public void value(final Long value)
{
if(longValue == null)
{
longValue = new ArrayList<>();
}
longValue.add(value);
}
public void value(final Integer value)
{
if(integerValue == null)
{
integerValue = new ArrayList<>();
}
integerValue.add(value);
}
public void value(final DateTime value)
{
if(datetimeValue == null)
{
datetimeValue = new ArrayList<>();
}
datetimeValue.add(value);
}
#SuppressWarnings(
{
"unchecked", "rawtypes"
})
#Transient
public Predicate buildPredicate(final CriteriaBuilder builder, final Root<Record> root, Join<Record, RecordInfo> infos)
{
switch(type)
{
case and:
case or:
final Predicate[] preds = new Predicate[sub.size()];
int cpt = 0;
for(final JSonSearchCriteria s : sub)
{
preds[cpt] = s.buildPredicate(builder, root, infos);
cpt++;
}
if(type == CriteriaType.and)
{
return builder.and(preds);
}
else if(type == CriteriaType.or)
{
return builder.or(preds);
}
break;
case equal:
case lt:
case gt:
case between:
final Path p;
if(what.startsWith("infos."))
{
p = infos.get(what.substring(6));
}
else
{
p = root.get(what);
}
if(stringValue != null && !stringValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, stringValue.get(0));
}
}
else if(longValue != null && !longValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, longValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, longValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, longValue.get(0));
}
}
else if(integerValue != null && !integerValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, integerValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, integerValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, integerValue.get(0));
}
}
else if(booleanValue != null && !booleanValue.isEmpty())
{
return builder.equal(p, booleanValue.get(0));
}
else if(datetimeValue != null && !datetimeValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, datetimeValue.get(0));
}
else if(type == CriteriaType.between && datetimeValue.size() > 1)
{
return builder.between(p, datetimeValue.get(0), datetimeValue.get(1));
}
}
break;
}
System.err.println(type + " - not implemented");
return null;
}
}
And it is used like that :
final SearchTemplate templ = DBHelper.get(SearchTemplate.class, 100);
final Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeJsonAdapter()).create();
final JSonSearchCriteria crits = gson.fromJson(templ.getTemplate(), JSonSearchCriteria.class);
final CriteriaBuilder critBuilder = DBHelper.getInstance().em().getCriteriaBuilder();
final CriteriaQuery<Record> critQuery = critBuilder.createQuery(Record.class);
final Root<Record> root = critQuery.from(Record.class);
final Join<Record, RecordInfo> infos = root.join("infos");
critQuery.where(crits.buildPredicate(critBuilder, root, infos));
final TypedQuery<Record> query = DBHelper.getInstance().em().createQuery(critQuery);
final List<Record> result = query.getResultList();
for(final Record rec : result)
{
System.err.println(rec.toString());
}