The class 'List' doesn't have an unnamed constructor
Asked Answered
G

3

6

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));
  });
  }
 }
}
Garrettgarrick answered 7/6, 2023 at 23:38 Comment(0)
C
18

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.

Condensed answered 8/6, 2023 at 0:13 Comment(0)
A
7

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.

Atchison answered 8/6, 2023 at 0:9 Comment(1)
This is a better answer than mine! Should have gotten the check.Condensed
P
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: []);
 }
} 
Panicle answered 8/6, 2023 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.