Home > other >  Type Conversion issue Flutter - Convert from Future<List<Dog>?> to List<Dog>
Type Conversion issue Flutter - Convert from Future<List<Dog>?> to List<Dog>

Time:08-17

Below is the method to retrieve a list of data from local sqlite table:

Future<List<Dog>?> retriveDogs() async {
    return await _dbHelper?.dogs();
  }

and you can check dogs() method as below :

Future<List<Dog>> dogs() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query('dogs');
return List.generate(maps.length, (i) {
  return Dog(
    id: maps[i]['id'],
    name: maps[i]['name'],
    age: maps[i]['age'],
  );
});

}

I want to display list in my log or via print statement. So, I have done as below :

print(" >>> " retriveDogs().toString());

But it gives me as : >> Instance of 'Future<List?> after print..

How can I get the complete list of Dogs ? Thanks.

CodePudding user response:

Your retriveDogs can retune null value. You can pass empty list for null cases like.

Future<List<Dog>> retriveDogs() async {
    return await _dbHelper?.dogs()??[];
  }

and to get data from future, you can use await or .then

onPressed: () async {
  final data = await retriveDogs();
  print(data.toString());
},
retriveDogs().then((value) => print(value));
  • Related