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

Flutter中如何关联食材勾选列表与JSON食谱数据库

食材匹配食谱并跳转的实现方案

1. 收集选中食材

从Screen2的勾选组件中获取用户选中的食材列表,用状态变量维护选中状态(以React Native为例):

const [selectedIngredients, setSelectedIngredients] = useState([]);

// 处理食材勾选/取消逻辑
const toggleIngredient = (ingredient) => {
  setSelectedIngredients(prev => 
    prev.includes(ingredient)
      ? prev.filter(item => item !== ingredient)
      : [...prev, ingredient]
  );
};

2. 筛选JSON食谱数据库

假设你的JSON食谱结构如下:

{
  "recipes": [
    {
      "id": 1,
      "name": "番茄炒蛋",
      "ingredients": ["番茄", "鸡蛋", "盐", "食用油"],
      "steps": "..."
    }
  ]
}

根据选中食材筛选食谱,支持两种匹配规则:

  • 全匹配:食谱所有食材都在选中列表中
  • 部分匹配:食谱包含至少一个选中食材(更符合常规需求)

筛选逻辑代码:

import recipeDb from './recipes.json';

// 部分匹配示例(推荐)
const filterMatchedRecipes = () => {
  const selectedSet = new Set(selectedIngredients);
  return recipeDb.recipes.filter(recipe => 
    recipe.ingredients.some(ing => selectedSet.has(ing))
  );
};

// 全匹配逻辑(按需切换)
// const filterMatchedRecipes = () => {
//   return recipeDb.recipes.filter(recipe => 
//     selectedIngredients.every(ing => recipe.ingredients.includes(ing))
//   );
// };

3. 跳转至Screen3并传递结果

以React Navigation为例,绑定按钮点击事件触发跳转,同时传递筛选后的食谱数据:

import { useNavigation } from '@react-navigation/native';

const navigation = useNavigation();

const handleGoToResults = () => {
  const matchedRecipes = filterMatchedRecipes();
  navigation.navigate('Screen3', { recipes: matchedRecipes });
};

4. Screen3接收并展示数据

在Screen3中读取传递的参数,渲染食谱列表:

import { useRoute } from '@react-navigation/native';

const Screen3 = () => {
  const route = useRoute();
  const { recipes } = route.params;

  return (
    <View>
      {recipes.length === 0 ? (
        <Text>未找到匹配的食谱</Text>
      ) : (
        recipes.map(recipe => (
          <View key={recipe.id} style={{ padding: 16, borderBottomWidth: 1 }}>
            <Text style={{ fontSize: 20, fontWeight: 'bold' }}>{recipe.name}</Text>
            <Text style={{ marginTop: 8 }}>食材:{recipe.ingredients.join(', ')}</Text>
            <Text style={{ marginTop: 8 }}>做法:{recipe.steps}</Text>
          </View>
        ))
      )}
    </View>
  );
};

优化提示

  • 用Set存储选中食材,比数组includes查找效率更高,适合数据量大的场景
  • 若支持多语言,需确保食材名称的匹配逻辑兼容不同语言的字符串对比

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:57:11