skip to Main Content

I am trying to write a model but i keep getting this error. Here is the code.

import 'package:flutter/material.dart';

class CardModel {
late List<CardResults> results;

CardModel({ required this.results});

CardModel.fromJson(Map<String, dynamic> json) {
if (json['cardResults'] != null) {
  results = List<CardResults>();
  json['cardResults'].forEach((v) {
    results.add(CardResults.fromJson(v));
  });
  }
 }
}

3

Answers


  1. Since you are getting the list of results from a JSON, you can map get the model list like this:

    class CardModel {
    //assuming your list is a list of strings
    List<String> results;
    
    CardModel({required this.results});
    
    factory CardModel.fromJson(Map<String, dynamic> json) {
      if (json['cardResults'] != null) {
      return CardModel(
          results: List<String>.from(json["cardResults"].map((x) => x)));
     }
     // return an empty list if cardResults is empty
     return CardModel(results: []);
     }
    } 
    
    Login or Signup to reply.
  2. First, List type doesn’t have a default constructor so doing List() is not possible. So, instead you can create an empty list using <CardResults>[] or List<CardResults>.empty().

    You can learn more about available constructors for List type here.


    Second, you can optimize your code and instead of creating an empty list and calling add for each item you can use map method, like:

    CardModel.fromJson(Map<String, dynamic> json) {
      if (json['cardResults'] != null) {
        results = json['cardResults'].map<CardResults>((v) => CardResults.fromJson(v)).toList();
      }
    }
    

    You can learn more about map method here.


    Third, instead of marking a property as late you can make it final and use factory constructor to instantiate an object. Finally, your CardModel should look like this:

    class CardModel {
      final List<CardResults> results;
    
      CardModel({required this.results});
    
      factory CardModel.fromJson(Map<String, dynamic> json) {
        return CardModel(
          results: json['cardResults']?.map<CardResults>((v) => CardResults.fromJson(v)).toList() ?? [],
        );
      }
    }
    

    You can learn more about factory constructors here.

    Login or Signup to reply.
  3. List<CardResults>() is no longer valid Dart code as of Dart 3.0.
    See https://github.com/dart-lang/sdk/issues/49529 for details.

    You can instead use <CardResults>[]. But personally, I prefer creating the completed list at the declaration, rather than creating an empty list and building it up.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search