Skip to content
CARP Docs
Ask AISystemLightDark
On this page

You are reading the docs for Health 13.x, an older version. Go to 14.x, the latest version.

Nutrition

Write meals with macronutrients, micronutrients, caffeine and water using writeMeal.

Copy MarkdownOpen inOpen in GitHubView as MarkdownOpen in Scira AIOpen in ChatGPTOpen in ClaudeOpen in Cursor

writeMeal writes a meal as a NUTRITION record with its meal type, name and nutrient values. Pass only the nutrients you have.

Signature

Future<bool> writeMeal({
  required MealType mealType,
  required DateTime startTime,
  required DateTime endTime,
  String? clientRecordId,
  double? clientRecordVersion,
  double? caloriesConsumed,
  double? carbohydrates,
  double? protein,
  double? fatTotal,
  String? name,
  double? caffeine,
  // ... vitamins, minerals, cholesterol, fat types, fiber, sugar and water
  RecordingMethod recordingMethod = RecordingMethod.automatic,
})

Core parameters

ParameterTypeRequiredDefaultDescription
mealTypeMealTypeYes—Breakfast, lunch, dinner, snack or unknown
startTimeDateTimeYes—When the meal was consumed
endTimeDateTimeYes—When the meal ended. A value before startTime throws an ArgumentError. On Android, it must be after startTime, or writeMeal returns false.
nameString?No—Meal name or description. On iOS, writeMeal throws a PlatformException without it.
clientRecordIdString?No—Client record ID, applied only together with clientRecordVersion (Android only)
clientRecordVersiondouble?No—Client record version, applied only together with clientRecordId (Android only)
recordingMethodRecordingMethodNoRecordingMethod.automaticHow the meal was recorded. On iOS, a value other than manual or automatic throws an ArgumentError. On Android, manual is stored as actively recorded and active as manual entry.

Macronutrients

ParameterTypeUnitDescription
caloriesConsumeddouble?kcalTotal energy
proteindouble?gramsProtein content
carbohydratesdouble?gramsCarbohydrates
fatTotaldouble?gramsTotal fat
fiberdouble?gramsDietary fiber
sugardouble?gramsSugars

Write a meal

// Simple meal with macros
await health.writeMeal(
  startTime: start,
  endTime: end,
  mealType: MealType.BREAKFAST,
  name: 'Oatmeal with berries',
  caloriesConsumed: 350.0,
  protein: 12.0,
  carbohydrates: 58.0,
  fatTotal: 8.0,
);

// Lunch with detailed macros
await health.writeMeal(
  startTime: start,
  endTime: end,
  mealType: MealType.LUNCH,
  name: 'Grilled chicken salad',
  caloriesConsumed: 450.0,
  protein: 35.0,
  carbohydrates: 25.0,
  fatTotal: 20.0,
  fiber: 8.0,
  sugar: 5.0,
);

Meal types

enum MealType {
  BREAKFAST,
  LUNCH,
  DINNER,
  SNACK,
  UNKNOWN,
}

// Usage
await health.writeMeal(
  startTime: start,
  endTime: end,
  mealType: MealType.SNACK,
  name: 'Apple with peanut butter',
  caloriesConsumed: 180.0,
);

Micronutrients

writeMeal supports many micronutrients, all in grams:

await health.writeMeal(
  mealType: MealType.BREAKFAST,
  startTime: start,
  endTime: end,
  name: 'Fortified cereal',
  caloriesConsumed: 250.0,
  
  // Vitamins
  vitaminA: 0.0005,        // 500 mcg
  vitaminC: 0.06,          // 60 mg
  vitaminD: 0.00001,       // 10 mcg
  vitaminE: 0.015,         // 15 mg
  vitaminK: 0.00008,       // 80 mcg
  b1Thiamin: 0.0012,       // 1.2 mg
  b2Riboflavin: 0.0013,    // 1.3 mg
  b3Niacin: 0.016,         // 16 mg
  b6Pyridoxine: 0.0014,    // 1.4 mg
  b12Cobalamin: 0.0000024, // 2.4 mcg
  b9Folate: 0.0004,        // 400 mcg
  
  // Minerals
  calcium: 0.3,            // 300 mg
  iron: 0.008,             // 8 mg
  magnesium: 0.1,          // 100 mg
  phosphorus: 0.25,        // 250 mg
  potassium: 0.4,          // 400 mg
  sodium: 0.2,             // 200 mg
  zinc: 0.011,             // 11 mg
);

