#json #api #flutter #dart
Вопрос:
Я пытаюсь отобразить название продукта и другие поля из Api, чтобы пользователь мог их видеть. Я могу распечатать весь ответ Json, но я не знаю, как отобразить определенные поля из ответа, используя модель.
Я получаю следующую ошибку:
тип _InternalLinkedHashMap<Строка, динамическая> не является подтипом типа String
Это структура Api CalorieMama
{
"model": "20170209",
"results": [{
"packagedgoods": true,
"group": "Packaged Good",
"items": [{
"nutrition": {
"totalCarbs": 0.875,
"protein": 0.0125,
"calories": 3500,
"sodium": 0.003,
"iron": 9.0E-6,
"sugars": 0.625
},
"name": "Licorice Candy",
"score": 6,
"brand": "Good amp; Plenty",
"servingSizes": [{
"unit": "33.0 pieces",
"servingWeight": 0.04
}]
}, {
"nutrition": {
"totalCarbs": 0.8461538461538461,
"calories": 3333.3333333333335,
"sodium": 0.0023076923076923075,
"iron": 9.23076923076923E-6,
"sugars": 0.5384615384615384
},
"name": "Licorice Candy",
"score": 10,
"brand": "Good amp; Plenty",
"servingSizes": [{
"unit": "33.0 pieces",
"servingWeight": 0.039
}]
}]
}, {
"group": "Bacon",
"items": [{
"score": 87,
"name": "Bacon",
"nutrition": {
"calcium": 1.1000000000000002E-4,
"saturatedFat": 0.13739,
"monounsaturatedFat": 0.18519999999999998,
"sodium": 0.0103,
"totalFat": 0.4178,
"cholesterol": 0.0011,
"iron": 1.4400000000000001E-5,
"polyunsaturatedFat": 0.04548000000000001,
"totalCarbs": 0.014299999999999998,
"protein": 0.37039999999999995,
"potassium": 0.0056500000000000005,
"vitaminA": 1.11E-7,
"calories": 5410
},
"servingSizes": [{
"unit": "1 slice, cooked",
"servingWeight": 0.008
}, {
"unit": "100 g",
"servingWeight": 0.1
}, {
"unit": "1 g",
"servingWeight": 0.001
}, {
"unit": "1 oz",
"servingWeight": 0.0283495
}]
}, {
"generic": true,
"score": 1,
"name": "Bacon (any kind)",
"nutrition": {
"calcium": 1.1000000000000002E-4,
"saturatedFat": 0.13739,
"monounsaturatedFat": 0.18519999999999998,
"sodium": 0.0103,
"totalFat": 0.4178,
"cholesterol": 0.0011,
"iron": 1.4400000000000001E-5,
"polyunsaturatedFat": 0.04548000000000001,
"totalCarbs": 0.014299999999999998,
"protein": 0.37039999999999995,
"potassium": 0.0056500000000000005,
"vitaminA": 1.11E-7,
"calories": 5410
},
"servingSizes": [{
"unit": "1 slice, cooked",
"servingWeight": 0.008
}, {
"unit": "100 g",
"servingWeight": 0.1
}, {
"unit": "1 g",
"servingWeight": 0.001
}, {
"unit": "1 oz",
"servingWeight": 0.0283495
}]
}]
},
{
"group": "Confection",
"items": [{
"score": 77,
"name": "Brownie",
"servingSizes": [{
"unit": "1 brownie (2" square)",
"servingWeight": 0.024
}, {
"unit": "1 oz",
"servingWeight": 0.02835
}, {
"unit": "100 g",
"servingWeight": 0.1
}, {
"unit": "1 g",
"servingWeight": 0.001
}],
"nutrition": {
"calcium": 5.700000000000001E-4,
"vitaminC": 3.0E-6,
"saturatedFat": 0.07318999999999999,
"monounsaturatedFat": 0.10839,
"sodium": 0.0034300000000000003,
"totalFat": 0.291,
"cholesterol": 7.3E-4,
"iron": 1.8399999996000002E-5,
"polyunsaturatedFat": 0.09412000000000001,
"totalCarbs": 0.502,
"protein": 0.062,
"potassium": 0.00176,
"vitaminA": 2.481E-6,
"calories": 4660
}
}]
}
]
}
Это модель
class CalorieMama {
String model;
List<Results> results;
CalorieMama({this.model, this.results});
CalorieMama.fromJson(Map<String, dynamic> json) {
model = json['model'];
if (json['results'] != null) {
results = new List<Results>();
json['results'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['model'] = this.model;
if (this.results != null) {
data['results'] = this.results.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
bool packagedgoods;
String group;
List<Items> items;
Results({this.packagedgoods, this.group, this.items});
Results.fromJson(Map<String, dynamic> json) {
packagedgoods = json['packagedgoods'];
group = json['group'];
if (json['items'] != null) {
items = new List<Items>();
json['items'].forEach((v) {
items.add(new Items.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['packagedgoods'] = this.packagedgoods;
data['group'] = this.group;
if (this.items != null) {
data['items'] = this.items.map((v) => v.toJson()).toList();
}
return data;
}
}
class Items {
Nutrition nutrition;
String name;
int score;
String brand;
List<ServingSizes> servingSizes;
bool generic;
Items(
{this.nutrition,
this.name,
this.score,
this.brand,
this.servingSizes,
this.generic});
Items.fromJson(Map<String, dynamic> json) {
nutrition = json['nutrition'] != null
? new Nutrition.fromJson(json['nutrition'])
: null;
name = json['name'];
score = json['score'];
brand = json['brand'];
if (json['servingSizes'] != null) {
servingSizes = new List<ServingSizes>();
json['servingSizes'].forEach((v) {
servingSizes.add(new ServingSizes.fromJson(v));
});
}
generic = json['generic'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.nutrition != null) {
data['nutrition'] = this.nutrition.toJson();
}
data['name'] = this.name;
data['score'] = this.score;
data['brand'] = this.brand;
if (this.servingSizes != null) {
data['servingSizes'] = this.servingSizes.map((v) => v.toJson()).toList();
}
data['generic'] = this.generic;
return data;
}
}
class Nutrition {
double totalCarbs;
double protein;
double calories;
double sodium;
double iron;
double sugars;
double calcium;
double saturatedFat;
double monounsaturatedFat;
double totalFat;
double cholesterol;
double polyunsaturatedFat;
double potassium;
double vitaminA;
double vitaminC;
Nutrition(
{this.totalCarbs,
this.protein,
this.calories,
this.sodium,
this.iron,
this.sugars,
this.calcium,
this.saturatedFat,
this.monounsaturatedFat,
this.totalFat,
this.cholesterol,
this.polyunsaturatedFat,
this.potassium,
this.vitaminA,
this.vitaminC});
Nutrition.fromJson(Map<String, dynamic> json) {
totalCarbs = json['totalCarbs'];
protein = json['protein'];
calories = json['calories'];
sodium = json['sodium'];
iron = json['iron'];
sugars = json['sugars'];
calcium = json['calcium'];
saturatedFat = json['saturatedFat'];
monounsaturatedFat = json['monounsaturatedFat'];
totalFat = json['totalFat'];
cholesterol = json['cholesterol'];
polyunsaturatedFat = json['polyunsaturatedFat'];
potassium = json['potassium'];
vitaminA = json['vitaminA'];
vitaminC = json['vitaminC'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['totalCarbs'] = this.totalCarbs;
data['protein'] = this.protein;
data['calories'] = this.calories;
data['sodium'] = this.sodium;
data['iron'] = this.iron;
data['sugars'] = this.sugars;
data['calcium'] = this.calcium;
data['saturatedFat'] = this.saturatedFat;
data['monounsaturatedFat'] = this.monounsaturatedFat;
data['totalFat'] = this.totalFat;
data['cholesterol'] = this.cholesterol;
data['polyunsaturatedFat'] = this.polyunsaturatedFat;
data['potassium'] = this.potassium;
data['vitaminA'] = this.vitaminA;
data['vitaminC'] = this.vitaminC;
return data;
}
}
class ServingSizes {
String unit;
double servingWeight;
ServingSizes({this.unit, this.servingWeight});
ServingSizes.fromJson(Map<String, dynamic> json) {
unit = json['unit'];
servingWeight = json['servingWeight'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['unit'] = this.unit;
data['servingWeight'] = this.servingWeight;
return data;
}
}
This is the code to display specific fields from the json response
class DisplayPictureScreen extends StatefulWidget {
final String imagePath;
const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);
_DisplayPictureScreenState createState() => _DisplayPictureScreenState();
}
class _DisplayPictureScreenState extends State<DisplayPictureScreen> {
Dio dio = new Dio();
Future<CalorieMama> imageResult() async {
ImageProperties properties =
await FlutterNativeImage.getImageProperties(widget.imagePath);
File compressedFile = await FlutterNativeImage.compressImage(
widget.imagePath,
targetWidth: 544,
targetHeight: 544);
FormData formData = new FormData.fromMap({
"image": await MultipartFile.fromFile(compressedFile.path),
"type": "image/jpeg"
});
Response response = await dio.post(
"https://api-2445582032290.production.gw.apicast.io/v1/foodrecognition?user_key=$key",
data: formData,
);
Map<String, dynamic> jsonResponse = jsonDecode(response.data);
return CalorieMama.fromJson(jsonResponse);
}
Future<CalorieMama> _showResult() async {
CalorieMama recipes = await imageResult();
return recipes;
}
@override
initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Display the Picture')),
// The image is stored as a file on the device. Use the `Image.file`
// constructor with the given path to display the image.
body: new FutureBuilder(
future: _showResult(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return Text(_showResult().toString());
}
},
)
//Image.file(File(widget.imagePath))
);
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
List<CalorieMama> values = snapshot.data;
return new ListView.builder(
itemCount: values.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
new ListTile(
title: new Text(' item ${values[index].items.toString()}'),
subtitle: new Text(
'package good ${values[index].packagedgoods.toString()}'),
),
new Divider(
height: 2.0,
),
],
);
},
);
}
}