0
votes

I have a Box from Hive package in flutter. to remove expired objects from local db i define a method with a loop within in initstate() method. bu when i open the class this loop works by half!! what is wrong with that?

  @override
  void initState() {
  super.initState();
  removeExpired();
  }


DateTime nowTime;


void removeExpired() async{
var boxSecure= await Hive.openBox('securityBox');
var box = Hive.box('securityBox');
print('length: ${box.length}');
final nowTime = DateTime.now();
if(box.length>0){
  for(var i = 0 ; i< box.length; ++i) {
    DbSecurity m = box.getAt(i);
    var s= m.registerTime;
    if(nowTime.isAfter(s)){
      box.deleteAt(i);
      print('${i} removed'); // when there are 
    }
    else{
      
    }
  }
}
else{
}
}

this is a model :

@HiveType(typeId : 0)
class DbSecurity{

@HiveField(0)
String carId;
@HiveField(1)
DateTime registerTime;
@HiveField(2)
String TypeOfCar;

and finally when i open the page :

 I/flutter ( 9193): length: 6
I/flutter ( 9193): 0 removed
I/flutter ( 9193): 1 removed
I/flutter ( 9193): 2 removed
/////////////////
I/flutter ( 9193): 3
I/flutter ( 9193): length: 3
I/flutter ( 9193): 0 removed
I/flutter ( 9193): 1 removed

I try to remove all of the objects that has expired.

1

1 Answers

0
votes

You are removing items while iterating the box. Say at index 2 and index 3 are items to be removed. Then first box.deleteAt(2) will be called. What happens next is that every other item will shift down an index. The box that first was at index 3 will be at index 2. But in the next iteration of the loop you are checking index 3, therefore, the original item at 3 will never be checked