当我运行下面的代码时,它会将此错误打印到屏幕上,我不知道为什么:
Null 类型不是 int 类型的子类型
这是我的 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();
},
),
),
);
}
}
我不明白为什么这不能正常工作。
您在项目中启用了Null Safety 来运行。您已在数据模型类中声明了所有字段 required 和 non-null。
您的 API 响应缺少字段或具有空值,这就是您面临此问题的原因。
解决方案: 将
int
替换为 int?
(将字段设为可选将解决问题)。
您可以使用 Helper 类。
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;
}
}
然后强制转换为 int。 在你的模型课上
id: TypesHelper.toInt(json['id']),
请勿使用
late Future<data> futureAlbum;
使用
Future<data>? futureAlbum;
确保在推送和检索数据时检查拼写
在我看来,你的一些 json 响应可能没有 id ,所以它显示了错误。您应该检查您收到的 json 响应,看看它是否有 id 。