How to store a list of maps in ObjectBox box?

Issue

I’m trying to store a list of Maps in the ObjectBox box, but since I’m new to ObjectBox I don’t understand how to store custom data types.

The data I’m trying to store (Structure looks like this)

name: 'name',
total: 100,
refNo: 00,
listOfProds: [{Map1},{Map2},{Map3},...]//<-Problem

I’ve tried

@Entity()
class ABC{
  int id;
  String name;
  int total;
  int refNo;
  List<Map>? products;

  ABC({
  this.id=0,
  required this.name,
  required this.total,
  required this.refNo,
  //required this.products, <-This will throw an error since List is not supported
  });
}

//Adding into DB
void addIntoDB(){
  late ABC _abc;
  _abc = ABC(
   name: 'name',
   total: 100,
   refNo: 00,
   //How can I assign the 'list of maps here' or any other ways?
  );
  _store.box<ABC>().put(_abc);
}

Solution

Referring to the Custom Types Documentation, turns out that storing a list in a raw format is not possible. (It’s still in feature request)

So instead try converting that list to JSON format, which would result in a single string.

String listInJson = json.encode(theList);

and now put that into box:

@Entity()
class ABC{
  int id;
  String name;
  int total;
  int refNo;
  String products;

  ABC({
  this.id=0,
  required this.name,
  required this.total,
  required this.refNo,
  required this.products,
  });
}

//Adding into DB
void addIntoDB(){
  late ABC _abc;
  _abc = ABC(
  name: 'name',
  total: 100,
  refNo: 00,
  products: listInJson,//<- That's how you do it.
  );
_store.box<ABC>().put(_abc);
}

and when retrieving, simply json.decode(products).

Answered By – Pranav

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

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