Manish Paul
Manish Paul

Reputation: 551

Flutter/Dart API Call Throws Error (sometimes)

APIs:

  1. https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY
  2. https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY

API Call Method:

import 'package:http/http.dart';

import '../Models/fetched_data.dart';

Future<FetchedData?> fetchIndexDetails(String index) async {
  final String url =
      'https://www.nseindia.com/api/option-chain-indices?symbol=$index';

  try {
    final response = await get(
      Uri.parse(url),
    );

    final FetchedData? fetchedData = fetchedDataFromJson(response.body);
    return fetchedData;
  } catch (e) {
    print('$index Error: $e');
  }
  return null;
}

The json file is same for both the APIs, hence the model class too.

However, the second API call works smoothly but the first API call throws an error saying:

type 'double' is not a subtype of type 'int?'

Can anybody help me decode the problem here? Much tia :)

Upvotes: 0

Views: 392

Answers (4)

iAhmedGhalab
iAhmedGhalab

Reputation: 83

This is a JSON parsing issue for unmatched type parsing of the API and the your Dart Model ..

How to diagnose it? You can always catch those errors while the development by enabling the dart debugger for uncaught exceptions, which gives you exactly the broken casting

How to enable dart debugger for uncaught exceptions

Upvotes: 1

esentis
esentis

Reputation: 4666

Seems like you are trying to map a double to int?, the response had a double and you are assigning it to int?, add a breakpoint when mapping the response to see the corresponding field. You can try casting it to int or just changing the type all together.

Upvotes: 0

imnaman
imnaman

Reputation: 92

Check your model class where you have defined different variables and match with data type you are getting in response from the json. There must be a variable you have defined in model class as int? but u r getting double as a response so u got to convert the data type .

Upvotes: 0

Rohan Thacker
Rohan Thacker

Reputation: 6337

type 'double' is not a subtype of type 'int?'

The API has returned a double value where an int is expected.

In your model or where appropriate replace the expected type to use num which int and double are both subtypes of

Upvotes: 1

Related Questions