Flutter营养分析插件nutrition_ai_module的使用
Flutter营养分析插件nutrition_ai_module的使用
欢迎使用Passio Nutrition-AI-Module Flutter SDK!
这个包提供了一组预构建的页面,允许用户轻松地将这些页面集成到您的Flutter应用中。只需几个简单的步骤,您的应用就可以利用这些现成的功能。此插件与nutrition_ai配合使用。
在继续之前:
-
Passio Nutrition-AI SDK添加了来自Open Food Facts的数据(https://en.openfoodfacts.org/)。每个包含Open Food Facts数据的食物都会被标记为公开变量
isOpenFood: Bool
。如果您选择设置isOpenFood = true
,则表示您同意遵守Open Food Facts许可协议(https://opendatacommons.org/licenses/odbl/1-0)及其使用条款(https://world.openfoodfacts.org/terms-of-use),并且您需要在UI中添加以下许可证声明:"本记录包含来自Open Food Facts([https://en.openfoodfacts.org](https://en.openfoodfacts.org))的信息,这些信息在此处根据Open Database License([https://opendatacommons.org/licenses/odbl/1-0)](https://opendatacommons.org/licenses/odbl/1-0)")提供。"
-
要使用SDK,请在 https://www.passio.ai/nutrition-ai 注册。没有有效的SDK密钥,SDK将无法工作。
最低要求
Android | iOS | |
---|---|---|
支持 | SDK 26+ | 13.0+ |
必要权限
该模块需要以下权限才能正常工作:
Android
在您的AndroidManifest.xml
文件中添加以下权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<application>
<receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
</application>
iOS
在您的Info.plist
文件中添加以下权限:
<key>NSCameraUsageDescription</key>
<string>App requires your camera access to scan the food.</string>
<key>NSLocalNotificationUsageDescription</key>
<string>We use local notifications to remind you of meal times.</string>
安装配置
安卓设置
在顶级的build.gradle
文件(项目: android)中添加:
allprojects {
repositories {
...
flatDir {
dirs project(':nutrition_ai').file('libs')
}
}
}
开始使用
- 在
pubspec.yaml
文件中添加依赖项:
dependencies:
nutrition_ai_module: ^3.1.0
使用方法
注意:确保在启动营养AI模块前正确配置SDK。
- 导入Passio Nutrition AI Module:
import 'package:nutrition_ai_module/nutrition_ai_module.dart';
- 在您选择的位置插入以下行以启动营养AI模块:
await NutritionAIModule.instance
.setPassioConnector(MyPassioConnector()) // 这是可选的
.launch(context);
-
setPassioConnector(PassioConnector passioConnector): 若要使用此方法,您必须提供一个
PassioConnector
作为参数,并确保实现PassioConnector
中指定的所有方法。默认情况下,数据将存储在本地数据库中。 -
launch(BuildContext context): 为了启动我们的模块,此方法需要一个
BuildContext
作为参数。您可以在所需位置调用此方法,并返回一个Future
。
- 实现
PassioConnector
class MyPassioConnector implements PassioConnector {
// 用户资料方法
@override
Future<UserProfileModel?> fetchUserProfile() async {
}
@override
Future<void> updateUserProfile({
required UserProfileModel userProfile,
required bool isNew,
}) async {
}
// 记录方法
@override
Future<List<FoodRecord>> fetchDayRecords({
required DateTime dateTime,
}) async {
}
@override
Future<List<FoodRecord>> fetchRecords({
required DateTime fromDate,
required DateTime endDate,
}) async {
}
@override
Future<void> updateRecord({
required FoodRecord foodRecord,
required bool isNew,
}) async {
}
@override
Future<void> deleteRecord({
required FoodRecord foodRecord,
}) async {
}
// 收藏方法
@override
Future<List<FoodRecord>?> fetchFavorites() async {
}
@override
Future<bool> favoriteExists({
required FoodRecord foodRecord,
}) async {
}
@override
Future<void> updateFavorite({
required FoodRecord foodRecord,
required bool isNew,
}) async {
}
@override
Future<void> deleteFavorite({
required FoodRecord foodRecord,
}) async {
}
// 水量方法
@override
Future<double> fetchConsumedWater({
required DateTime dateTime,
}) async {
}
@override
Future<List<WaterRecord>> fetchWaterRecords({
required DateTime fromDate,
required DateTime endDate,
}) async {
}
@override
Future<void> updateWater({
required WaterRecord waterRecord,
required bool isNew,
}) async {
}
@override
Future<void> deleteWaterRecord({
required WaterRecord record,
}) async {
}
// 体重方法
@override
Future<double> fetchMeasuredWeight({
required DateTime dateTime,
}) async {
}
@override
Future<List<WeightRecord>> fetchWeightRecords({
required DateTime fromDate,
required DateTime endDate,
}) async {
}
@override
Future<void> updateWeight({
required WeightRecord record,
required bool isNew,
}) async {
}
@override
Future<void> deleteWeightRecord({
required WeightRecord record,
}) async {
}
}
FoodRecord
类
class FoodRecord {
String id = '';
String passioID;
String refCode;
String name;
String additionalData = '';
String iconId = '';
late List<FoodRecordIngredient> ingredients;
String _selectedUnit = '';
double _selectedQuantity = zeroQuantity;
late List<PassioServingSize> servingSizes;
late List<PassioServingUnit> servingUnits;
PassioIDEntityType? entityType;
MealLabel? mealLabel;
int? _createdAt;
String? openFoodLicense;
static const zeroQuantity = 0.00001;
bool isFavorite = false;
}
FoodRecordIngredient
类
class FoodRecordIngredient {
String id = '';
String passioID;
String refCode;
String name = '';
String iconId = '';
String selectedUnit = '';
double selectedQuantity = 0;
late List<PassioServingSize> servingSizes;
late List<PassioServingUnit> servingUnits;
PassioNutrients referenceNutrients;
String? openFoodLicense;
PassioIDEntityType entityType;
}
UserProfileModel
类
class UserProfileModel {
String? id;
String? name;
int? _age;
double? _weight;
double _targetWeight;
GenderSelection gender;
MeasurementSystem heightUnit;
MeasurementSystem weightUnit;
double _targetWater;
ActivityLevel? _activityLevel;
double? _height;
CalorieDeficit _calorieDeficit;
PassioMealPlan? _mealPlan;
int caloriesTarget = 2100;
int carbsPercentage = 50;
int proteinPercentage = 25;
int fatPercentage = 25;
}
WaterRecord
类
class WaterRecord {
int? id;
double _waterConsumption;
final int createdAt;
}
WeightRecord
类
class WeightRecord {
int? id;
double _weight;
final int createdAt;
}
更多关于Flutter营养分析插件nutrition_ai_module的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter营养分析插件nutrition_ai_module的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
nutrition_ai_module
是一个用于在 Flutter 应用中实现营养分析的插件。它可以帮助开发者轻松集成营养分析功能,例如识别食物、获取营养成分信息等。以下是使用 nutrition_ai_module
的基本步骤和示例代码。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 nutrition_ai_module
的依赖:
dependencies:
flutter:
sdk: flutter
nutrition_ai_module: ^1.0.0 # 请确保使用最新版本
然后运行 flutter pub get
以安装依赖。
2. 初始化插件
在你的 Flutter 项目中,首先需要初始化 nutrition_ai_module
。通常在 main.dart
或应用启动时进行初始化。
import 'package:nutrition_ai_module/nutrition_ai_module.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化 Nutrition AI
await NutritionAIModule.initialize(
apiKey: 'YOUR_API_KEY', // 替换为你的 API 密钥
);
runApp(MyApp());
}
3. 识别食物并获取营养信息
使用 NutritionAIModule
提供的 API 来识别食物并获取其营养成分信息。
import 'package:flutter/material.dart';
import 'package:nutrition_ai_module/nutrition_ai_module.dart';
class NutritionAnalysisPage extends StatefulWidget {
[@override](/user/override)
_NutritionAnalysisPageState createState() => _NutritionAnalysisPageState();
}
class _NutritionAnalysisPageState extends State<NutritionAnalysisPage> {
String _nutritionInfo = '等待分析...';
Future<void> _analyzeFood(String foodName) async {
try {
NutritionInfo info = await NutritionAIModule.analyzeFood(foodName);
setState(() {
_nutritionInfo = '卡路里: ${info.calories}kcal\n'
'蛋白质: ${info.protein}g\n'
'脂肪: ${info.fat}g\n'
'碳水化合物: ${info.carbohydrates}g';
});
} catch (e) {
setState(() {
_nutritionInfo = '分析失败: $e';
});
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('营养分析'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
decoration: InputDecoration(
labelText: '输入食物名称',
),
onSubmitted: _analyzeFood,
),
SizedBox(height: 20),
Text(_nutritionInfo),
],
),
),
);
}
}