如何在Flutter Objectbox中使用putMany()?

yqkkidmi  于 2023-08-07  发布在  Flutter
关注(0)|答案(1)|浏览(171)

我想使用putMany()方法而不是使用循环将一堆对象放入Flutter Objectbox中。我试图在列表中生成对象并放置列表,但它会抛出错误。我的模型就是这么简单:

@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,
  });
}

字符串

w51jfk4q

w51jfk4q1#

首先,确保您的ObjectBox实体类用@Entity()正确注解,并且您已经使用objectbox_generator包生成了ObjectBox文件。
现在,创建Careers对象列表,并使用putMany()方法将它们插入到数据库中

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();
}

字符串

相关问题