I have list of lists of dynamics which contain empty values. when I filter the list where values are not empty I get blank space separated by comma.
main.dart
const List<List<dynamic>> items = [
['name', 'username', 'email', 'password'],
['admin', '', 'test@mail', 'fakepass'],
['', 'useritemname', '', 'hello'],
];
void main() {
final al = items.where((element) => element != '' && element.length >= 4);
for (var l in al) {
print(l);
}
}
Above code give below results:
[name, username, email, password]
[admin, , test@mail, fakepass]
[, useritemname, , hello]
i want to remove those commas (, , and ,)
CodePudding user response:
,
is for separating item in list, but ,,
means you have empty string in your list, you can remove ,,
with this:
List<List<dynamic>> newList = [];
for (var item in items) {
List<String> tempList = [];
for (var element in item) {
if (element.isNotEmpty) {
tempList.add(element);
}
}
newList.add(tempList);
}
shorter version(tanks to @pskink):
List<List<dynamic>> newList items.map((l) => l.where((i) => i.isNotEmpty).toList()).toList();
results:
print('newList = $newList'); //[[name, username, email, password], [admin, test@mail, fakepass], [useritemname, hello]]
print('items = $items'); // [[name, username, email, password], [admin, , test@mail, fakepass], [, useritemname, , hello]]
CodePudding user response:
Even though the code of the other answer works I strongly commend to use strict typing. If you had strict typing you could have avoid these semantic errors:
Have a look at this:
const List<List<String>> items = [
['name', 'username', 'email', 'password'],
['admin', '', 'test@mail', 'fakepass'],
['', 'useritemname', '', 'hello'],
];
void main() {
List al = items
.map((List<String> list) => list.where((String element) => element != '' && element.length >= 4).toList())
.toList();
print(al);
}
This generates the output you want:
[name, username, email, password]
[admin, test@mail, fakepass]
[useritemname, hello]