writeMeal does not store b1Thiamin on either platform: it sends the value under a key that neither platform reads.

For the full parameter list, see writeMeal in the API reference.

Caffeine, water and fat breakdown

// Caffeine tracking
await health.writeMeal(
  startTime: start,
  endTime: end,
  name: 'Coffee',
  mealType: MealType.BREAKFAST,
  caloriesConsumed: 5.0,
  caffeine: 0.095, // 95 mg
);

// Water tracking (iOS only)
await health.writeMeal(
  mealType: MealType.UNKNOWN,
  startTime: start,
  endTime: end,
  name: 'Water',
  water: 500.0, // ml
);

// Fat breakdown
await health.writeMeal(
  mealType: MealType.BREAKFAST,
  startTime: start,
  endTime: end,
  name: 'Avocado toast',
  caloriesConsumed: 320.0,
  fatTotal: 18.0,
  fatSaturated: 2.5,        // Saturated fat (g)
  fatMonounsaturated: 12.0,  // Monounsaturated fat (g)
  fatPolyunsaturated: 2.0,   // Polyunsaturated fat (g)
  cholesterol: 0.0,          // g
);

On Android, writeMeal ignores water. To log water on both platforms, write WATER in liters with writeHealthData and an endTime after startTime. See Numeric data.

Examples

Meal logger

class MealLogger {
  final Health health;
  
  MealLogger(this.health);
  
  Future<bool> logMeal({
    required String name,
    required MealType type,
    DateTime? consumedAt,
    double? calories,
    double? protein,
    double? carbs,
    double? fat,
    double? fiber,
    double? sugar,
  }) async {
    final endTime = consumedAt ?? DateTime.now();
    return await health.writeMeal(
      startTime: endTime.subtract(const Duration(minutes: 30)),
      endTime: endTime,
      mealType: type,
      name: name,
      caloriesConsumed: calories,
      protein: protein,
      carbohydrates: carbs,
      fatTotal: fat,
      fiber: fiber,
      sugar: sugar,
    );
  }
  
  Future<void> logDailyMeals() async {
    final today = DateTime.now();
    
    // Breakfast
    await logMeal(
      name: 'Scrambled eggs with toast',
      type: MealType.BREAKFAST,
      consumedAt: DateTime(today.year, today.month, today.day, 8, 0),
      calories: 400,
      protein: 24,
      carbs: 35,
      fat: 18,
    );
    
    // Lunch
    await logMeal(
      name: 'Chicken wrap',
      type: MealType.LUNCH,
      consumedAt: DateTime(today.year, today.month, today.day, 12, 30),
      calories: 500,
      protein: 32,
      carbs: 48,
      fat: 18,
    );
    
    // Dinner
    await logMeal(
      name: 'Salmon with vegetables',
      type: MealType.DINNER,
      consumedAt: DateTime(today.year, today.month, today.day, 19, 0),
      calories: 550,
      protein: 38,
      carbs: 42,
      fat: 22,
    );
  }
}

Log servings of a recipe

class Recipe {
  final String name;
  final double servings;
  final Map<String, double> nutrition;
  
  Recipe({
    required this.name,
    required this.servings,
    required this.nutrition,
  });
  
  Future<bool> logServing(Health health, double servingSize) async {
    final multiplier = servingSize / servings;
    final now = DateTime.now();
    
    return await health.writeMeal(
      mealType: MealType.UNKNOWN,
      startTime: now.subtract(const Duration(minutes: 30)),
      endTime: now,
      name: name,
      caloriesConsumed: (nutrition['calories'] ?? 0) * multiplier,
      protein: (nutrition['protein'] ?? 0) * multiplier,
      carbohydrates: (nutrition['carbs'] ?? 0) * multiplier,
      fatTotal: (nutrition['fat'] ?? 0) * multiplier,
    );
  }
}

