how can I store a Map type in my box ? I use Flutter Objectbox

Issue

I cannot save the Map type in my box, the songInfo attributes


@Entity()
class PlaylistItem {
  int id = 0;
  int recentIndex;
  
  Map<String, Object> songInfo;
  PlaylistItem({
    this.recentIndex = 0,
    this.songInfo = const <String, Object>{} ,
  });
 
}

When I run: flutter pub run build_runner build it ignores songInfo
WARNING : skipping property 'songInfo' in entity 'PlaylistItem', as it has an unsupported type: 'Map<String, Object>'
Why is Map an unsupported type? How do I store Map? please I need help (with an example would be welcome)

Solution

You would need to create a custom converter as seen here https://docs.objectbox.io/advanced/custom-types

Your best bet would probably be to convert it to json and store that as a String.
Untested, but you would need something like the following. Although, the Object portion of your map makes it a tad trickier, you would also have to write a way to serialize the object to json/string as well

  String? get dbSaveSongInfo=>
      songInfo== null ? null : json.encode(songInfo);

  set dbSaveSongInfo(String? value) {
    if (value == null) {
      songInfo= null;
    } else {
      songInfo= Map.from(
          json.decode(value).map((k, v) => MapEntry(k as String, v(handle your 2nd conversion here));
    }
  }

Answered By – Swisscheese

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *