Unable to convert map to list of object : dart

Issue

I’m trying to read the bookmarked items in my app on page reload. The code queries the list of items previously bookmarked but unable to access the particular bookmarked index. What am I missing to map the objects correctly? please help!

Future<List<Map<String, dynamic>>>_readfav() async {
   DatabaseHelper helper = DatabaseHelper.instance;
   List<Bookmark> savedbk = [];
  final favs = await helper.queryAllRows();
  print(favs); // returns a map of favorite objects
   favs.forEach((row) => savedbk.add(Bookmark()));
   print(savedbk); // returns Instances of Bookmark
   print( savedbk[0].Ayah.toString()); // returns null-- this is the problem 

  return favs;

 }

model class

class Bookmark{

  int id;
  int Surah;
  int Ayah;
  int Juz;

  Bookmark();

  
  Bookmark.fromMap(Map<String, dynamic> map) {


    id = map[columnId];
    Surah = map[columnSurah];
    Ayah = map[columnAyah];
    Juz = map[columnJuz];
  }

  
  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      columnSurah: Surah ,
      columnAyah: Ayah,
      columnJuz : Juz
    };
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }
}

Solution

Maybe the problem comes from the fact that you are not using row

Future<List<Map<String, dynamic>>>_readfav() async {
   DatabaseHelper helper = DatabaseHelper.instance;
   List<Bookmark> savedbk = [];
   final favs = await helper.queryAllRows();

   favs.forEach((row) => savedbk.add(Bookmark())); <-- here

   print( savedbk[0].Ayah.toString());  

  return favs;

 }

Doing favs.forEach((row) => savedbk.add(Bookmark())); will only create a list of empty Bookmark instances.

Maybe you should use favs.forEach((row) => savedbk.add(Bookmark.fromMap(row))); based on your constructor

Answered By – Quentin Klein

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.