マーケターライフ

【Dart/Flutter】複数行をデータベースに追加

void test() async {

Future<void> insertProducts(products) async {
final db = await database;
var buffer = new StringBuffer();
products.forEach((c) {
if (buffer.isNotEmpty) {
buffer.write(“,\n”);
}
buffer.write(“(‘”);
buffer.write(c[“id”]);
buffer.write(“‘, ‘”);
buffer.write(c[“name”]);
buffer.write(“‘, ‘”);
buffer.write(c[“price”]);
buffer.write(“‘)”);
});
var raw = await db.rawInsert(“INSERT Into products (id,name,price)”
” VALUES ${buffer.toString()}”);
return raw;
}

 

var products = Products(
id: 3,
name: ‘tarou’,
price: 39800,
);

await insertProducts(products.toMap());

 

}

 

 

class Products {
final int id;
final String name;
final int price;

Products({this.id, this.name, this.price});

List<Map<String, dynamic>> toMap() {
return [
{
‘id’: id,
‘name’: name,
‘price’: price,
},
{
‘id’: id + 100,
‘name’: name,
‘price’: price,
}
];
}
}