USDA FoodData Central API Get Food Nutrients in your Flutter App.

USDA FoodData Central API Get Food Nutrients in your Flutter App.(updated 8/13/2022)






Friends, today in this article we will teach you how you can use the USDA Food Data Central API in your flutter app. In this app, we will have a food list And we want to get the nutrients of each food from the API. We will receive data in JSON format. To use that data we have to convert that JSON to model data class then show them on the details screen.

Add this to your package’s pubspec.yaml file:

http: ^0.13.5

If you got an error while Pub get please change your (flutter_lints) in pubspec.yaml to flutter_lints:👇 without version.

flutter_lints:



This is our file: main.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import 'package:flutter/material.dart';

import 'homeScreen.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {

return HomeScreen();
}
}

Here is our first Screen UI file: homeScreen.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import 'package:flutter/material.dart';
import '/foodlist.dart';

import 'detailScreen.dart';

class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);

@override
_HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
var foodList = FoodList(
name: '',
foodCategory: '',
id: 0,
);
List<FoodList> _foodList = [];
@override
void initState() {
_foodList = foodList.foodList();
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Food Nutrients",
style: TextStyle(fontSize: 28),
),
),
body: ListView.builder(
itemCount: _foodList.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(_foodList[index].id)),
);
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${_foodList[index].name}",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.black54),
),
Text(
"${_foodList[index].foodCategory}",
style: TextStyle(fontSize: 16, color: Colors.black38),
),
],
),
),
);
}),
);
}
}

Here is the foodlist.dart file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class FoodList {
final int id;
final String name;
final String foodCategory;

FoodList({
required this.id,
required this.name,
required this.foodCategory,
});

List<FoodList> foodList() {
return [
FoodList(
id: 1102670,
name: 'Mango',
foodCategory: 'Fruit',
),
FoodList(
id: 1102879,
name: 'Potato',
foodCategory: 'vegetable',
),
FoodList(
id: 1103528,
name: 'Okra',
foodCategory: 'vegetable',
),
FoodList(
id: 1102653,
name: 'Banana',
foodCategory: 'Fruit',
),
FoodList(
id: 1102597,
name: 'Orange',
foodCategory: 'Fruit',
),
FoodList(
id: 1100534,
name: 'Peanut',
foodCategory: 'Nuts',
),
FoodList(
id: 1102702,
name: 'Blueberries',
foodCategory: 'Fruit',
),
FoodList(
id: 1102644,
name: 'Apple',
foodCategory: 'Fruit',
)
];
}
}

This is our model class: foodmodel.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// To parse this JSON data, do
//
// final foodData = foodDataFromMap(jsonString);

import 'dart:convert';

FoodData foodDataFromMap(String str) => FoodData.fromMap(json.decode(str));

String foodDataToMap(FoodData data) => json.encode(data.toMap());

