Home > Net >  Flutter json api problem, some of data not listening
Flutter json api problem, some of data not listening

Time:07-11

Hello guys i have a small project with flutter. Try to list meals from https://www.themealdb.com/. I wish to list the meals in api. So far so good but the main problem some of the food listed some of are not.

For example Beef category not listening and give me this error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Null' is not a subtype of type 'String'

but vegan category is listening.

screen Page :

class _MealScreenState extends State<MealScreen> {
  List<Meal> mealsIn = [];

  Future<bool> getMealInside() async {
    Uri uri = Uri.parse(
        'https://www.themealdb.com/api/json/v1/1/search.php?s=${widget.names}');
    final response = await http.get(uri);

    if (response.statusCode == 200) {
      final result = mealsJsonFromJson(response.body);
      mealsIn = result.meals;

      setState(() {});

      return true;
    } else {
      return false;
    }
  }

  @override
  void initState() {
    super.initState();
    getMealInside();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.names),
      ),
      body: ListView.separated(
        itemBuilder: (context, index) {
          final mealsOut = mealsIn[index];
          return ListTile(
            title: Text(mealsOut.strMeal != null
                ? mealsOut.strMeal.toString()
                : 'Loading'),
            leading: Image.network(mealsOut.strMealThumb),
          );
        },
        separatorBuilder: (context, index) => Divider(),
        itemCount: mealsIn.length
      ),
    );
  }
}

model page:

import 'dart:convert';

MealData mealDataFromJson(String str) => MealData.fromJson(json.decode(str));
String mealDataToJson(MealData data) => json.encode(data.toJson());

class MealData {
  MealData({
    required this.categories,
  });

  List<Category> categories;

  factory MealData.fromJson(Map<String, dynamic> json) => MealData(
    categories: List<Category>.from(json["categories"].map((x) => Category.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "categories": List<dynamic>.from(categories.map((x) => x.toJson())),
  };

class Category {
  Category({
    required this.idCategory,
    required this.strCategory,
    required this.strCategoryThumb,
    required this.strCategoryDescription,
  });

  String idCategory;
  String strCategory;
  String strCategoryThumb;
  String strCategoryDescription;

  factory Category.fromJson(Map<String, dynamic> json) => Category(
    idCategory: json["idCategory"],
    strCategory: json["strCategory"],
    strCategoryThumb: json["strCategoryThumb"],
    strCategoryDescription: json["strCategoryDescription"],
  );

  Map<String, dynamic> toJson() => {
    "idCategory": idCategory,
    "strCategory": strCategory,
    "strCategoryThumb": strCategoryThumb,
    "strCategoryDescription": strCategoryDescription,
  };
}

Beef

Vegan

CodePudding user response:

You have to add null check for each keys : for Category class

factory Category.fromJson(Map<String, dynamic> json) => Category(
    idCategory: json["idCategory"] ?? "",
    strCategory: json["strCategory"] ?? "",
    strCategoryThumb: json["strCategoryThumb"] ?? "",
    strCategoryDescription: json["strCategoryDescription"] ?? "",
  );
  • Related