3

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You probably intend e.toString() == value. If you use contains, then '123' would be "found" in [1234].
I thought so, but Error: The method 'contains' isn't defined for the class 'int'.
Huh? I'm telling you to not use contains.
So I made sure every single value in that list and list itself is a string. Also made sure the value I am searching for inside the list is also a string.
Finally found the issue, Thanks to all who helped figure it out.
1

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
}

3 Comments

I checked the runtimetype, it says contacts is a dynamic list and those values are pulled in from an api call.
If you make sure it is a List of String using type cast, or just use toString() or "$value" to turn them to String before use contacts
Yes I made it a list of strings, now I see the runtimetype as String. Still I haven't been able to make it work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.