I have a futurebuilder that builds the UI based on a List, it does the job, however I get duplicates due to the UI being built again and again whenever I navigate. My question is, is there a innate method in Dart that can remove duplicates from a list? I've tried this StackOverflow question however it doesn't work.
Here is my custom model:
class HomeList {
Widget navigateScreen;
String imagePath;
PatientInfo patientInfo;
HomeList({
this.navigateScreen,
this.imagePath = '',
this.patientInfo,
});
static List<HomeList> homeList = [];
}
Here is my function for the futureBuilder i'm getting the data from my cloud_firestore:
_getPatients() async {
if (didLoadpatients == 0) {
print('this is didloadpatients at start of func $didLoadpatients');
var document = await db
.collection('users')
.document(mUser.uid)
.collection('patients');
document.getDocuments().then((QuerySnapshot query) async {
query.documents.forEach((f) {
uids.add(f.data['uID']);
});
didLoadpatients++;
print('this is didloadpatients at end of func $didLoadpatients');
for (var i = 0; i < uids.length; i++) {
var userDocuments = await db.collection('users').document(uids[i]);
userDocuments.get().then((DocumentSnapshot doc) {
print(doc.data);
homeList.add(HomeList(
imagePath: 'assets/fitness_app/fitness_app.png',
patientInfo: new PatientInfo.fromFbase(doc.data)));
});
print(homeList);
}
});
} else
print('I am leaving the get patient function');
}
Future<bool> getData() async {
_getCurrentUser();
await Future.delayed(const Duration(milliseconds: 1500), () async {
_getPatients();
});
return true;
}
Any help would be appreciated thank you!
To remove duplicates you can use Set Data Structure instead of List.
Just use Set instead of List to get unique values only.
Before Adding you can Remove Element from model this will Work
dummymodel.removeWhere((m) => m.id == id);
dummymodel.add(dummymodel.fromJson(data));
To Remove Duplicates from Data Model simply use Set (Data structure),
Original List with Duplicate Entries:
List<MyDataModel> mList = [MyDataModel(1), MyDataModel(2), MyDataModel(1), MyDataModel(3)];
New List that removes duplicate Entries from your List<MyDataModel>:
List<MyDataModel> mNewList = list.toSet().toList();
Output:
The result will be like
MyDataModel(1), MyDataModel(2), MyDataModel(3)
To remove the duplicate elements from custom object list, you need to override == and hashcode methods in your POJO class and then add the items in Set and again convert set to list to remove duplicate objects. Below is the working code:-
class TrackPointList {
double latitude;
double longitude;
String eventName;
Time timeZone;
TrackPointList({
this.latitude,
this.longitude,
this.eventName,
this.timeZone,
});
#override
bool operator==(other) {
// Dart ensures that operator== isn't called with null
// if(other == null) {
// return false;
// }
if(other is! TrackPointList) {
return false;
}
// ignore: test_types_in_equals
return eventName == (other as TrackPointList).eventName;
}
int _hashCode;
#override
int get hashCode {
if(_hashCode == null) {
_hashCode = eventName.hashCode;
}
return _hashCode;
}
factory TrackPointList.fromJson(Map<String, dynamic> json) => TrackPointList(
latitude: json["latitude"].toDouble(),
longitude: json["longitude"].toDouble(),
eventName: json["eventName"],
timeZone: timeValues.map[json["timeZone"]],
);
Map<String, dynamic> toJson() => {
"latitude": latitude,
"longitude": longitude,
"eventName": eventName,
"timeZone": timeValues.reverse[timeZone],
};
}
Above is the POJO class. Now below is the method which helps you to filter the objects according to the eventName data member.
List<TrackPointList> getFilteredList(List<TrackPointList> list){
final existing = Set<TrackPointList>();
final unique = list
.where((trackingPoint) => existing.add(trackingPoint))
.toList();
return unique;
}
This will work definitely.
Please +1 if it helps you.
I've come up with quite a brute force solution. Instead of
_getPatients() async {
if (didLoadpatients == 0) {
print('this is didloadpatients at start of func $didLoadpatients');
var document = await db
.collection('users')
.document(mUser.uid)
.collection('patients');
document.getDocuments().then((QuerySnapshot query) async {
query.documents.forEach((f) {
uids.add(f.data['uID']);
});
didLoadpatients++;
print('this is didloadpatients at end of func $didLoadpatients');
for (var i = 0; i < uids.length; i++) {
var userDocuments = await db.collection('users').document(uids[i]);
userDocuments.get().then((DocumentSnapshot doc) {
print(doc.data);
homeList.add(HomeList(
imagePath: 'assets/fitness_app/fitness_app.png',
patientInfo: new PatientInfo.fromFbase(doc.data)));
});
print(homeList);
}
});
} else
print('I am leaving the get patient function');
}
I've done what #Jay Mungara says and clear my Set everytime my UI rebuilds:
_getPatients() async {
homeList.clear();
if (didLoadpatients == 0) {
print('this is didloadpatients at start of func $didLoadpatients');
var document = await db
.collection('users')
.document(mUser.uid)
.collection('patients');
document.getDocuments().then((QuerySnapshot query) async {
query.documents.forEach((f) {
uids.add(f.data['uID']);
});
didLoadpatients++;
print('this is didloadpatients at end of func $didLoadpatients');
for (var i = 0; i < uids.length; i++) {
var userDocuments = await db.collection('users').document(uids[i]);
userDocuments.get().then((DocumentSnapshot doc) {
print(doc.data);
homeList.add(HomeList(
imagePath: 'assets/fitness_app/fitness_app.png',
patientInfo: new PatientInfo.fromFbase(doc.data)));
});
print(homeList);
}
});
} else
print('I am leaving the get patient function');
}
Thank you for all your answers!
this is a small examples to remove duplicate element
removeDuplicate() {
List<dynamic> demoList = [
{"userId": 1, "id": 1, "name": "thappu1"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 1, "id": 1, "name": "thappu1"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 2, "id": 2, "name": "appu"},
];
var toRemove = {};
demoList.forEach((e) {
toRemove.putIfAbsent("$e", () => e);
});
print(toRemove.keys.toList());
}
output is
[{userId: 1, id: 1, name: thappu1}, {userId: 2, id: 2, name: appu}]
Related
I would like to use a where clause in my Firestore query, with a list in parameter.
I used a for loop to do this but when I want to add all my values in a variable, I have some problems with the add function (variable type problem).
I understand the problem but I don't what is the way I have to take to do this in another way ...
Can anyone help me?
Best regards :) ###It's my first question on stack! :D ###
in my main class:
var games = [
"uno",
"poker",
];
return StreamProvider<List<AppUserData>>.value(
initialData: [],
value: DatabaseService().users4(games),
child: Scaffold(....
in my database class
List<AppUserData> _list = [];
void addToList(AppUserData value) {
_list.add(value);
}
Stream<List<AppUserData>> users4 (List games) {
print(games);
var b;
var len = games.length;
for (var i = 0; i < len + 1; i++) {
b = FirebaseFirestore.instance.collection("users")
.where("games", isEqualTo: games[i]).snapshots().map(
_userListFromSnapshot);
print("$b");
addToList(b);
}
return b;
}
List<AppUserData> _userListFromSnapshot(
QuerySnapshot<Map<String, dynamic>> snapshot) {
return snapshot.docs.map((doc) {
return _userFromSnapshot(doc);
}).toList();
}
AppUserData _userFromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot) {
var data = snapshot.data();
if (data == null) throw Exception("user not found");
return AppUserData(
uid: uid,
name: snapshot.data()['name'],
distance: snapshot.data()['distance'],
games: snapshot.data()['games'],
id: snapshot.data()['id'],
);
}
I think you're looking for whereIn
Try this:
Stream<List<AppUserData>> users4(List games) async* {
yield* FirebaseFirestore.instance
.collection("users")
.where("games", whereIn: games)
.snapshots()
.map((e) {
List<AppUserData> l =
e.docs.map((e) => _userFromMap(Map.from(e.data()))).toList();
return l;
});
}
AppUserData _userFromMap(Map<String, dynamic> map) {
if (map == null) throw Exception("user not found");
return AppUserData(
uid: uid,
name: map['name'],
distance: map['distance'],
games: map['games'],
id: map['id'],
);
}
I am having trouble removing an item in a list after adding the element.
List<CartItem> _items = [];
FirebaseFirestore? _instance;
void add(BuildContext context, CartItem item) {
_items.add(item);
AuthService authService = Provider.of<AuthService>(context, listen: false);
Map<String, dynamic> cartMap = Map();
_items.forEach((CartItem item) {
cartMap['title'] = (item.product as Product).title;
cartMap['name'] = (item.product as Product).name;
});
_instance = FirebaseFirestore.instance;
_instance!
.collection('cart')
.doc(authService.getCurrentUser()) //need to get logged in account's id
.update({
'cartProduct': FieldValue.arrayUnion([cartMap])
}).then((value) {
print(_items.length);
notifyListeners();
});
}
void remove(BuildContext context, CartItem item) {
_items.remove(item);
AuthService authService = Provider.of<AuthService>(context, listen: false);
Map<String, dynamic> cartMap = Map();
cartMap['title'] = (item.product as Product).title;
cartMap['name'] = (item.product as Product).name;
_instance = FirebaseFirestore.instance;
_instance!.collection('cart').doc(authService.getCurrentUser()).update({
'cartProduct': FieldValue.arrayRemove([cartMap]),
}).then((value) {
print(_items.length);
notifyListeners();
});
}
After I do add(context, widget.product) and print _items.length, the result is 1
However, after I do remove(context, widget.product) and print _items.length, the result is still 1.
Consumer<CartService>(
builder: (context, cart, child) {
Widget renderedButton;
if (cart.isProductAddedToCart(widget.product) == false) {
renderedButton = DefaultButton(
text: "Participate",
press: () {
print(cart.isProductAddedToCart(widget.product));
cartService.add(context, CartItem(product: widget.product));
print(cart.isProductAddedToCart(widget.product));
},
);
} else {
renderedButton = DefaultButton(
text: "Delete",
press: () {
print(cart.isProductAddedToCart(widget.product));
cartService.remove(
context, CartItem(product: widget.product));
print(cart.isProductAddedToCart(widget.product));
},
);
}
return renderedButton;
As in the code above, the remove() method is supposed to remove the same item that was added to the list using the add() method.
Just update the remove() to: (only change _items.remove(item); position)
void remove(BuildContext context, CartItem item) {
AuthService authService = Provider.of<AuthService>(context, listen: false);
Map<String, dynamic> cartMap = Map();
cartMap['title'] = (item.product as Product).title;
cartMap['name'] = (item.product as Product).name;
_instance = FirebaseFirestore.instance;
_instance!.collection('cart').doc(authService.getCurrentUser()).update({
'cartProduct': FieldValue.arrayRemove([cartMap]),
}).then((value) {
/// todo check firebase collection's deletion success first
_items.remove(item);
print(_items.length);
notifyListeners();
});
}
The item you're adding to the list may not be the same instance of the item you're removing. Make sure the item object/class have equality and hashcode implementation to compare the two items properly.
If you don't have control over the object, the following approach can be an easier alternative:
_items.removeWhere((_item) => _item.property == item.property);
^ where property can be the id of the product.
I'm populating cities name from SQLite database and trying to display as a drop down list. I make it work by following a tutorial, but having a small issue. The selected value is not displayed in dropdown, it keep displaying default hint value. However, I was able to assign and retrieve correct selected value.
Here is my code:
cities.dart
class Cities {
int id;
String name;
Cities(this.id, this.name);
Cities.fromMap(Map<String, dynamic> json) {
this.id = json["id"];
this.name = json["name"];
}
Map<String, dynamic> toMap() => {
'id': null,
'name': name,
};
}
Function that retrieve and returns value from db:
Future<List<Cities>> getCitiesList() async {
Database db = await instance.database;
final citiesData = await db.query('cities');
if (citiesData.length == 0) return null;
List<Cities> citiesList = citiesData.map((item) {
return Cities.fromMap(item);
}).toList();
return citiesList;
}
The code which builds drop down, inside Widget build:
//these are defined above in the code
Cities _city;
final databaseHelper = DatabaseHelper.instance;
FutureBuilder<List<Cities>>(
future: databaseHelper.getCitiesList(),
builder: (BuildContext context, AsyncSnapshot<List<Cities>> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return DropdownButton<Cities>(
items: snapshot.data
.map((city) => DropdownMenuItem<Cities>(
child: Text(city.name),
value: city,
))
.toList(),
onChanged: (Cities value) {
setState(() {
_city = value;
});
},
isExpanded: true,
// value: _city, //uncommenting this line breaks the layout
hint: Text('Select City'),
);
},
),
Error in the console:
'package:flutter/src/material/dropdown.dart': Failed assertion: line 620 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.
Un-commenting this value: _city, add same error in display (displays error 8 times, instead of dropdown list).
Questions:
How can I fix this issue?
How can I set default value from the list? (which will be selected by default)
You can do it in simple way, just create a simple list of strings and pass that list to dropdown menu.
Here's how:
Update your getCitiesList() function:
Future<List<String>> getCitiesList() async {
Database db = await instance.database;
final citiesData = await db.query(tblCities);
if (citiesData.length == 0) return null;
return citiesData.map((Map<String, dynamic> row) {
return row["name"] as String;
}).toList();
}
Add this inside your form page:
//initialize these at top
List<String> _citiesList = <String>[];
String _city;
void _getCitiesList() async {
final List<String> _list = await databaseHelper.getCitiesList();
setState(() {
_citiesList = _list;
});
}
Call _getCitiesList(); inside initState().
Add this inside your build method:
DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: _city,
items: _citiesList.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
_city = newValue;
});
},
)),
In Vtiger 6.5.0 open source, I wants to create a alert function to warn users that the conact's mobile is existing? could you please help me. I'm fresher.
Thanks,
Loi
You can refer the function wich exist in Account module for checking Duplicate Account Name.
Please follow this files you will get an idea.
This is the code flow how its done In Account Module
Registring Pre Save Event
http://code.vtiger.com/vtiger/vtigercrm/blob/master/layouts/vlayout/modules/Accounts/resources/Edit.js#L250
This teh Fucntion to check Duplicate in cache, If not calls the Helper function
http://code.vtiger.com/vtiger/vtigercrm/blob/master/layouts/vlayout/modules/Accounts/resources/Edit.js#L83
This the Helper function which makes the call to server
http://code.vtiger.com/vtiger/vtigercrm/blob/master/resources/helper.js#L166
This is the action function which is responsible for Serving the request which came from Helper Function
http://code.vtiger.com/vtiger/vtigercrm/blob/master/modules/Accounts/actions/CheckDuplicate.php#L30
And this is the function which checks for Duplicate
http://code.vtiger.com/vtiger/vtigercrm/blob/master/modules/Accounts/models/Record.php#L57
Hope this helps.
Hi Victor please follow this steps
modules\Leads\actions\Checkprimaryemail.php
<?php
class Leads_Checkprimaryemail_Action extends Vtiger_BasicAjax_Action {
public function checkPermission(Vtiger_Request $request) {
return;
}
public function process(Vtiger_Request $request) {
global $adb;
$moduleName = $request->get('module');
$recordId = $request->get('recordId');
$primary_email = $request->get('primary_email');
/*Lead Details*/
$lead_query = "select * from vtiger_leaddetails
inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid
where vtiger_crmentity.deleted = 0 and vtiger_leaddetails.email='".$primary_email."'";
$lead_result = $adb->query($lead_query);
$lead_email = $adb->query_result($lead_result,0,'email');
$lead_numrows = $adb->num_rows($lead_result);
/*Contact Details*/
$cont_query = "select * from vtiger_contactdetails
inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid
where vtiger_crmentity.deleted = 0 and vtiger_contactdetails.email='".$primary_email."'";
$cont_result = $adb->query($cont_query);
$cont_email = $adb->query_result($cont_result,0,'email');
$cont_numrows = $adb->num_rows($cont_result);
if($recordId != '' ){
if($primary_email == $lead_email && $lead_numrows == 1 ){
$emailtrue = 0;
} elseif($primary_email == $cont_email && $cont_numrows >= 1 ) {
$emailtrue = 1;
}
} else {
if(($lead_numrows >=1 || $cont_numrows >=1 ) || ($lead_numrows >=1 && $cont_numrows >= 1) ){
$emailtrue = 1;
} else {
$emailtrue = 0;
}
}
$emailData = array($emailtrue);
$response = new Vtiger_Response();
$response->setResult($emailData);
$response->emit();
}
}
?>
After Create One other file
layouts\vlayout\modules\Leads\resources\Edit.js
Vtiger_Edit_Js("Leads_Edit_Js", {
}, {
changeEvent: function (container) {
jQuery('input[name="email"]').on('focusout', function (e) {
var email = jQuery('input[name="email"]').val();
var recordId = jQuery('input[name="record"]').val();
var email_length = email.length;
if (email != '') {
if (email_length > 100) {
var errorMessage = app.vtranslate('JS_EMAIL_LENGTH_VALIDATION');
params = {
text: errorMessage,
'type': 'error',
};
Vtiger_Helper_Js.showMessage(params);
}
var progressIndicatorElement = jQuery.progressIndicator({
'position': 'html',
'blockInfo': {
'enabled': true
}
});
var postData = {
"module": 'Leads',
"action": "Checkprimaryemail",
"primary_email": email,
"recordId": recordId
}
AppConnector.request(postData).then(
function (data) {
progressIndicatorElement.progressIndicator({'mode': 'hide'});
if (data['result'] == 1) {
jQuery('#emailalready_exists').val(1);
var errorMessage = app.vtranslate('JS_EMAIL_EXIST');
params = {
text: errorMessage,
'type': 'error',
};
Vtiger_Helper_Js.showMessage(params);
} else {
jQuery('#emailalready_exists').val(0);
}
},
function (error, err) {}
);
e.preventDefault();
}
});
},
registerBasicEvents: function (container) {
this._super(container);
this.changeEvent(container);
}
});
To check duplicate records in vTiger follow below steps:
Register checkDuplicate function in registerBasicEvents
1: \layouts\vlayout\modules\Contacts\resources\Edit.js
getmobile : function(container){
return jQuery('input[name="mobile"]',container).val();
},
getRecordId : function(container){
return jQuery('input[name="record"]',container).val();
},
DuplicateCheck : function(form) {
var thisInstance = this;
if(typeof form == 'undefined') {
form = this.getForm();
}
jQuery( "#mobileFieldId" ).change(function() {
var mobile = thisInstance.getmobile(form);
var recordId = thisInstance.getRecordId(form);
var params = {
'module' : "Contacts",
'action' : "CheckDuplicate",
'mobile' : mobile,
'record' : recordId
}
AppConnector.request(params).then(
function(data) {
var response = data['result'];
var result = response['success'];
if(result == true) {
var message_params = {
title : app.vtranslate('JS_MESSAGE'),
text: response['message'],
animation: 'show',
type: 'error'
};
Vtiger_Helper_Js.showPnotify(message_params);
jQuery(".btn-success").attr('disabled',true);
return false;
} else {
jQuery(".btn-success").attr('disabled',false);
}
}
);
});
},
2: Create new file in** \modules\Contacts\actions\CheckDuplicate.php
Follow the same process / code as given in \modules\Accounts\actions\CheckDuplicate.php
3: Add new function checkDuplicate() in \modules\Contacts\models\Record.php
And follow same process as given in \modules\Accounts\models\Record.php having function checkDuplicate()
Note: Don't forget to change the db table name, class name module wise.
Hope this will help you. Thank you.
I have two models. Company and Booking.
In the relation part of model Company
"bookings": {
"type": "hasMany",
"model": "Booking",
"foreignKey": "companyId"
}
The issue is, it is possible to post a Booking without companyId which is not ok.
From the explorer.
Booking {
bookingId (string, optional),
name (string),
location (string),
companyId (string, optional)
}
You actually can't enforce this particular validation out-of-the-box. Instead you have a couple different options:
a) You can enforce the creation of Booking through company through the endpoint, POST /api/Company/{id}/Bookings by disabling Booking.disableRemoteMethod('create', ...) along with any other methods that have the ability to create records from the Booking model.
b) You can add a remote hook to check whether or not the company record exists and throw an error accordingly.
Booking.beforeRemote('create', function(ctx, booking, next) {
var Company = Booking.app.models.Company;
var companyId = ctx.req.body.companyId;
if (companyId) {
errorMsg = 'Company with id=' + companyId + ' does not exist.';
var noCompany = new Error(errorMsg);
Company.findById(companyId, function(err, company) {
if (err) next(err);
if (!company) {
ctx.res.statusCode = 400;
next(noCompany);
} else {
next();
}
});
} else {
next();
}
});
You will also have to do the same thing for any other endpoints that allow record create such as PUT /api/Bookings.
Hope that helps!
You can add the companyId property explicitly in the booking.json file, and add the required:true property. It would look like
{
"properties": {
"companyId": {
"type": "number",
"required": true
},
... //other properties
}
}
In richardpringle's answer part b booking was an empty object for me.
I was able to get this answer to work by adding app to the booking.js file like below:
'use strict';
var app = require('../../server/server');
module.exports = function(Booking) {
Booking.beforeRemote('create', function(ctx, booking, next) {
var Company = app.models.Company;
var companyId = ctx.req.body.companyId;
if (companyId) {
errorMsg = 'Company with id=' + companyId + ' does not exist.';
var noCompany = new Error(errorMsg);
Company.findById(companyId, function(err, company) {
if (err) next(err);
if (!company) {
ctx.res.statusCode = 400;
next(noCompany);
} else {
next();
}
});
} else {
next();
}
});
};
line 2 is new
line 6 is modified from richardpringle's answer
From: var Company = Booking.app.models.Company;
To: var Company = app.models.Company;