You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用中如何按指定Recipe ID同步关联Ingredient数据

解决方案:同步特定Recipe关联的Ingredient数据

在Amplify DataStore中处理多对多关联的选择性同步时,不能直接通过Ingredient.RECIPES.contains()嵌套关联条件,需要借助自动生成的中间表RecipeIngredient来构建正确的同步表达式。

正确的同步配置代码

替换你原有的AmplifyDataStore配置部分,使用以下同步表达式:

await Future.wait([
  Amplify.addPlugin(AmplifyDataStore(
    modelProvider: ModelProvider.instance,
    syncExpressions: [
      DataStoreSyncExpression(
        Ingredient.classType,
        () => RecipeIngredient.INGREDIENT.eq(
          IngredientModelIdentifier(id: Ingredient.ID)
        ).and(
          RecipeIngredient.RECIPE.eq(RecipeModelIdentifier(id: recipeId))
        ),
        syncMode: SyncMode.syncWithSubscription,
      ),
    ],
  )),
  Amplify.addPlugin(AmplifyAPI()),
  Amplify.addPlugin(AmplifyAuthCognito()),
  Amplify.addPlugin(AmplifyStorageS3()),
]);

await Amplify.configure(amplifyconfig);

关键说明

  • 多对多关系会自动生成RecipeIngredient中间表,我们通过该表的INGREDIENT字段关联到Ingredient的ID,同时筛选RECIPE字段等于目标recipeId,以此精准定位关联的Ingredient数据。
  • 若之前已有本地同步数据,建议先调用Amplify.DataStore.clear()清除本地存储,再重新配置同步,避免旧数据残留导致筛选异常。

验证同步结果

配置完成后,调用DataStore查询Ingredient即可获取仅与目标Recipe关联的数据:

final ingredients = await Amplify.DataStore.query(
  Ingredient.classType,
);

内容的提问来源于stack exchange,提问作者tamptek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:22:39