Issue
I am trying to make a method that creates a map with a certain length based on an int value. The map consists of int value which is the same as the I value in the loop and a boolean value which is always false.
Future initialMap(FirebaseUser user, String packageCode, int totalDays) async{
List<Map<int, dynamic>> days = List<Map<int, dynamic>>() ;
int i =0;
while(i<totalDays){
days[i].addAll({i:false});
i++;
}
return await users.document(user.uid).collection('myPackages').document(packageCode).setData({
'DaysMap': days
});
}
I am getting this error:
ion in 3,580ms.
E/flutter (26175): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter (26175): #0 List._setIndexed (dart:core-patch/growable_array.dart:152:72)
E/flutter (26175): #1 List.[]= (dart:core-patch/growable_array.dart:149:5)
Solution
The error you have is normal because you are trying to access a value in the table's nonexistent index. The array "days" is initially empty but you try to access a value by doing: days [i], which normally returns an error.
Since I was not sure of what exactly you wanted to achieve (build a list of maps, or build a map), I create these snippets :
The snippet above creates a list of maps:
Future initialMap(FirebaseUser user, String packageCode, int totalDays) async{
List<Map<int, dynamic>> days = List<Map<int, dynamic>>() ;
int i =0;
while(i<totalDays){
days[i].addAll({i:false});
i++;
}
return await users.document(user.uid).collection('myPackages').document(packageCode).setData({
'DaysMap': days
});
}
Sample result : [{0: false}, {1: false}, {2: false}, {3: false}, {4: false}, {5: false}, {6: false}, {7: false}, {8: false}, {9: false}, {10: false}, {11: false}, {12: false}, {13: false}, {14: false}]
The snipped above creates a map:
Future initialMap(FirebaseUser user, String packageCode, int totalDays) async{
Map<int, dynamic> days = Map<int, dynamic>() ;
int i =0;
while(i<totalDays){
days[i].addAll({i:false});
i++;
}
return await users.document(user.uid).collection('myPackages').document(packageCode).setData({
'DaysMap': days
});
}
Sample result: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false, 11: false, 12: false, 13: false, 14: false}
Also, you should never add side effects to functions. I mean, this function is supposed to build a list of items, it should only build this list and nothing else, instead you could create another function named for example updateUserPackage(user, data)
that saves the data of the map previously generated by initialMap()
.
Answered By - Steve
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.