I'm working on an API sync using Flutter and SQFLite.
I get the data from the API, map it, and then add to SQL item by item:
return (response as List).map((tmp) {
print('• API: apiSync - Inserting News');
DBProvider.db.updateNews(ArtNews.fromJson(tmp));
}).toList();
Everything works fine, but there is a small problem: the return is called before the 'updateNews' is done.
updateNews is a simple async function that writes data on SQFLite.
This creates a big issue: the app opens before the sync is over and data is still being written on DB.
I've tried using AWAIT, but it doesn't make any effect:
(response as List).map((tmp) async{
print('• API: apiSync - Inserting $type');
await DBProvider.db.updateNews(ArtNews.fromJson(tmp));
}).toList();
return 'done';
updateNews is called dozens of times, the toList ends, returns 'done', but the updateNews is still adding content to the DB.
I guess there is something I'm missing on toList or async. Any ideas? Thanks!
CodePudding user response:
Try this:
await Future.wait((response as List).map((tmp) {
print('• API: apiSync - Inserting $type');
return DBProvider.db.updateNews(ArtNews.fromJson(tmp));
}));
return 'done';
Gist for reference: