9

When I run the code below, it prints this error to the screen, and I don't know why:

type Null is not a subtype of type int

This is my model class for the data from the API:

class data {
  final int id;
  final String email;
  final String first_name;
  final String last_name;
  final String avatar;

  data({
    required this.id,
    required this.email,
    required this.first_name,
    required this.last_name,
    required this.avatar,
  });

  factory data.fromJson(Map<String, dynamic> json) {
    return data(
      id: json['id'],
      email: json['email'],
      first_name: json['first_name'],
      last_name: json['last_name'],
      avatar: json['avatar'],
    );
  }
}

API calling part(this part is the calling):

import 'dart:async';
import 'dart:convert';
import 'package:api_data/models/datamodel.dart';
import 'package:http/http.dart' as http;

class ApiManager {
  Future<data> fetchAlbum() async {
    final response =
        await http.get(Uri.parse('https://reqres.in/api/users?page=2'));

    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      return data.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }
  }
}

Main part

import 'package:api_data/models/datamodel.dart';
import 'package:api_data/network/api_data.dart';
import 'package:flutter/material.dart';

class Testpage extends StatefulWidget {
  const Testpage({Key? key}) : super(key: key);

  @override
  _TestpageState createState() => _TestpageState();
}

class _TestpageState extends State<Testpage> {
  late Future<data> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = ApiManager().fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Test2'), centerTitle: true),
      body: Center(
        child: FutureBuilder<data>(
          future: futureAlbum,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data!.email.toString());
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }

            // By default, show a loading spinner.
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

I don't understand why this doesn't work properly.

0

5 Answers 5

11

You are running with Null Safety enabled in your project. You have declared your all fields required and non-null in your Data Model Class.

Your API response is having a field absent or having a null value, that's why you are facing this issue.

Solution: Replacing int with int? (making fields optional will resolve issue).

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the Helper class.

class TypesHelper{
static int toInt(num val){
try{
  if(val == null){
    return 0;
  }
  if(val is int){
    return val;
  }else{
    return val.toInt();
  }
}catch(error){
  print('Error');
return 0;
}

}

Then you force conversion to int. On your Model class

id: TypesHelper.toInt(json['id']),

Comments

0

Do not use late Future<data> futureAlbum;

Use Future<data>? futureAlbum;

1 Comment

I've used both in the same line, still facing this issue. any ideas?
0

make sure to check spelling while pushing and retrieving the data

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-1

It appears to me that some of your json response might not have an id , so it's showing the error . You should check the json response you are getting and see if it has the id .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.