// Usage
final grilledChicken = Recipe(
  name: 'Grilled Chicken Breast',
  servings: 4.0,
  nutrition: {
    'calories': 660.0,
    'protein': 120.0,
    'carbs': 0.0,
    'fat': 18.0,
  },
);

await grilledChicken.logServing(health, 1.0); // Log 1 serving

Calculate macros

class MacroCalculator {
  // Standard calorie values per gram
  static const double caloriesPerGramProtein = 4.0;
  static const double caloriesPerGramCarbs = 4.0;
  static const double caloriesPerGramFat = 9.0;
  
  static double calculateTotalCalories({
    double? protein,
    double? carbs,
    double? fat,
  }) {
    return (protein ?? 0) * caloriesPerGramProtein +
           (carbs ?? 0) * caloriesPerGramCarbs +
           (fat ?? 0) * caloriesPerGramFat;
  }
  
  static Map<String, double> calculateMacroPercentages({
    required double protein,
    required double carbs,
    required double fat,
  }) {
    final totalCalories = calculateTotalCalories(
      protein: protein,
      carbs: carbs,
      fat: fat,
    );
    
    if (totalCalories == 0) {
      return {'protein': 0, 'carbs': 0, 'fat': 0};
    }
    
    return {
      'protein': (protein * caloriesPerGramProtein / totalCalories * 100),
      'carbs': (carbs * caloriesPerGramCarbs / totalCalories * 100),
      'fat': (fat * caloriesPerGramFat / totalCalories * 100),
    };
  }
}

// Usage
final macros = MacroCalculator.calculateMacroPercentages(
  protein: 30,
  carbs: 40,
  fat: 15,
);

print('Protein: ${macros['protein']?.toStringAsFixed(1)}%');
print('Carbs: ${macros['carbs']?.toStringAsFixed(1)}%');
print('Fat: ${macros['fat']?.toStringAsFixed(1)}%');

Default meal times

class MealTiming {
  static DateTime breakfast([DateTime? date]) {
    final d = date ?? DateTime.now();
    return DateTime(d.year, d.month, d.day, 8, 0);
  }
  
  static DateTime morningSnack([DateTime? date]) {
    final d = date ?? DateTime.now();
    return DateTime(d.year, d.month, d.day, 10, 30);
  }
  
  static DateTime lunch([DateTime? date]) {
    final d = date ?? DateTime.now();
    return DateTime(d.year, d.month, d.day, 12, 30);
  }
  
  static DateTime afternoonSnack([DateTime? date]) {
    final d = date ?? DateTime.now();
    return DateTime(d.year, d.month, d.day, 15, 30);
  }
  
  static DateTime dinner([DateTime? date]) {
    final d = date ?? DateTime.now();
    return DateTime(d.year, d.month, d.day, 19, 0);
  }
}

// Usage
await health.writeMeal(
  startTime: MealTiming.breakfast(),
  endTime: MealTiming.breakfast().add(const Duration(minutes: 30)),
  mealType: MealType.BREAKFAST,
  name: 'Morning oatmeal',
  caloriesConsumed: 350,
);

Platform differences

AndroidiOS
  • Meals are stored as nutrition records in Health Connect.
  • Every nutrient except water and b1Thiamin is stored.
  • Requires the Health Connect SDK.
  • Compatible with nutrition tracking apps.
  • Meals are stored as a complete nutrition record.
  • b1Thiamin and fatTransMonoenoic are not stored, and fatUnsaturated is stored as monounsaturated fat.
  • Data appears in the Apple Health app.
  • HealthKit throws an exception for a meal without nutrients, which crashes the app. Pass at least one nutrient other than b1Thiamin and fatTransMonoenoic.

Quick links

Page · DocumentationCARP DocumentationPage · DocumentationIntroductionPage · DocumentationQuickstartPage · DocumentationTerminologyPage · DocumentationArchitecture