class FoodData {
FoodData({
this.wweiaFoodCategory,
this.description,
this.foodAttributes,
this.foodCode,
this.inputFoods,
this.startDate,
this.endDate,
this.foodComponents,
this.foodClass,
this.fdcId,
this.publicationDate,
this.foodNutrients,
this.foodPortions,
this.dataType,
});

WweiaFoodCategory? wweiaFoodCategory;
String? description;
List<FoodAttribute>? foodAttributes;
String? foodCode;
List<InputFood>? inputFoods;
String? startDate;
String? endDate;
List<dynamic>? foodComponents;
String? foodClass;
String? fdcId;
String? publicationDate;
List<FoodNutrient>? foodNutrients;
List<FoodPortion>? foodPortions;
String? dataType;

FoodData copyWith({
WweiaFoodCategory? wweiaFoodCategory,
String? description,
List<FoodAttribute>? foodAttributes,
String? foodCode,
List<InputFood>? inputFoods,
String? startDate,
String? endDate,
List<dynamic>? foodComponents,
String? foodClass,
String? fdcId,
String? publicationDate,
List<FoodNutrient>? foodNutrients,
List<FoodPortion>? foodPortions,
String? dataType,
}) =>
FoodData(
wweiaFoodCategory: wweiaFoodCategory ?? this.wweiaFoodCategory,
description: description ?? this.description,
foodAttributes: foodAttributes ?? this.foodAttributes,
foodCode: foodCode ?? this.foodCode,
inputFoods: inputFoods ?? this.inputFoods,
startDate: startDate ?? this.startDate,
endDate: endDate ?? this.endDate,
foodComponents: foodComponents ?? this.foodComponents,
foodClass: foodClass ?? this.foodClass,
fdcId: fdcId ?? this.fdcId,
publicationDate: publicationDate ?? this.publicationDate,
foodNutrients: foodNutrients ?? this.foodNutrients,
foodPortions: foodPortions ?? this.foodPortions,
dataType: dataType ?? this.dataType,
);

factory FoodData.fromMap(Map<String, dynamic> json) => FoodData(
wweiaFoodCategory: WweiaFoodCategory.fromMap(json["wweiaFoodCategory"]),
description: json["description"],
foodAttributes: List<FoodAttribute>.from(json["foodAttributes"].map((x) => FoodAttribute.fromMap(x))),
foodCode: json["foodCode"],
inputFoods: List<InputFood>.from(json["inputFoods"].map((x) => InputFood.fromMap(x))),
startDate: json["startDate"],
endDate: json["endDate"],
foodComponents: List<dynamic>.from(json["foodComponents"].map((x) => x)),
foodClass: json["foodClass"],
fdcId: json["fdcId"].toString(),
publicationDate: json["publicationDate"],
foodNutrients: List<FoodNutrient>.from(json["foodNutrients"].map((x) => FoodNutrient.fromMap(x))),
foodPortions: List<FoodPortion>.from(json["foodPortions"].map((x) => FoodPortion.fromMap(x))),
dataType: json["dataType"],
);

Map<String, dynamic> toMap() => {
"wweiaFoodCategory": wweiaFoodCategory!.toMap(),
"description": description,
"foodAttributes": List<dynamic>.from(foodAttributes!.map((x) => x.toMap())),
"foodCode": foodCode,
"inputFoods": List<dynamic>.from(inputFoods!.map((x) => x.toMap())),
"startDate": startDate,
"endDate": endDate,
"foodComponents": List<dynamic>.from(foodComponents!.map((x) => x)),
"foodClass": foodClass,
"fdcId": fdcId,
"publicationDate": publicationDate,
"foodNutrients": List<dynamic>.from(foodNutrients!.map((x) => x.toMap())),
"foodPortions": List<dynamic>.from(foodPortions!.map((x) => x.toMap())),
"dataType": dataType,
};
}

class FoodAttribute {
FoodAttribute({
this.id,
this.value,
this.name,
this.foodAttributeType,
});

int? id;
String? value;
String? name;
FoodAttributeType? foodAttributeType;

FoodAttribute copyWith({
int? id,
String? value,
String? name,
FoodAttributeType? foodAttributeType,
}) =>
FoodAttribute(
id: id ?? this.id,
value: value ?? this.value,
name: name ?? this.name,
foodAttributeType: foodAttributeType ?? this.foodAttributeType,
);

factory FoodAttribute.fromMap(Map<String, dynamic> json) => FoodAttribute(
id: json["id"],
value: json["value"],
name: json["name"],
foodAttributeType: FoodAttributeType.fromMap(json["foodAttributeType"]),
);

Map<String, dynamic> toMap() => {
"id": id,
"value": value,
"name": name,
"foodAttributeType": foodAttributeType!.toMap(),
};
}

class FoodAttributeType {
FoodAttributeType({
this.id,
this.name,
this.description,
});

int? id;
String? name;
String? description;

FoodAttributeType copyWith({
int? id,
String? name,
String? description,
}) =>
FoodAttributeType(
id: id ?? this.id,
name: name ?? this.name,
description: description ?? this.description,
);

factory FoodAttributeType.fromMap(Map<String, dynamic> json) => FoodAttributeType(
id: json["id"],
name: json["name"],
description: json["description"],
);

Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"description": description,
};
}

class FoodNutrient {
FoodNutrient({
this.nutrient,
this.type,
this.id,
this.amount,
});

Nutrient? nutrient;
Type? type;
int? id;
double? amount;

FoodNutrient copyWith({
Nutrient? nutrient,
Type? type,
int? id,
double? amount,
}) =>
FoodNutrient(
nutrient: nutrient ?? this.nutrient,
type: type ?? this.type,
id: id ?? this.id,
amount: amount ?? this.amount,
);

factory FoodNutrient.fromMap(Map<String, dynamic> json) => FoodNutrient(
nutrient: Nutrient.fromMap(json["nutrient"]),
type: typeValues.map[json["type"]],
id: json["id"] == null ? null : json["id"],
amount: json["amount"] == null ? null : json["amount"].toDouble(),
);

Map<String, dynamic> toMap() => {
"nutrient": nutrient!.toMap(),
"type": typeValues.reverse![type!],
"id": id == null ? null : id,
"amount": amount == null ? null : amount,
};
}

