Flutter 未处理的异常:类型 'Null' 不是类型转换中类型 'List<dynamic>' 的子类型

Flutter Unhandled Exception: type 'Null' is not a subtype of type 'List<dynamic>' in type cast

我需要将模型分配给应用程序中的列表,但出现标题中提到的错误。

虽然我在 android 端收到此错误,但我没有问题,但是当我在 ios 端尝试时,我的应用程序崩溃了。

List<MessageModel> messageList = [];
String? message;
bool success = false;

@override
MessageService decode(dynamic data) {
messageList = (data as List).map((e) => MessageModel.fromJsonData(e)).toList(); ----> Unhandled Exception: type 'Null' is not a subtype of type 'List<dynamic>' in type cast
return this;
}
    List<MessageModel> ?messageList = [];
String? message;
bool success = false;

@override
MessageService decode(dynamic data) {
messageList = (data as List).map((e) => MessageModel.fromJsonData(e)).toList(); ----> Unhandled Exception: type 'Null' is not a subtype of type 'List<dynamic>' in type cast
return this;
}

您收到错误的原因是 data 为空。

试试我的解决方案:

List<MessageModel> messageList = [];
String? message;
bool success = false;

@override
MessageService decode(dynamic data) {
  messageList = data?.map((e) => MessageModel.fromJsonData(e))?.toList() ?? [];
  return this;
}