I am new to dart, trying to convert Map to json String for sqflite, json.encoder
and jsonEncode
doesn't work. i tried to use json_serializable
but couldn't run build_runner
, did a bunch of manipulations with meta and analyzer.
the problem occurs when converting Variants, this is should look like:
"variants": {
"iphone 6": {"1": "8", "2": "6"},
"xiaomi mi6": {"1": "8", "3": "5"},
"samsung A6": {"1": "8"}
}
How it is look like:
variants: {
iphone 6: {1: 8, 2: 6},
xiaomi mi6: {1: 8, 3: 5},
samsung A6: {1: 8}
}
SQL func:
Future<void> addToCart(List<List<TextEditingController>> controllers, Item item) async {
Map<String, Map<int, String>> resultMap = Map();
var list = item.variants.values.toList();
var models = item.variants.keys.toList();
for (int i = 0; list.length > i; i ++) {
var variantsName = list.elementAt(i).toList();
var modelsName = models.elementAt(i);
Map<int, String> values = Map();
for (int ind = 0; variantsName.length > ind; ind ++) {
String reasultC = controllers[i].elementAt(ind).text;
if (reasultC.isNotEmpty && int.parse(reasultC) > 0) {
values[ind + 1] = reasultC;
}
}
if (!resultMap.containsKey(modelsName) && values.isNotEmpty) {
resultMap[modelsName] = values;
}
}
db = await openDatabase("$_dbName.db");
db.execute('''
CREATE TABLE IF NOT EXISTS $_dbName(
id INTEGER PRIMARY KEY,
idItem TEXT,
title TEXT,
variants TEXT,
images TEXT)
''');
var end = Cart(idItem: item.id, title: item.title, variants: resultMap, images: item.images).toJson();
print(end);
await db.insert(_dbName, end);
await db.close();
}
class Cart {
String idItem;
String title;
Map<String, dynamic> variants;
List<String> images;
Cart({this.idItem, this.title, this.variants, this.images});
Map<String, dynamic> toJson() =>
<String, dynamic>{
'idItem': this.idItem,
'title': this.title,
'variants': jsonEncode(this.variants), <= NoSuchMethodError: Class '_InternalLinkedHashMap<int, String>' has no instance method 'toJson'. Receiver: _LinkedHashMap len:1 T
'images': json.encode(this.images)
};
}
Thanks.
'variants': jsonEncode(this.variants)
? – Ameline