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.
Related
The following code will give the current user whose role is Meet.
_currentUser["role"] == "Meet"
But in reality, I'd like to get the current user whose role is prefixed with Meet.
eg.MeetAdmin, MeetPec, like that.
Please help me how do I do that.
You can create an extension on String:
extension StringExtension on String {
bool hasPrefix(String prefix) {
return substring(0, prefix.length) == prefix;
}
}
void main() {
final role = 'MeetPec';
final invalidRole = 'PecMeet';
print(role.hasPrefix('Meet')); // returns true
print(invalidRole.hasPrefix('Meet')); // returns false
}
It assumes case-sensitive check, but you can tweak it to also support case-insensitive by adding .toLowerCase() to both prefix and the string itself.
EDIT:
As pointed out in the comments, we already have a startsWith method, this is definitely a way to go here:
void main() {
final role = 'MeetPec';
final invalidRole = 'PecMeet';
print(role.startsWith('Meet')); // returns true
print(invalidRole.startsWith('Meet')); // returns false
}
Okay, if I understand your question property, you want to check if the current user role has the word "meet" in it.
If that's the case your can use contains to check if the role contains role
Example
if(_currentUser["role"].contains("meet") ) {
//It contains meet
}else{
//It does not contain meet
}
check this method it might help you. whenever you want to check or search you should convert string to lower case to compare then check
bool getCurrentUserWithMeet() {
Map<String, String> _currentUser = {
'role': 'MeetAdmin',
};
final isCurrentUserContainsMeet =
_currentUser['role']?.toLowerCase().contains('meet');
return isCurrentUserContainsMeet ?? false;
}
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();
List listFinal = [];
So listFinal have values from multiple list inside like below.
[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]]
How do I make this list so that it only extract numbers and separate with comma?
End result should be like
[1113335555, 2223334555, 5553332222]
I can think of trimming or regexp but not sure how to pull this off.
many thanks.
Try this
void main() {
List<String> numberList=[];
List<List<dynamic>> demoList=[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]];
for(int i=0;i<demoList.length;i++){
numberList.addAll(demoList[i].map((e) => e.toString().split(":")[1].replaceAll("-", "")).toList());
}
print(numberList.toString());
}
Here is an example to get you started. This doesn't handle things like malformed input strings. First step is to "flatten" the list with .expand, and then for each element of the flattened iterable use a regex to extract the substring. Other options might include using .substring to extract exactly the last 12 characters of the String.
You can see this in action on dartpad.
void main() {
final input = [
['test: 111-333-5555', 'test2: 222-333-4555'],
['test3: 555-333-2222']
];
final flattened = input.expand((e) => e); // un-nest the lists
// call extractNumber on each element of the flattened iterable,
// then collect to a list
final result = flattened.map(extractNumber).toList();
print(result);
}
final _numberRegExp = RegExp(r'.*: ([\d-]+)$');
int extractNumber(String description) {
var numberString = _numberRegExp.firstMatch(description).group(1);
return int.parse(numberString.replaceAll('-', ''));
}
Let's do this in a simple way.
List<List<String>> inputList = [
["test: 111-333-5555", "test2: 222-333-4555"],
["test3: 555-333-2222"]
];
List resultList = [];
print('Input List : $inputList');
inputList.forEach((subList){
subList.forEach((element){
var temp = element.split(' ')[1].replaceAll('-', '');
resultList.add(temp);
});
});
print('Output List : $resultList');
Here I have taken your list as inputList and stored the result in resultList.
For each element of inputList we get a sub-list. I have converted the elements of that sub-list into the needed format and added those into a List.
Happy Coding :)
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!
My test scenario is to search for last name and expect whether all the names in the table are equal to the search value. I have a different function to search for the last name.
What i want now is to get all the names in the table and to test whether all the names have the same value. I want to use the below function in my page object and use it in the expect in the spec. How to do so?
I am confused how to use getText() and push them into an array and return the array so that i can use it in the expect
this.getAllBorrowerNamesInTable = function () {
element.all(by.binding('row.borrowerName')).then(function (borrowerNames){
});
};
Aside from using map(), you can approach it by simply calling getText() on the ElementArrayFinder - the result of element.all() call:
this.getAllBorrowerNamesInTable = function () {
return element.all(by.binding('row.borrowerName')).getText();
}
Then, you can assert the result to be equal to an array of strings:
expect(page.getAllBorrowerNamesInTable()).toEqual(["Borrower 1", "Borrower 2"]);
I am using the map() function to do the job:
this.getAllBorrowerNamesInTable = function () {
return element.all(by.binding('row.borrowerName')).map(function(elem) {
return elem.getText();
)};
}
You can use javascript 'push' function to add every borrower name and then we can return that array;
this.getAllBorrowerNamesInTable = function () {
var names = [];
element.all(by.binding('row.borrowerName')).then(function (borrowerNames){
borrowerNames.each(function(borrowerName) {
borrowerName.getText().then(function(name) {
names.push(name);
});
});
});
return names;
};