I recently started with Flutter. My App runs a sqflite database and I want to get all the data out of it and show it in a Row Widget in my App.
I know how to get the data and I know how to build the Widgets. I´m so confused, I have no idea how to convert the data that I get from the database to a List (with that I could build my widgets).
So I get Future List but I need List Drink
Just look:
My Object:
class Drink {
int id;
String time;
int amount;
Drink({this.id, this.time, this.amount});
}
Database:
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY,
$columnTime TEXT NOT NULL,
$columnAmount INTEGER NOT NULL
)
''');
}
How I get the output:
Future<List> raw() async {
Database db = await instance.database;
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $table");
List<Map<String, dynamic>> r = result.toList();
return r;
}
Create a factory constructor in your model
class Drink {
int id;
String time;
int amount;
Drink({this.id, this.time, this.amount});
factory Drink.fromJson(Map<String, dynamic> json) {
return Drink(
id: json['columnId'],
time: json['columnTime'],
amount: json['columnAmount'],
);
}
}
Later, You can map your fetched db data to Drink like this
Future<List<Drink>> fetchDrinks() async {
Database db = await instance.database;
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $table");
List<Map<String, dynamic>> r = result.toList().map((data) => Drink.fromJson(data));
return r;
}
You can use await on fetchDrinks method to get your list of Drink object.
I've not tested this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With