【问题标题】:Json serialization returns: type 'Null' is not a subtype of type 'String'Json 序列化返回:“Null”类型不是“String”类型的子类型
【发布时间】:2021-09-22 10:41:38
【问题描述】:

所以我正在尝试从颤振中的 Json 列表对象构建一个列表(任何类型),我使用 REST api 获取它,响应是一个 Json 列表,其中包含以下字段:类型,联系人 {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'],
);
} 

}

这是我要显示的小部件的代码,并在问题标题中返回错误

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

【问题讨论】:

    标签: json flutter rest flutter-listview


    【解决方案1】:

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

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

    【讨论】:

    • 我已经注释掉了 first_name 和 last_name 并且错误消失了。也许我在尝试访问关键联系人.last_name 时做错了什么? json 是联系人:{ first_name: XXX, last_name: XXX}
    • 我认为json['contact.first_name']不起作用。试试json['contact']['first_name']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2022-11-14
    • 2022-06-12
    • 2023-03-03
    • 1970-01-01
    • 2022-07-10
    相关资源
    最近更新 更多