3

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;
  }
mariusEBR
  • 43
  • 1
  • 2
  • 5
  • 1
    Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Aug 03 '20 at 11:19

1 Answers1

6

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.

arthankamal
  • 6,341
  • 4
  • 36
  • 51