francesco
francesco

Reputation: 1

Error: Expected a value of type 'String', but got one of type 'Null'

I am learing about api's and http request in flutter and I got an error in making a get request I got this error : Error: Expected a value of type 'String', but got one of type 'Null'

enter image description here

I got this error:

enter image description here

Upvotes: 0

Views: 3099

Answers (1)

mario francois
mario francois

Reputation: 1371

When you say data[id] as String for example, that means: data[id] is null.

  factory Formule.fromMap(Map? data) {
    if (data == null) {
      return const Formule(
          id: '', title: '', prix: 0, nombreDePlace: 0, alertThreshold: 0, remainingPlaces: 0);
    }
    return Formule(
        id: data['id'] as String,
        title: data['title'] as String,
        prix: data['prix'] as double,
        nombreDePlace: data['nombreDePlace'] as int,
        alertThreshold: data['alertThreshold'] as int,
        remainingPlaces: data['remainingPlaces'] as int);
  }

2 solutions:

id: data['id'] as String?,

Or

id: data['id'] as String? ?? "",

Upvotes: 2

Related Questions