Код: Выделить всё
@riverpod
class JsonInventoryService extends _$JsonInventoryService {
late Future _currentItems;
late InventoryResult inventoryResult;
Future loadItems() async {
var jsonString = await rootBundle.loadString('assets/inventorylist.json');
inventoryResult =
InventoryResult.fromJson(jsonDecode(jsonString));
_currentItems = Future.value(inventoryResultsToItems(inventoryResult));
}
Future fetchData() async {
return _currentItems;
}
Код: Выделить всё
Map insertItem(Item item) {
inventoryResult.results.add(item);
final jsonmap = inventoryResult.toJson(); //json_serializable automatically handles nested class
storage.writeFile(jsonmap);
return jsonmap;
}
}
Класс хранения:< /p>
Код: Выделить всё
class Storage {
Future get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future get _localFile async {
final path = await _localPath;
return File('$path/inventorylist.json');
}
Future writeFile(dynamic jsonmap) async {
final file = await _localFile;
return file.writeAsString('$jsonmap');
}
}
Любые предложения по улучшению или исправлению очень приветствуются, поскольку я начал только в прошлом месяце.
Подробнее здесь: https://stackoverflow.com/questions/790 ... -local-fil