Reputation: 1834
I made a list to separate to different lists of integers for a flutter project. Now I want to remove all integers after the last null value. How can I do that ?
void main() {
List<int> v =[];
for(int i=0; i<3; i++){
for(int j=0; j<4; j++){
v.add(1);
}
v.add(null);
}
for(int i=0; i<12; i++){
print(v[i]);
}
}
Upvotes: 1
Views: 2614
Reputation: 1834
We can simply do that by, taking another list and storing the reverse of the list v in the new list. Then find the index of the first null in the new list. Then the index of the final null will be, Let the index of the null value came out to be n, then the value of the last null value in the list v will be, v.length - n + 1 for example,
rev = v.reversed;
int i;
for (i = 0; i < rev.length; i++) {
if (rev[i] == null) {
break;
}
}
Then the index will be v.length - i + 1. Now, just use sublist
function in Dart.
Upvotes: 0
Reputation: 802
if you need to remove ranger data from list then you can use removeWhere , using this method you can remove ranger data based in condition
void main() {
List<int> v =[];
for(int i=0; i<3; i++){
for(int j=0; j<4; j++){
v.add(1);
}
v.add(null);
v.removeWhere((x) => x is int);
}
for(int i=0; i<v.length; i++){
print(v[i]);
}
}
Upvotes: 1
Reputation: 7119
You can find the index of the last occurrence of null
in the list and make a sublist
starting from 0 to that index (+1 is used to include the last null value in the sublist):
List<int> v2 = v.sublist(0, v.lastIndexOf(null) + 1);
for(int i=0; i<v2.length; i++){
print(v2[i]);
}
Upvotes: 1