Home > Back-end >  How to handle null value in API responses for certain values at some time
How to handle null value in API responses for certain values at some time

Time:04-16

I am learning to build a book shelf app using Google Books API. In some queries, there are certain values which are not present, for example Author or Thumbnail image and so on, and in some cases for example, the Author is an array with 1 or 2 values and sometimes null. How do I handle this efficiently, so that I cover all scenarios - values missing and values present and if present do some operations like .join() on the array

Here is my model class

class VolumeModel {
  final String title;
  final String author;
  final String thumbnail;
  final String description;
  final String id;
  final String totalItems;
  final String publishedDate;
  final String publisher;
  final String pageCount;
  final isbn;
  final String language;

  VolumeModel(
      {required this.publishedDate,
      required this.publisher,
      required this.pageCount,
      required this.title,
      required this.totalItems,
      required this.author,
      required this.id,
      required this.thumbnail,
      required this.description,
      required this.isbn,
      required this.language});
}

Here is my services code.

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../apiurls/api_urls.dart';
import '../models/volume_details.dart';
    
    class GoogleApiService {
      Future<List<VolumeModel>> getBooks(query, startIndex, maxResults) async {
        try {
          print('APi Started');
    
          var querryData = ApiEndpoints.googleBookLite  
              query  
              '&'  
              ApiEndpoints.apiKey  
              '&startIndex='  
              startIndex.toString()  
              '&maxResults='  
              maxResults.toString();
          print(querryData);
          var response = await http
              .get(Uri.parse(querryData))
              .timeout(Duration(seconds: 10), onTimeout: () {
            throw TimeoutException(
                'Unable to establish connection . Please try again after sometime');
          });
    
          if (response.statusCode == 200) {
            print(jsonDecode(response.body));
            return _parseBookJson(response.body);
          } else {
            print('Null');
          }
        } on TimeoutException catch (_) {
          print('Response TimeOUt');
        }
        throw {};
      }
    
      List<VolumeModel> _parseBookJson(String jsonStr) {
        final jsonMap = jsonDecode(jsonStr);
        final totalItems = jsonMap['totalItems'];
        final jsonList = (jsonMap['items'] as List);
        var obj = jsonList
            .map((jsonBook) => VolumeModel(
                totalItems: totalItems.toString(),
                id: jsonBook['id'],
                title: jsonBook['volumeInfo']['title'],
                author: jsonBook['volumeInfo']['authors'].join('') ?? "NA",
                description: jsonBook['volumeInfo']['description'] ?? '',
                thumbnail: jsonBook['volumeInfo']['imageLinks']['thumbnail'] ?? '',
                isbn: jsonBook['volumeInfo']['industryIdentifiers'][0]
                            ['identifier']  
                        '  '  
                        jsonBook['volumeInfo']['industryIdentifiers'][1]
                            ['identifier'] ??
                    "",
                pageCount: jsonBook['volumeInfo']['pageCount'].toString(),
                publishedDate: jsonBook['volumeInfo']['publishedDate'].toString(),
                publisher: jsonBook['volumeInfo']['publisher'] ?? 'NA',
                language: jsonBook['volumeInfo']['language']))
            .toList();
        // print(obj);
        return obj;
      }
    }

A case in point, I got this error below, because the Authors for some results are not present or null, so I have around 15 results out of which 2 or 3 don't have any value. I am using .join() to combine two or more values in the Author array. Can you give me some pointers on this?

Unhandled Exception: NoSuchMethodError: The method 'join' was called on null.
E/flutter (32062): Receiver: null
E/flutter (32062): Tried calling: join("")

CodePudding user response:

Trying using the null safe operator (?.)

jsonBook['volumeInfo']['authors']?.join('') ?? "NA"

This will call join('') only when the list is not null and return "NA" otherwise

CodePudding user response:

In the model class you have to declare like below!!!

class VolumeModel {
  final String title;
  final String? author;
  final String thumbnail;
  final String description;
  final String id;
  final String totalItems;
  final String publishedDate;
  final String publisher;
  final String pageCount;
  final isbn;
  final String language;

  VolumeModel(
      {required this.publishedDate,
      required this.publisher,
      required this.pageCount,
      required this.title,
      required this.totalItems,
      this.author,
      required this.id,
      required this.thumbnail,
      required this.description,
      required this.isbn,
      required this.language});
}

author: jsonBook['volumeInfo']['authors']?.join('') ?? "NA",

you have to make that field nullable using (?) and remove required keyword from the constructor to make that field nullable. so if null value comes from response for that particular field, flutter accepts null value for that field...

enjoy coding!!!
  • Related