1

最近从 1.0.0 更新到 1.1.1 并且我的关系代码停止工作,我不确定我到底错过了什么,但直到项目的查询似乎正常工作。

这就是我所拥有的,我真的可以使用一些帮助来弄清楚我错过了什么

店铺创建:

  void initializeUserInventory() async {
    await getApplicationDocumentsDirectory().then((dir) {
      try {
        _quickSaveStore =
            Store(getObjectBoxModel(), directory: dir.path + '/quickSaveItems');
        _quickActionStore = Store(getObjectBoxModel(),
            directory: dir.path + '/quickSaveActions');
        _categorizedSaveStore = Store(getObjectBoxModel(),
            directory: dir.path + '/categorizedSaveItems');
        _itemCategoryStore = Store(getObjectBoxModel(),
            directory: dir.path + '/categorizedSaveCategories');
        _itemTagsStore = Store(getObjectBoxModel(),
            directory: dir.path + '/categorizedSaveTags');
      } catch (e) {
        print(e.toString());
      }
    }).whenComplete(() {
      // Must initialize everything else after completion of store initialization!
      _userQuickSaveBox = Box<InitialItem>(_quickSaveStore!);
      _quickActionSaveBox = Box<QuickSaveAction>(_quickActionStore!);
      _categorizedSaveBox = Box<InitialItem>(_categorizedSaveStore!);
      _itemCategoryBox = Box<ItemCategory>(_itemCategoryStore!);
      _itemTagsBox = Box<ItemTag>(_itemTagsStore!);
    });
  }

以下是实体文件: InitialItem:

part 'initial_item.g.dart';

@JsonSerializable(explicitToJson: true)
@Entity()
class InitialItem {
  String? itemName;
  String? inc;
  DateTime cacheTime;
  DateTime? saveTime;


  @Id(assignable: true)
  int id;

  //#region Category
  //
  // Functions that are utilized for Saving the item by Category
  //
  /// Holds the count of how many items the vehicle/WO needs
  int? quantity;

  /// Any comments the user has added to the item
  String? userComment;

  /// Category that the item belongs too
  final itemCategory = ToOne<ItemCategory>();

  /// Allows adding a tag to the saved item
  final tags = ToMany<ItemTag>();

  //#endregion


  InitialItem(
      {this.id = 0,
      this.itemName,
      this.inc,
      this.quantity = 1,
      DateTime? cacheTime,
      DateTime? saveTime,
      this.userComment = '',})
      : cacheTime = cacheTime ?? DateTime.now(),
        saveTime = cacheTime ?? DateTime.now();
}

物品类别:

part 'item_category.g.dart';

@JsonSerializable(explicitToJson: true)
@Entity()
class ItemCategory {
  int id;
  String? categoryUid;
  String? userUid;
  String? categoryName;
  String? categoryComment;

  @Backlink()
  final items = ToMany<InitialItem>();

  ItemCategory(
      {this.id = 0,
      this.userUid,
      this.categoryName,
      this.categoryUid,
      this.categoryComment});
}

物品标签:

part 'item_tag.g.dart';

@JsonSerializable(explicitToJson: true)
@Entity()
class ItemTag {
  int id;
  String? name;

  /// Only used for FilterChip display, not saved in any database
  @Transient()
  bool isSelected;
  String? uid;

  ItemTag({this.id = 0, this.name, this.isSelected = false, this.uid});
}

标签和类别已经由用户创建并保存在他们的框中。一个项目被传递到视图中,用户可以为项目添加标签,并且可以选择一个类别来保存项目。

  /// Attaches the tags that the user selected to the item for saving
  void attachTagsToItem() {
    // Clear all previous tags before adding the selected tags
    savingItem?.tags.clear();
    savingItem?.tags.addAll(enabledTagList);
  }

然后该项目将选定的类别写入它的 toOne 目标并保存 - saveItem 正确地在其中包含所有内容

  bool saveCategorizedItem() {
    if (selectedCategory != null) {
      // Set the item category
      savingItem!.itemCategory.target = selectedCategory;

      _userInventoryService.addCategorizedItemToLocal(savingItem!);

      return true;
    } else {
      return false;
    }
  }

它的保存位置——此时,一切都已检查完毕。我可以调试并查看其变量中的标签和信息,并且可以在 itemCategory 中查看类别及其信息。

  void addCategorizedItemToLocal(InitialItem saveItem) {
    _categorizedSaveBox.put(saveItem);
    print('Item saved to categorized database');
  }

保存项目

稍后,我查询保存的每个项目,以便将它们分组到列表中。而此时它只返回InitialItem,并没有拉取关系数据。toOne 和 toMany 的目标都是空的。

  /// Returns all the of Items that have been categorized and saved
  List<InitialItem> getAllCategorizedItems() => _categorizedSaveBox.getAll();

------------------------------------------------------------------------------------------
Calling the query in the View Provider's class
  void getCategorizedItems() {
    _categorizedSaveList = _userInventoryService.getAllCategorizedItems();
    notify(ViewState.Idle);
  }

然后我尝试使用返回的查询构建列表。element.itemCategory.target 返回 null,标签也是如此。正如我所说,这一切以前在版本 1.0.0 中工作,升级后失败,没有进行其他更改。一般的查询有问题吗?我可以在调试窗口中查看关系,所以我假设设置正确,它似乎并没有使用原始查询拉取对象。谁能阐明我做错了什么?

  Widget categorizedList(BuildContext context) {
    final saveProvider =
        Provider.of<UserInventoryProvider>(context, listen: true);
    return GroupedListView<dynamic, String>(
      physics: const BouncingScrollPhysics(),
      elements: saveProvider.categorizedSaveList,
      groupBy: (element) => element.itemCategory.target!.categoryName,
      groupComparator: (d1, d2) => d2.compareTo(d1),
      groupSeparatorBuilder: (String value) => Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text(value,
            textAlign: TextAlign.center,
            style: TextStyles.kTextStyleWhiteLarge),
      ),
      indexedItemBuilder: (c, element, index) {
        return Container();
      },
    );
  }

保存后直接从商店查询的项目

4

1 回答 1

1

经过评论中的所有讨论,我终于注意到您初始化了多个商店。实际上,您正在使用多个独立数据库,因此关系无法按预期工作。你initializeUserInventory()应该看起来像:

void initializeUserInventory() async {
  _store = await openStore(); // new shorthand in v1.1, uses getApplicationDocumentsDirectory()
  _userQuickSaveBox = _store.box();
  _quickActionSaveBox = _store.box();
  _categorizedSaveBox = _store.box();
  _itemCategoryBox = _store.box();
  _itemTagsBox = _store.box();
}
于 2021-08-06T06:30:53.467 回答