class Nutrient {
Nutrient({
this.id,
this.number,
this.name,
this.rank,
this.unitName,
});

int? id;
String? number;
String? name;
String? rank;
String? unitName;

Nutrient copyWith({
int? id,
String? number,
String? name,
String? rank,
UnitName? unitName,
}) =>
Nutrient(
id: id ?? this.id,
number: number ?? this.number,
name: name ?? this.name,
rank: rank ?? this.rank,
unitName: unitName as String? ?? this.unitName,
);

factory Nutrient.fromMap(Map<String, dynamic> json) => Nutrient(
id: json["id"],
number: json["number"],
name: json["name"],
rank: json["rank"].toString(),
unitName: json["unitName"],
);

Map<String, dynamic> toMap() => {
"id": id,
"number": number,
"name": name,
"rank": rank,
"unitName": unitNameValues.reverse![unitName as UnitName],
};
}

enum UnitName { G, KCAL, MG, UNIT_NAME_G }

final unitNameValues = EnumValues({
"g": UnitName.G,
"kcal": UnitName.KCAL,
"mg": UnitName.MG,
"µg": UnitName.UNIT_NAME_G
});

enum Type { FOOD_NUTRIENT }

final typeValues = EnumValues({
"FoodNutrient": Type.FOOD_NUTRIENT
});

class FoodPortion {
FoodPortion({
this.id,
this.portionDescription,
this.gramWeight,
this.sequenceNumber,
this.modifier,
this.measureUnit,
});

int? id;
String? portionDescription;
String? gramWeight;
String? sequenceNumber;
String? modifier;
MeasureUnit? measureUnit;

FoodPortion copyWith({
int? id,
String? portionDescription,
String? gramWeight,
String? sequenceNumber,
String? modifier,
MeasureUnit? measureUnit,
}) =>
FoodPortion(
id: id ?? this.id,
portionDescription: portionDescription ?? this.portionDescription,
gramWeight: gramWeight ?? this.gramWeight,
sequenceNumber: sequenceNumber ?? this.sequenceNumber,
modifier: modifier ?? this.modifier,
measureUnit: measureUnit ?? this.measureUnit,
);

factory FoodPortion.fromMap(Map<String, dynamic> json) => FoodPortion(
id: json["id"],
portionDescription: json["portionDescription"],
gramWeight: json["gramWeight"].toString(),
sequenceNumber: json["sequenceNumber"].toString(),
modifier: json["modifier"],
measureUnit: MeasureUnit.fromMap(json["measureUnit"]),
);

Map<String, dynamic> toMap() => {
"id": id,
"portionDescription": portionDescription,
"gramWeight": gramWeight,
"sequenceNumber": sequenceNumber,
"modifier": modifier,
"measureUnit": measureUnit!.toMap(),
};
}

class MeasureUnit {
MeasureUnit({
this.id,
this.name,
this.abbreviation,
});

int? id;
String? name;
String? abbreviation;

MeasureUnit copyWith({
int? id,
String? name,
String? abbreviation,
}) =>
MeasureUnit(
id: id ?? this.id,
name: name ?? this.name,
abbreviation: abbreviation ?? this.abbreviation,
);

factory MeasureUnit.fromMap(Map<String, dynamic> json) => MeasureUnit(
id: json["id"],
name: json["name"],
abbreviation: json["abbreviation"],
);

Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"abbreviation": abbreviation,
};
}

class InputFood {
InputFood({
this.id,
this.foodDescription,
this.ingredientDescription,
this.ingredientWeight,
this.portionCode,
this.portionDescription,
this.sequenceNumber,
this.ingredientCode,
this.unit,
this.amount,
});

int? id;
String? foodDescription;
String? ingredientDescription;
String? ingredientWeight;
String? portionCode;
String? portionDescription;
String? sequenceNumber;
String? ingredientCode;
String? unit;
String? amount;

InputFood copyWith({
int? id,
String? foodDescription,
String? ingredientDescription,
String? ingredientWeight,
String? portionCode,
String? portionDescription,
String? sequenceNumber,
String? ingredientCode,
String? unit,
String? amount,
}) =>
InputFood(
id: id ?? this.id,
foodDescription: foodDescription ?? this.foodDescription,
ingredientDescription: ingredientDescription ?? this.ingredientDescription,
ingredientWeight: ingredientWeight ?? this.ingredientWeight,
portionCode: portionCode ?? this.portionCode,
portionDescription: portionDescription ?? this.portionDescription,
sequenceNumber: sequenceNumber ?? this.sequenceNumber,
ingredientCode: ingredientCode ?? this.ingredientCode,
unit: unit ?? this.unit,
amount: amount ?? this.amount,
);

factory InputFood.fromMap(Map<String, dynamic> json) => InputFood(
id: json["id"],
foodDescription: json["foodDescription"],
ingredientDescription: json["ingredientDescription"],
ingredientWeight: json["ingredientWeight"].toString(),
portionCode: json["portionCode"],
portionDescription: json["portionDescription"],
sequenceNumber: json["sequenceNumber"].toString(),
ingredientCode: json["ingredientCode"].toString(),
unit: json["unit"],
amount: json["amount"].toString(),
);

Map<String, dynamic> toMap() => {
"id": id,
"foodDescription": foodDescription,
"ingredientDescription": ingredientDescription,
"ingredientWeight": ingredientWeight,
"portionCode": portionCode,
"portionDescription": portionDescription,
"sequenceNumber": sequenceNumber,
"ingredientCode": ingredientCode,
"unit": unit,
"amount": amount,
};
}

