강수경
강수경

Reputation: 37

Flutter: problem in fetching data: type 'Null' is not a subtype of type 'String' error

I am trying to fetch google book search api data. https://www.googleapis.com/books/v1/volumes?q=%EA%B2%BD%EC%A0%9C

I followed this one: https://docs.flutter.dev/cookbook/networking/fetch-data

My class:

class Book {
  final String id;
  final String title;
  final List<String> authors;

  const Book({
    required this.id,
    required this.title,
    required this.authors,
  });

  factory Book.fromJson(Map json) {
    return Book(
      id: json['id'],
      title: json['title'],
      authors: json['author'],
    );
  }
}

request data:

  late Future<List<Book>> futureBooks;
  Future<List<Book>> fetchBooks() async {
    Uri url = Uri.parse(
        'https://www.googleapis.com/books/v1/volumes?q=경제 경영'); //&maxResults=1
    final response = await http.get(url);
    if (response.statusCode == 200) {
      var json = jsonDecode(response.body);
      List<dynamic> items = json['items'];
      List<Book> books = (items.map((item) {
        return Book.fromJson(item);
      })).toList();
      return books;
    } else {
      throw Exception('Failed to load Books');
    }
  }

  @override
  void initState() {
    super.initState();
    futureBooks = fetchBooks();
  }

enter image description here

I think I have same issue with this. How to solve the "Type Null is not a subtype of type ..." error?

So I appended [?] for fields.

class Book {
  final String? id;
  final String? title;
  final List<String>? authors;

It still give me null.

enter image description here

my code: https://github.com/kangsudal/millie/blob/7f1f912c5a0eba0fe09de67c1c729be73b660da1/lib/screens/0_today/tab_widdget/tab_now.dart#L62

how to get data?

Upvotes: 0

Views: 81

Answers (1)

manhtuan21
manhtuan21

Reputation: 3455

because title and author is not inside item object, it inside volumeInfo, so you much change fromJson method of your Book class to

factory Book.fromJson(Map json) {
    return Book(
      id: json['id'],
      title: json['volumeInfo']['title'],
      authors: json['volumeInfo']['author'],
    );
  }

Upvotes: 1

Related Questions