我正在使用 Flutter 和 SQFLite 進行 API 同步。
我從 API 獲取資料,對其進行映射,然后逐項添加到 SQL:
return (response as List).map((tmp) {
print('? API: apiSync - Inserting News');
DBProvider.db.updateNews(ArtNews.fromJson(tmp));
}).toList();
一切正常,但有一個小問題:在“updateNews”完成之前呼叫了回傳。
updateNews 是一個在 SQFLite 上寫入資料的簡單異步函式。
這產生了一個大問題:應用程式在同步結束之前打開并且資料仍在資料庫中寫入。
我嘗試過使用 AWAIT,但它沒有任何效果:
(response as List).map((tmp) async{
print('? API: apiSync - Inserting $type');
await DBProvider.db.updateNews(ArtNews.fromJson(tmp));
}).toList();
return 'done';
updateNews 被呼叫了幾十次,toList 結束,回傳'done',但 updateNews 仍在向資料庫添加內容。
我想我在 toList 或 async 上缺少一些東西。有任何想法嗎?謝謝!
uj5u.com熱心網友回復:
嘗試這個:
await Future.wait((response as List).map((tmp) {
print('? API: apiSync - Inserting $type');
return DBProvider.db.updateNews(ArtNews.fromJson(tmp));
}));
return 'done';
參考要點:
https://dartpad.dev/?id=e72b1dc9013e2add447a90979bed7aab
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524827.html
