1

Occurs exception when I get the chapter list. So how can I solve this problem? Please help.

Here is my API response.

{
  "success": 1,
  "chapter": [
    {
      "chapter_id": "609cb13f497e3",
      "chapter_name": "test",
      "subject_id": "5e32874c714fa",
      "medium_id": "5d15938aa1344",
      "standard_id": "5d1594e283e1a",
      "material": null,
      "textbook": null,
      "test_paper": null,
      "test_paper_solution": null,
      "subject_memory_map": null,
      "active": "1"
    }
  ]
}

The model class which I created in chapter_model.dart file.

// To parse this JSON data, do
//
//     final chapterBySubjectModel = chapterBySubjectModelFromJson(jsonString);

import 'dart:convert';

ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));

String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());

class ChapterBySubjectModel {
    ChapterBySubjectModel({
        required this.success,
        required this.chapter,
    });

    int success;
    List<Chapter> chapter;

    factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
        success: json["success"],
        chapter: List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
    );

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

class Chapter {
    Chapter({
        required this.chapterId,
        required this.chapterName,
        required this.subjectId,
        required this.mediumId,
        required this.standardId,
        this.material,
        this.textbook,
        this.testPaper,
        this.testPaperSolution,
        this.subjectMemoryMap,
        required this.active,
    });

    String chapterId;
    String chapterName;
    String subjectId;
    String mediumId;
    String standardId;
    dynamic material;
    dynamic textbook;
    dynamic testPaper;
    dynamic testPaperSolution;
    dynamic subjectMemoryMap;
    String active;

    factory Chapter.fromJson(Map<String, dynamic> json) => Chapter(
        chapterId: json["chapter_id"],
        chapterName: json["chapter_name"],
        subjectId: json["subject_id"],
        mediumId: json["medium_id"],
        standardId: json["standard_id"],
        material: json["material"],
        textbook: json["textbook"],
        testPaper: json["test_paper"],
        testPaperSolution: json["test_paper_solution"],
        subjectMemoryMap: json["subject_memory_map"],
        active: json["active"],
    );

    Map<String, dynamic> toJson() => {
        "chapter_id": chapterId,
        "chapter_name": chapterName,
        "subject_id": subjectId,
        "medium_id": mediumId,
        "standard_id": standardId,
        "material": material,
        "textbook": textbook,
        "test_paper": testPaper,
        "test_paper_solution": testPaperSolution,
        "subject_memory_map": subjectMemoryMap,
        "active": active,
    };
}

Method which i Created in api_manager.dart file.

Future<List<Chapter>> getChapterBySubject() async {
    final chapterUrl =
        '$baseUrl/subject/get_by_user_plan?user_id=609cab2cd5b6c&order_id=1620889722609cd07a601af469889697609cab2cd5b6c&standard_id=5d1594e283e1a&medium_id=5d15938aa1344';
    final response = await http.get(Uri.parse(chapterUrl));
    if (response.statusCode == 200) {
      final chapterData = chapterBySubjectModelFromJson(response.body);

      final List<Chapter> chapters = chapterData.chapter;
      print(chapters);
      return chapters;
    } else {
      return <Chapter>[];
    }
  }

And view as below in chapter_widget.dart file.

class _ChapterWidgetState extends State<ChapterWidget> {
  late bool _loading;
  var _chapters = <Chapter>[];

  @override
  void initState() {
    super.initState();
    _loading = true;

    ApiManager().getChapterBySubject().then((chapters) {
      setState(() {
        _chapters = chapters;
        _loading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: null == _chapters ? 0 : _chapters.length,
        //itemCount: _chapters.length,
        itemBuilder: (context, index) {
          Chapter chapter = _chapters[index];

          return Container(
            padding: EdgeInsets.all(8),
            child: Card(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20.0),
                child: InkWell(
                  //child: Image.asset("assets/logos/listbackground.png"),
                  child: Text(chapter.chapterName),
                ),
              ),
            ),
          );
        });

   
  }
}

It throws an Exception in Model Class in below line.

List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),

Exception Shown in image

Akif
  • 7,098
  • 7
  • 27
  • 53
Dhaval Chaudhari
  • 417
  • 8
  • 22

1 Answers1

0

You set chapter as required but it seems API says it can be null. So, you should convert your parameters from required to nullable like this:

import 'dart:convert';

ChapterBySubjectModel chapterBySubjectModelFromJson(String str) => ChapterBySubjectModel.fromJson(json.decode(str));

String chapterBySubjectModelToJson(ChapterBySubjectModel data) => json.encode(data.toJson());

class ChapterBySubjectModel {
    ChapterBySubjectModel({
        this.success,
        this.chapter,
    });

    int success;
    List<Chapter> chapter;

    factory ChapterBySubjectModel.fromJson(Map<String, dynamic> json) => ChapterBySubjectModel(
        success: json["success"] == null ? null : json["success"],
        chapter: json["chapter"] == null ? null : List<Chapter>.from(json["chapter"].map((x) => Chapter.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "success": success == null ? null : success,
        "chapter": chapter == null ? null : List<Chapter>.from(chapter.map((x) => x)),
    };
}
Akif
  • 7,098
  • 7
  • 27
  • 53