Change item in a List - flutter

I'm fetching data from an API that contains details of some person with their job. That could happen that one person has more than one job.
In this case, I don't want to add this person to a list but I want to append the current job title to the existing one.
Here is the snippet of the code:
if (workers.any((item) => item.id == person.id)) {
//here I want to append the job title.
} else {
workers.add(coWorker);
}

Maybe you can do something like this:
if (workers.any((item) => item.id == person.id)) {
final worker = workers.firstWhere((item) => item.id == person.id);
worker.jobTitle += 'appended text to jobTitle if that is a string';
} else {
workers.add(coWorker);
}

Related

Update a BuiltList from built_value

I want to update the BuiltList in the state if some condition is met. Here is my reducer
TravelDeductionsStateBuilder _travelDeductionBreakfastToggled(
TravelDeductionsStateBuilder state,
TravelDeductionBreakfastToggledAction action) =>
state
..days = state.days.build().rebuild((d) {
if (d[action.key].deductions.contains(TravelDeductionType.BREAKFAST)) {
d[action.key]
.deductions
.rebuild((p0) => p0.remove(TravelDeductionType.BREAKFAST));
} else {
d[action.key]
.deductions
.rebuild((p0) => p0.add(TravelDeductionType.BREAKFAST));
}
}).toBuilder();
I need to add/remove ENUM entry into deductions but it seems that this update is ignored and I am not able to update this list accordingly. Any tips of what may be wrong?
If anyone wonders this is the solution
TravelDeductionsStateBuilder _travelDeductionBreakfastToggled(
TravelDeductionsStateBuilder state,
TravelDeductionBreakfastToggledAction action) =>
state
..days = state.days.build().rebuild((d) {
if (d[action.index]
.deductions
.contains(TravelDeductionType.BREAKFAST)) {
d[action.index] = d[action.index].rebuild(
(b) => b.deductions.remove(TravelDeductionType.BREAKFAST));
} else {
d[action.index] = d[action.index]
.rebuild((b) => b.deductions.add(TravelDeductionType.BREAKFAST));
}
}).toBuilder();
You can find the explanation here https://github.com/google/built_collection.dart/issues/259#issuecomment-1122390601

How to get value inside list without index?

I am creating an app using flutter and dart.
I have a list of objects with the name parameter, and I want to check if the user input is equal to any of the names of objects inside list.
Simply
I want to take input from a user and switch if one of the objects inside a list has this value to add it in a list
I have searched a lot but with nothing.
void main() {
Data data = Data();
String name = 'Messi';
//I want to switch if name equals any name inside players list without index
}
class Data {
List<Player> players = [
Player(
name: 'Messi',
),
Player(
name: 'Mohamed',
),
];
}
If you want to get a filtered list from the list you have, you can do this:
players.where((player) => player.name == userInput).toList();
If you just want the first occurrence, you can do this:
players.firstWhere((player) => player.name == userInput);
You can use the method forEach from the lists.
It basically works like this:
players.forEach ((player) {
if(player.name == name){
your code...
}
});
Hope this helps!

Search data in Observable

I'd like to have a search input, that display the result on keypress.
At the moment, this is what I have :
mylist: Observable<MyData[]>;
term = new FormControl();
ngOnInit() {
this.mylist = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.searchData(term));
}
searchData(valueToSearch:string){
if(valueToSearch == ''){
this.channels = MyData.find();
}
return MyData.find({'title':new RegExp(valueToSearch)});
}
It works quite well, but I have trouble to initialize "mylist", and I think my method isn't performant at all.
Basically, I want when my component is initialize, that:
this.mylist = MyData.find();
And on keypress, I want my search to be done on this.mylist, to avoid doing too much request.
Is it possible ?
I hope I'm clear.
Thanks by advance guys.
You must subscribe to the mapped data. Modify to the below code
this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.searchData(term))
.subscribe((result) => {
this.mylist = result
});;
#Julia is correct , modify your searchData() function as below
searchData(valueToSearch:string):Observable<any> {
if(valueToSearch == ''){
this.channels = MyData.find();
}
return <Observable<any>>MyData.find({'title':new RegExp(valueToSearch)});
}

declare variable to store linq entity for conditional statements

I am trying to look up record using if I have the key then use Find if not use Where
private ApplicationDbContext db = new ApplicationDbContext();
public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "")
{
var prices = db.BeveragePrices;
// if we have an id then find
if (priceId != 0)
{
prices = prices.Find(priceId);
}
else
{
prices = prices.Where(b => b.UserCreated == sponsorUserName);
}
if (prices != null)
{
// do something
}
return true;
I get the following error for
prices = prices.Find(priceId);
Cannot convert app.Model.BeveragePrices from system.data.entity.dbset
I am copying the pattern from this answer but something must be different.
Seems you forgot to put a predicate inside the Find function call. Also you need to do ToList on the collection. The second option is a lot more efficient. The first one gets the whole collection before selection.
Another note commented by #Alla is that the find returns a single element. So I assume another declaration had been made for 'price' in the first option I state down here.
price = prices.ToList.Find(b => b.PriceId == priceId);
Or
prices = prices.Select(b => b.PriceId == priceId);
I assume the field name is PriceId.

Is that possible to generate unique Id for list item across site collection?

Ex: I have 10 sites and every site have 5 list. From site 1 i have adding one item in listX now id will be like "1" and creating another item in listB of 4th sub site so now id will "2"... So it has to go on like this how to achieve this?
I need to update this with all list item added event ? also how to get the latest id?
I have tried this code with custom forms it's work's cool, but thinking this may give concurrency issue
public static void ID()
{
if ((field.InternalName.Equals("Field1")))
{
{
string template;
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.RootWeb)
{
template = web.Properties["eydtemplate"].ToString();
}
}
if ("eydadvisory" == template)
{
SPListItemCollection items = _currentList.Items;
if (_currentList.ItemCount == 0)
{
webControl.Field.DefaultValue = (1).ToString();
}
else
{
SPQuery query = new SPQuery();
query.RowLimit = 1;
query.Query = " <OrderBy><FieldRef Name='" + field.InternalName + "' Ascending='FALSE' /></OrderBy>";
webControl.Field.DefaultValue = (Convert.ToInt64(_currentList.GetItems(query).Cast<SPListItem>().FirstOrDefault()[field.InternalName]) + 1).ToString();
}
}
}