当前位置: 首页 > 知识库问答 >
问题:

Flatter json需要类型为“List”的值,但得到类型为“”的值

班景龙
2023-03-14

大家好,我正在制作一个菜谱应用程序,它显示食物的名称、图像和ingredants,所以我制作了一个简单的主页,制作了requst和一个类,该类提供了我从spooncular使用的这个url的数据。通用域名格式:

https://api.spoonacular.com/recipes/complexSearch?apiKey=8fe91444f092411fa6011b71fd6e582d

这是主课

  import 'package:flutter/material.dart';
import 'package:flutter_application_1/recipes.dart';
import 'dart:convert' as cnv;
import 'package:http/http.dart' as http;

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

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

class _HomeScreen extends State<HomeScreen> {
  List<MissedIngredients>? modell;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Food recipe api'),
      ),
      body: modell == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  child: ExpansionTile(
                    title: Text(modell![index].originalName.toString()),
                    children: [
                      Text(modell![index].name.toString()),
                      Container(
                        child:
                            Image.network('modell![index].image.toString()'),
                      )
                    ],
                  ),
                );
              },
              itemCount: modell!.length),
    );
  }

  Future<void> getData() async {
    http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/recipes/complexSearch?apiKey=8fe91444f092411fa6011b71fd6e582d&number=1&query=pizza&fillIngredients=true'));
    print(res.body);
    List<dynamic> body = cnv.jsonDecode(res.body)['missedIngredients'];
    modell = body.map((dynamic item) => MissedIngredients.fromJson(item)).toList();
    setState(() {});
   }
}

这是recipes类i mdae,它使用json连接到dart类网站

  class recipes {
  List<Results> ?results;
  int? offset;
  int? number;
  int? totalResults;

  recipes({this.results, this.offset, this.number, this.totalResults});

  recipes.fromJson(Map<String, dynamic> json) {
    if (json['results'] != null) {
      results = <Results>[];
      json['results'].forEach((v) {
        results!.add(new Results.fromJson(v));
      });
    }
    offset = json['offset'];
    number = json['number'];
    totalResults = json['totalResults'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.results != null) {
      data['results'] = this.results!.map((v) => v.toJson()).toList();
    }
    data['offset'] = this.offset;
    data['number'] = this.number;
    data['totalResults'] = this.totalResults;
    return data;
  }
}

class Results {
  int? id;
  int? usedIngredientCount;
  int? missedIngredientCount;
  List<MissedIngredients> ?missedIngredients;
  int ?likes;
  List<Null>? usedIngredients;
  List<Null>? unusedIngredients;
  String ?title;
  String ?image;
  String ?imageType;

  Results(
      {this.id,
      this.usedIngredientCount,
      this.missedIngredientCount,
      this.missedIngredients,
      this.likes,
      this.usedIngredients,
      this.unusedIngredients,
      this.title,
      this.image,
      this.imageType});

  Results.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    usedIngredientCount = json['usedIngredientCount'];
    missedIngredientCount = json['missedIngredientCount'];
    if (json['missedIngredients'] != null) {
      missedIngredients = <MissedIngredients>[];
      json['missedIngredients'].forEach((v) {
        missedIngredients!.add(new MissedIngredients.fromJson(v));
      });
    }
    title = json['title'];
    image = json['image'];
    imageType = json['imageType'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['usedIngredientCount'] = this.usedIngredientCount;
    data['missedIngredientCount'] = this.missedIngredientCount;
    if (this.missedIngredients != null) {
      data['missedIngredients'] =
          this.missedIngredients!.map((v) => v.toJson()).toList();
    }
    data['likes'] = this.likes;
    
    data['title'] = this.title;
    data['image'] = this.image;
    data['imageType'] = this.imageType;
    return data;
  }
}

class MissedIngredients {
  int ? id;
  double? amount;
  String ?unit;
  String ?unitLong;
  String ?unitShort;
  String? aisle;
  String? name;
  String? original;
  String? originalString;
  String? originalName;
  List<String> ?metaInformation;
  List<String>? meta;
  String ?image;
  String? extendedName;

  MissedIngredients(
      {this.id,
      this.amount,
      this.unit,
      this.unitLong,
      this.unitShort,
      this.aisle,
      this.name,
      this.original,
      this.originalString,
      this.originalName,
      this.metaInformation,
      this.meta,
      this.image,
      this.extendedName});

  MissedIngredients.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    amount = json['amount'];
    unit = json['unit'];
    unitLong = json['unitLong'];
    unitShort = json['unitShort'];
    aisle = json['aisle'];
    name = json['name'];
    original = json['original'];
    originalString = json['originalString'];
    originalName = json['originalName'];
    metaInformation = json['metaInformation'].cast<String>();
    meta = json['meta'].cast<String>();
    image = json['image'];
    extendedName = json['extendedName'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['amount'] = this.amount;
    data['unit'] = this.unit;
    data['unitLong'] = this.unitLong;
    data['unitShort'] = this.unitShort;
    data['aisle'] = this.aisle;
    data['name'] = this.name;
    data['original'] = this.original;
    data['originalString'] = this.originalString;
    data['originalName'] = this.originalName;
    data['metaInformation'] = this.metaInformation;
    data['meta'] = this.meta;
    data['image'] = this.image;
    data['extendedName'] = this.extendedName;
    return data;
  }
}

注意:当我尝试使用结果类(如标题或图像)时,它可以工作,但当我尝试使用MissingRedants类时,它会给我此错误,预期值为'List'类型,但得到'Null'类型的值。如果您想要任何进一步的信息,请询问我的评论,谢谢!

共有1个答案

阳修永
2023-03-14

在您的案例中使用以下方法,

Future<void> getData() async {
    http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/recipes/complexSearch?apiKey=8fe91444f092411fa6011b71fd6e582d&number=1&query=pizza&fillIngredients=true'));
    print(res.body);
    var jsonData = cnv.jsonDecode(res.body);
    modell = jsonData['results'][0]['missedIngredients'].map((dynamic item) => MissedIngredients.fromJson(item)).toList();
    setState(() {});
  }

当您的“结果”列表中有多个数据时,您可以在结果列表数组中找到“错过的配料”列表,

Future<void> getData() async {
    http.Response res = await http.get(Uri.parse('https://api.spoonacular.com/recipes/complexSearch?apiKey=8fe91444f092411fa6011b71fd6e582d&number=1&query=pizza&fillIngredients=true'));
    print(res.body);
    var jsonData = cnv.jsonDecode(res.body);
    List<Results> resultList = jsonData['results'].map(
            (jsonElement) => Results.fromJson(jsonElement)
    ).toList();
    print(resultList[0].missedIngredients.length.toString());
  }
 类似资料: