Line data Source code
1 : import 'dart:convert'; 2 : import 'dart:typed_data'; 3 : 4 : import 'package:flutter/services.dart' show rootBundle; 5 : 6 : /// A class that loads, and cache files 7 : /// 8 : /// it automatically looks for files on the assets folder 9 : class AssetsCache { 10 : final String prefix; 11 : final Map<String, _Asset> _files = {}; 12 : 13 25 : AssetsCache({this.prefix = 'assets/'}); 14 : 15 : /// Removes the file from the cache 16 0 : void clear(String file) { 17 0 : _files.remove(file); 18 : } 19 : 20 : /// Removes all the files from the cache 21 0 : void clearCache() { 22 0 : _files.clear(); 23 : } 24 : 25 : /// Reads a file from assets folder 26 0 : Future<String> readFile(String fileName) async { 27 0 : if (!_files.containsKey(fileName)) { 28 0 : _files[fileName] = await _readFile(fileName); 29 : } 30 : 31 : assert( 32 0 : _files[fileName] is _StringAsset, 33 0 : '"$fileName" is not a String Asset', 34 : ); 35 : 36 0 : return _files[fileName]!.value as String; 37 : } 38 : 39 : /// Reads a binary file from assets folder 40 0 : Future<List<int>> readBinaryFile(String fileName) async { 41 0 : if (!_files.containsKey(fileName)) { 42 0 : _files[fileName] = await _readBinary(fileName); 43 : } 44 : 45 : assert( 46 0 : _files[fileName] is _BinaryAsset, 47 0 : '"$fileName" is not a Binary Asset', 48 : ); 49 : 50 0 : return _files[fileName]!.value as List<int>; 51 : } 52 : 53 0 : Future<Map<String, dynamic>> readJson(String fileName) async { 54 0 : final content = await readFile(fileName); 55 0 : return jsonDecode(content) as Map<String, dynamic>; 56 : } 57 : 58 0 : Future<_StringAsset> _readFile(String fileName) async { 59 0 : final string = await rootBundle.loadString('$prefix$fileName'); 60 0 : return _StringAsset(string); 61 : } 62 : 63 0 : Future<_BinaryAsset> _readBinary(String fileName) async { 64 0 : final data = await rootBundle.load('$prefix$fileName'); 65 0 : final list = Uint8List.view(data.buffer); 66 : 67 0 : final bytes = List<int>.from(list); 68 0 : return _BinaryAsset(bytes); 69 : } 70 : } 71 : 72 : class _Asset<T> { 73 : T value; 74 0 : _Asset(this.value); 75 : } 76 : 77 : class _StringAsset extends _Asset<String> { 78 0 : _StringAsset(String value) : super(value); 79 : } 80 : 81 : class _BinaryAsset extends _Asset<List<int>> { 82 0 : _BinaryAsset(List<int> value) : super(value); 83 : }