1

I created a function, _queryOffline(), for retrieving data from a local Sqflite database and inserting it into a Google Sheets worksheet via Google Sheets API when internet is available. Basically, I iterated database query calls using a while loop that runs the number of rows of the database table which tries to insert the query result into the _postOnline() function which calls for adding a row on GoogleSheets.

_queryOffline() async {
   Database db = await DatabaseHelperTwo.instance.database;
   int? count = Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM table'));
   String countString = count.toString();
   var countInt = int.parse(countString);
   while (countInt != 0) {
      List<Map<String, dynamic>> result = await db.rawQuery('SELECT * FROM table WHERE id=?', ['$countInt']);
      _postOnline(result);
      countInt--;
   }
}

_postOnline(feedback) async {
   await GoogleSheetsApi.insertOffline([feedback]);
   setState(() {});
}

However, whenever I do a function call _queryOffline(), I always get "Unhandled Exception: type 'QueryResultSet' is not a subtype of type 'Map<String, dynamic>'", and when I checked the query was of List<Map<String, dynamic>> type, whereas what was required by the gsheets API function was Map<String, dynamic>.

Is there any way I can convert List<Map<String, dynamic>> into Map<String, dynamic> only? I'm still new to flutter and app dev in general, so if you have any suggestions for improving what I aim to do (Sqflite -> GSheets), I'll really appreciate it! Thanks!

  • If you have a `List` and want to merge all of the `Map`s together into a single `Map`, you can use collection-for and the spread operator: `var mergedMap = {for (var map in listOfMaps) ...map};` – jamesdlin Feb 19 '22 at 22:06

1 Answers1

2

Try this :

List<Map<String, dynamic>> results = await db.rawQuery('SELECT * FROM table WHERE id=?', ['$countInt']);
Map<String, dynamic> result = {};
for(var r in results){
  result.addAll(r);
}
_postOnline(result);
Kantine
  • 747
  • 6
  • 14
  • This worked perfectly! Although what I did is that I did not need to store the list map items into the result list, and instead I added r to the function _postOnline instead. – Yosef Christian Cuenca Feb 22 '22 at 02:39