【问题标题】:Type Null is not a subtype of type int error when tried fetch data from an API尝试从 API 获取数据时,Null 类型不是 int 类型的子类型错误
【发布时间】:2021-08-27 06:01:31
【问题描述】:

我已经尝试了很长时间,但我无法通过此错误。我是一个初学者级别的颤振开发者。非常感谢您的帮助。
这个类,这是我的 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调用部分(这部分是调用)

    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');
        }
      }
    }

主要部分

    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();
              },
            ),
          ),
        );
      }
    }

我知道这是一项非常简单的任务。但我不明白为什么这不能正常工作。当我运行它时,它会在屏幕上显示错误

type Null is not a subtype of type int

【问题讨论】:

  • 你的 api 响应是什么?

标签: api flutter fetch runtime-error


【解决方案1】:

欢迎来到 SO,

您在项目中使用 Null Safety Enbaled 运行。您已在数据模型类中声明了所有字段必填非空

您的 API 响应缺少字段或具有空值,这就是您遇到此问题的原因。

解决方案:int 替换为 int?(将字段设为可选将解决问题)。Read

【讨论】:

    【解决方案2】:

    在我看来,您的某些 json 响应可能没有 id ,因此它显示错误。你应该检查你得到的 json 响应,看看它是否有 id 。

    【讨论】:

      【解决方案3】:

      您拥有的唯一 int 是 int id。你的代码会在这里失败吗?

      return data(
        id: json['id'], // ?????
        email: json['email'],
        first_name: json['first_name'],
        last_name: json['last_name'],
        avatar: json['avatar'],
      );
      

      【讨论】:

        猜你喜欢
        • 2022-09-30
        • 1970-01-01
        • 2022-12-23
        • 1970-01-01
        • 2021-09-25
        • 2020-11-13
        • 2021-10-08
        • 1970-01-01
        • 2022-09-27
        相关资源
        最近更新 更多