Yassine BENNKHAY
Yassine BENNKHAY

Reputation: 149

Handle null value in json with flutter

I'm trying to fetch quotes from here

but some values in the JSON are null, how can I handle this in flutter?

I have the error message:_TypeError (type 'String' is not a subtype of type 'Null')

API call method:

Future fetchAllQuotes() async {
  final response = await http.get(Uri.parse('https://type.fit/api/quotes'));
  if (response.statusCode == 200) {
    var jsonData = jsonDecode(response.body);
    var quotes = [];
    for (var aQuote in jsonData) {
      Quote quote = Quote(
        text: aQuote['text'],
        author: aQuote['author'],//the error is caused here
      );

      quotes.add(quote);
    }
    
    return quotes;
  } else {
    throw Exception('Failed to fetch quotes');
  }
}

Upvotes: 2

Views: 2080

Answers (1)

Csisanyi
Csisanyi

Reputation: 885

Possible solution

author: aQuote['author'] ?? 'null'

Upvotes: 2

Related Questions