Home > Blockchain >  Api call throwing error type 'Null' is not a subtype of type 'List<Quotes>'
Api call throwing error type 'Null' is not a subtype of type 'List<Quotes>'

Time:05-11

here is my api call.

    class Httpservice {
    final Uri postURL = Uri.parse(
    "https://quotes.rest/qod?category=inspire",
  );
 static dynamic quoteOfTheDay;

 Future<List<Quotes>> getQuotes() async {
 Response res = await get(postURL);

final jsonItems = json.decode(res.body)["contents"]["quotes"];
List<Quotes> quote = jsonItems.map<Quotes>((json) {
  return Quotes.fromJson(json);
}).toList();
quoteOfTheDay = quote;
return quote;
 }
}
 

This is the display page

    class PostsPage extends StatelessWidget {
    final List<Quotes> quote = Httpservice.quoteOfTheDay;

    PostsPage({Key? key}) : super(key: key);

    @override
   Widget build(BuildContext context) {
   return Scaffold(
    appBar: AppBar(
    title: const Text("quotes"),
   ),
   body: FutureBuilder(
    //future: httpService.getQuotes(),
    builder: (BuildContext context, AsyncSnapshot<List<Quotes>> 
    snapshot) {
      if (snapshot.hasData) {
        //Future.delayed(const Duration(seconds: 5));
        // Quote? quotes = snapshot.data;
        if (kDebugMode) {
          print('" ${quote[0].quote} ?? '' "');
        }
        return Text('" ${quote[0].quote} ?? '' "');
      } else {
        return Scaffold(
          body: Column(children: const [
            SizedBox(height: 400.0),
            Center(
              child: CircularProgressIndicator(
                color: Colors.black,
              ),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text('loading')
          ]),
         );
       }
      },
     ),
   );
  }
 }

This is the model data

       class Quotes {
       String? quote;
       String? length;
       String? author;
       List<String>? tags;
       String? category;
      String? language;
      String? date;
      String? permalink;
      String? id;
      String? background;
      String? title;

     Quotes(
    {this.quote,
    this.length,
    this.author,
    this.tags,
    this.category,
    this.language,
    this.date,
    this.permalink,
    this.id,
    this.background,
    this.title});

   Quotes.fromJson(Map<String, dynamic> json) {
   quote = json['quote'];
   length = json['length'];
   author = json['author'];
   tags = json['tags'].cast<String>();
   category = json['category'];
   language = json['language'];
   date = json['date'];
   permalink = json['permalink'];
   id = json['id'];
   background = json['background'];
   title = json['title'];
   }

  Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = <String, dynamic>{};
  data['quote'] = quote;
  data['length'] = length;
  data['author'] = author;
  data['tags'] = tags;
 data['category'] = category;
 data['language'] = language;
 data['date'] = date;
 data['permalink'] = permalink;
 data['id'] = id;
 data['background'] = background;
 data['title'] = title;
 return data;
 }
}

Model data 2

 import 'quotes.dart';

 class Contents {
 List<Quotes>? quotes;

 Contents({this.quotes});

Contents.fromJson(Map<String, dynamic> json) {
if (json['quotes']) {
  quotes = <Quotes>[];
  json['quotes'].forEach((v) {
    quotes!.add(Quotes.fromJson(v));
  });
  }
 }

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (quotes != null) {
  data['quotes'] = quotes!.map((v) => v.toJson()).toList();
  }
 return data;
   }
  }

This is the code to all the major pages. when i try to display the quote from the class Quote nothing shows. i continously keep on getting this error when i try to navigate to the display page.Another exception was thrown: type 'Null' is not a subtype of type 'List' i really dont know what im doing wrong and im slumped.

CodePudding user response:

You are using FutureBuilder to get data. Snapshot that is returned does have List, however you are getting quoteOfTheDay before FutureBuilder which is null. Best way is to get data, when it is loaded,is through snapshot. Here is the working code:

PostsPage:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'http_service.dart';
import 'model_quote.dart';

class PostsPage extends StatelessWidget {
  PostsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("quotes"),
      ),
      body: FutureBuilder(
        future: Httpservice().getQuotes(),
        builder: (BuildContext context, AsyncSnapshot<List<Quotes>> snapshot) {
          if (snapshot.hasData) {
            //Future.delayed(const Duration(seconds: 5));
            // Quote? quotes = snapshot.data;
            final List<Quotes> quotes = snapshot.data!;
            return ListView.builder(
                itemCount: quotes.length,
                itemBuilder: (ctx, i) {
                  return Container(
                      child: Text('" ${quotes[0].quote} ?? ' ' "'));
                });
          } else {
            return Column(children: const [
              SizedBox(height: 400.0),
              Center(
                child: CircularProgressIndicator(
                  color: Colors.black,
                ),
              ),
              SizedBox(
                height: 10.0,
              ),
              Text('loading')
            ]);
          }
        },
      ),
    );
  }
}

HTTP Service

import 'dart:convert';
import 'package:http/http.dart';
import 'model_quote.dart';

class Httpservice {
  final Uri postURL = Uri.parse(
    "https://quotes.rest/qod?category=inspire",
  );

  Future<List<Quotes>> getQuotes() async {
    Response res = await get(postURL);
    final jsonItems = json.decode(res.body)["contents"]["quotes"];
    List<Quotes> quote = jsonItems.map<Quotes>((json) {
      print(json);
      return Quotes.fromJson(json);
    }).toList();
    return quote;
  }
}

CodePudding user response:

I think the issue is in this line final List<Quotes> quote = Httpservice.quoteOfTheDay;. As the variable quote is expecting List<Quotes> and you are calling Httpservice.quoteOfTheDay which is returning a null value.

Instead, you should call Httpservice.getQuotes(), as this method is returning the expected value.

final List<Quotes> quote = Httpservice.getQuotes();
  • Related