I want to put a bunch of objects in Flutter Objectbox using the putMany() method instead of using a loop. I tried to generate the objects in a list and put the list, but it throws errors. My model is as simple as that:
@Entity()
class Careers {
int id = 0;
int serialNumber;
String careerCode;
String careerNewName;
String careerOldName;
Careers({
required this.serialNumber,
required this.careerCode,
required this.careerNewName,
required this.careerOldName,
});
}
First, make sure that your ObjectBox
entity class is properly annotated with @Entity()
and that you have generated the ObjectBox
files using the objectbox_generator
package.
Now, create a list of Careers
objects and use the putMany()
method to insert them into the database
import 'package:objectbox/objectbox.dart';
// code
void main() async {
// Initialize ObjectBox store
var store = await openStore();
// Get the box for the Careers entity
final box = store.box<Careers>();
// Create a list of Careers objects
List<Careers> careersList = [
Careers(
serialNumber: 1,
careerCode: 'C1',
careerNewName: 'Career 1',
careerOldName: 'Old Career 1',
),
Careers(
serialNumber: 2,
careerCode: 'C2',
careerNewName: 'Career 2',
careerOldName: 'Old Career 2',
),
];
// Use putMany() to insert the list of Careers objects
final insertedIds = box.putMany(careersList);
print('Inserted IDs: $insertedIds');
// Close the store when done
await store.close();
}