Can we make List of File in flutter? I have a function which I have called multiple times and later set a value. But when I make List of File and try to store data I get error saying RangeError. This is my code
File? _displayImage;
List<File> _displayImageList = [];
Future<void> saveNetworkFileToLocalDirectory(String fileSrcUrl, int j) async {
var response = await http.get(Uri.parse(fileSrcUrl));
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String filePath =
join(documentsDirectory.path, getFileNameFromUrl(fileSrcUrl));
File file = File(filePath);
log(file.toString() + ' file');
log(filePath + ' file path');
await file.writeAsBytes(response.bodyBytes);
setState(() {
_displayImage = file;
log('j value ' + j.toString());
_displayImageList[j] = file;
});
List
in Dart does not allow for arbitrary position of elements, but are instead a collection of objects that starts from index position 0 and to index length - 1
where length
are the amount of elements in the List
.
So to insert an element in List
, we need to grow it by using one of the methods that List
provides to do so. Eg we can use add()
to grow the list by one in size while adding an element to the end of the List
.
If you need to insert elements with arbitrary "positions", you should instead consider using a Map<int, File>
in your case since you can then map a given j
value to a File
object.
You do, however, need to be aware that the default Map
in Dart are ordered by the insertion time of the element (newest entry = last "position" when iterating over the keys). If you need to order the elements based on the key, we can consider using something like SplayTreeMap
which automatically sorts entries based on the key
object when inserting the element:
https://api.dart.dev/stable/2.17.5/dart-collection/SplayTreeMap-class.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.