Json 序列化 returns: 类型 'Null' 不是类型 'String' 的子类型

Json serialization returns: type 'Null' is not a subtype of type 'String'

所以我正在尝试从 Json 列表 object 中构建一个(任何类型的)列表,我正在使用 REST api 获取它,响应是Json 列表,包含以下字段:type, contact {first_name, last_name}, created_at, uuid.

使用此代码获取数据并将其解析为自定义数据类型

import 'dart:convert';
import 'package:connectix/models/calls.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class ContactService {
static String _url = "https://api.voipappz.io/tasks//connectix_conversations_recent";

static Future browse() async{
var channel = IOWebSocketChannel.connect(Uri.parse(_url));

}
}

List<CallType> parseCalls(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

return parsed.map<CallType>((json) => CallType.fromJson(json)).toList();
}

Future<List<CallType>> fetchCalls(http.Client client) async {
final response = await client
  .get(Uri.parse("https://api.voipappz.io/tasks//connectix_conversations_recent"));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseCalls, response.body);
}

这就是数据类型模型

class CallType {
final String type;
final String first_name, last_name;
final String created;

CallType({
required this.type,
required this.first_name,
required this.last_name,
required this.created,
});

factory CallType.fromJson(Map<String, dynamic> json){
return CallType(
  type: json['type'],
  first_name: json['contact.first_name'],
  last_name: json['contact.last_name'],
  created: json['created_at'],
);
} 

}

这是我要显示的小部件的代码,returns我是问题标题中的错误

class CallsList extends StatelessWidget {
final List<CallType> calls;

CallsList({Key? key, required this.calls}) : super(key: key);

@override
Widget build(BuildContext context) {
return GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2,
  ),
  itemCount: calls.length,
  itemBuilder: (context, index) {
    return Text(calls[index].type);
  },
);
}
}


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

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

class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.orange,
    appBar: AppBar(
      title: Text('hello'),
    ),
    body: FutureBuilder<List<CallType>>(
      future: fetchCalls(http.Client()),
      builder: (context, snapshot) {
        if (snapshot.hasError) print(snapshot.error);

      return snapshot.hasData
          ? CallsList(calls: snapshot.data!)
          : Center(child: CircularProgressIndicator());
    },
  ),
);
}
}

您将 CallType 的所有属性标记为 required。 API 似乎没有返回其中一个(或多个)属性的数据。

您需要将它们标记为可选(删除 required 并将它们设为 String? 类型),或者注意您的 API 始终响应数据。