How to get value inside list without index? - flutter

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!

Related

Dart find string value in a list using contains

I have a list of numbers like below -
List contacts = [14169877890, 17781231234, 14161231234];
Now I want to find if one of the above list element would contain the below string value -
String value = '4169877890';
I have used list.any to do the search, but the below print statement inside the if condition is not printing anything.
if (contacts.any((e) => e.contains(value))) {
print(contacts[0]);
}
I am expecting it to print out the first element of the contacts list as it partially contains the string value.
What is it I am doing wrong here?
contacts isn't a List<String>, so your any search can't be true, you need turn element of contracts to string to able to use contains.
void main() {
var contacts = [14169877890, 17781231234, 14161231234];
print(contacts.runtimeType);
var value = '4169877890';
print(value.runtimeType);
var haveAnyValid = contacts.any((element) {
return "$element".contains(value);
});
print(haveAnyValid);
// result
// JSArray<int>
// String
// true
}
Not sure if contacts is an integer and value is a string on purpose or mistake, but this works in dart pad if you convert it to string:
if (contacts.any((e) => e.toString().contains(value))) {
print(contacts[0]);
}
DartPad Link.

How to Call Dynamic Variable on Flutter

I have the following code
List toCheck = ['province','regency','district','village'];
List data = [];
toCheck.forEach((value) {
//sample data would looke like (object.province)
if(object.value!=null){ => need to call with object.value
data.add(value);
}
});
If it is in php, that would be look like ${$value}
Try this:
ElevatedButton(onPressed: (){
List toCheck = ['province','regency','district','village'];
List data = [];
toCheck.forEach((value) {
//sample data would looke like (object.province)
if(value!=null){
data.add(value);
}
});
If I understand what you want correctly, this should check if the values of your list are not null, and if so, it will add each value to the data list.

Flutter : How to Map values dynmically into list and iterate to its length and how can i do Update and Delete after maping values

I am trying to build json expected output as below through dart programing for my application, I have mapped data to list successfully. But when I trying to delete / add the list, the elements in the list are not getting updated accordingly instead they are hgetting reapeted same data.
Here is my code implimentation
in this set state i am getting required values like Phone, name, email e.t.c
for (int i = 0; i <= selectedContacts.length - 1; i++) {
SimplifiedContact? contact = selectedContacts.elementAt(i);
CreateContestModel(//<-- from here i am getting required values.
contact.phone,
contact.name,
contact.email,
);
}
in below code i am, mapping data and building json
class CreateContestModel {
static List models = [];
String phone = '';
String name = '';
String email;
CreateContestModel(this.phone, this.name, this.email) {
var invitemap = {
'name': name,
'phone': phone,
'email': email,
};
models.add(invitemap);
print(models);
}
}
Output
{
"invitations":[
{
"name":"Acevedo Castro",
"phone":982-475-2009,
"email":"floresjoyner#digifad.com"
},
{
"name":"Acevedo Castro",
"phone":982-475-2009,
"email":"floresjoyner#digifad.com"
},
{
"name":"Abby Webster",
"phone":888-561-2141,
"email":"howardnoel#perkle.com"
},
{
"name":"Abby Webster",
"phone":888-561-2141,
"email":"howardnoel#perkle.com"
},
{
"name":"Abby Webster",
"phone":888-561-2141,
"email":"howardnoel#perkle.com"
}
]
}
As you see above items are not getting updated, but they are getting added more.
Expected Output
{
"invitations":[
{
"name":"Acevedo Castro",
"phone":"982-475-2009",
"email":"floresjoyner#digifad.com"
},
{
"name":"Abby Webster",
"phone":"888-561-2141",
"email":"howardnoel#perkle.com"
}
]
}
That is some seriously flawed program flow. Your object creation as a side effect at the same time fills a static list. And it seems you call your object creation every build. So you would insert into your list whenver the user flips it's phone or drags his browser window.
I'm not entirely sure what you want, but you need state management in your application. There are different ways to do it, you can pick the one you like best from the Flutter documentation on state management.
This is a huge flow issue, You should never do data manipulation in build() function as in flutter build function is called multiple times so the manipulation code will also get called multiple times.
So, the proper way to manipulate data is before the data is being used so make sure that the data is only manipulated in initstate(). In Your case you are also doing something which is not required. You are trying to add data to a list via a constructor to a static list so it will always add the data whenever you call it, This is not a proper way.
class CreateContestModel {
late String phone = '';
late String name = '';
late String email;
CreateContestModel.fromMap(Map<String, String> json) {
phone = json['phone'] ?? '';
phone = json['name'] ?? '';
phone = json['email'] ?? '';
}
}
This is how you should create your class. And always create functions for manipulation if possible.
List<CreateContestModel> createContestModelList =
testData['invitations']!.map(
(data) {
return CreateContestModel.fromMap(data);
},
).toList();
Then use this code to construct your list in initstate() and manipulate this having a static variable in your stateful widget. Make Sure you do not construct the data on build() function.
Need More Help?? here's the Gist link
As per my question i find some work around, i.e., by clear up stack on selecting or updtaing existing contacts because as explained below
in this for loop i am itrating same values on each time, when i hit on submit button
for (int i = 0; i <= selectedContacts.length - 1; i++) { //<--- for every time same elements will be itrated
SimplifiedContact? contact = selectedContacts.elementAt(i);
CreateContestModel(//<-- from here i am getting required values.
contact.phone,
contact.name,
contact.email,
);
}
so the list of sets are not updating as per the displayed list as mentioned in question, so i done some work around in below code while selecting / updating contacts, because my model is static list
void onContactBtnPress(BuildContext context) async { CreateContestModel.models.clear(); //<-- clearing up stack
}

Filter list with whereIn condition in Flutter?

This code sample works fine.
var box = await Hive.openBox<MainWords>('mainWords');
box.values.where((item) {
return item.category == "6" || item.category == '13';
}).toList();
I am trying to filter a list with whereIn condition but it must filter like
List<String> categoryList = ['6', '13'];
var box = await Hive.openBox<MainWords>('mainWords');
box.values.where((item) {
return item in categoryList; // just an examle
}).toList();
How can i achive this?
You should not use the keyword in but the method contains to check if your item exists inside categoryList. Moreover you cannot compare values of different types, I'm seeing that you are returning with box.values an Iterable<MainWords>.
I don't know the content of this class but the item variable is of type MainWords and so it cannot be compared with a String object directly.
I am supposing that you have some access to a String value from your class MainWords so you will need to compare this value with your list.
Code Sample
List<String> categoryList = ['6', '13'];
var box = await Hive.openBox<MainWords>('mainWords');
// As I don't know what are MainWords' properties I named it stringValue.
box.values.where((item) => categoryList.contains(item.stringValue)).toList();

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.