class WweiaFoodCategory {
WweiaFoodCategory({
this.wweiaFoodCategoryCode,
this.wweiaFoodCategoryDescription,
});

int? wweiaFoodCategoryCode;
String? wweiaFoodCategoryDescription;

WweiaFoodCategory copyWith({
int? wweiaFoodCategoryCode,
String? wweiaFoodCategoryDescription,
}) =>
WweiaFoodCategory(
wweiaFoodCategoryCode: wweiaFoodCategoryCode ?? this.wweiaFoodCategoryCode,
wweiaFoodCategoryDescription: wweiaFoodCategoryDescription ?? this.wweiaFoodCategoryDescription,
);

factory WweiaFoodCategory.fromMap(Map<String, dynamic> json) => WweiaFoodCategory(
wweiaFoodCategoryCode: json["wweiaFoodCategoryCode"],
wweiaFoodCategoryDescription: json["wweiaFoodCategoryDescription"],
);

Map<String, dynamic> toMap() => {
"wweiaFoodCategoryCode": wweiaFoodCategoryCode,
"wweiaFoodCategoryDescription": wweiaFoodCategoryDescription,
};
}

class EnumValues<T> {
Map<String, T> map;
Map<T, String>? reverseMap;

EnumValues(this.map);

Map<T, String>? get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}

This is our detailScreen.dart file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'models/foodmodel.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

class DetailScreen extends StatefulWidget {
final int id;
DetailScreen(this.id);
@override
_DetailScreenState createState() => _DetailScreenState();
}

class _DetailScreenState extends State<DetailScreen> {
late FoodData foodData;
bool loading = true;
@override
void initState() {
fetchData();
super.initState();
}

Future<void> fetchData() async {
var url = Uri.parse(
"https://api.nal.usda.gov/fdc/v1/food/${widget.id}?api_key=[Please add here your API key without square brackets ]");
var response = await http.get(url);
if (response.statusCode == 200) {
var decodedResponse = convert.jsonDecode(response.body);
print('===================$decodedResponse');
foodData = FoodData.fromMap(decodedResponse);
print('===================$foodData');
setState(() {
loading = false;
});
} else {
throw Exception('Failed to load data');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: loading
? SizedBox.shrink()
: FittedBox(
child: Text(
"${foodData.description}",
style: TextStyle(fontSize: 28),
),
),
),
body: Container(
child: loading
? Center(child: CircularProgressIndicator())
: Column(
children: [
Text(
"Portion: per 100g",
style: TextStyle(fontSize: 25),
),
Container(
child: Expanded(
child: ListView.builder(
itemCount: foodData == null
? 0
: foodData.foodNutrients!.length,
itemBuilder: (context, index) {
var nutrient =
foodData.foodNutrients![index].nutrient!;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: FittedBox(
alignment: Alignment.topLeft,
fit: BoxFit.scaleDown,
child: Text(
foodData.foodNutrients![index].amount ==
null
? " ${nutrient.name}: "
: "${nutrient.name}: ${foodData.foodNutrients![index].amount} ${foodData.foodNutrients![index].amount == null ? "" : nutrient.unitName}",
style: foodData.foodNutrients![index]
.amount ==
null
? TextStyle(
backgroundColor: Colors.green,
fontWeight: FontWeight.w600,
fontSize: 23,
)
: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
),
),
Container(
height: 1,
color: Colors.black54,
),
],
);
}),
),
)
],
),
),
);
}
}

Popular posts from this blog

In-App Purchase with null safety in Flutter 2.5.

How to add In-App Purchase subscription in Flutter.

Flutter Native Ad Templates Implementation