【发布时间】:2020-11-19 13:31:57
【问题描述】:
我创建了一个名为NotificationModel 的抽象类,并扩展了两个类。当我尝试添加类型为List<NotificationModel> 的列表时,仅适用于一种类型(如果我有一种类型效果很好,但是当我添加另一个扩展相同NotificationModel 的类型时,我得到一个错误)。错误是下一个:
[错误:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常: 未处理的错误类型“AndroidNotificationsModel”不是 '元素'的类型'ApiNotificationModel'发生在实例中 'NotificationBloc'。
NotificationModel 抽象类:
import 'package:equatable/equatable.dart';
class NotificationsModel extends Equatable {
final String id, title, body, image;
final bool viewed;
NotificationsModel({this.id, this.title, this.body, this.image, this.viewed,});
@override
List<Object> get props => [this.id];
}
扩展类的类:
class ApiNotificationModel extends NotificationsModel {
final InvestmentOpportunityModel investmentOpportunityModel;
ApiNotificationModel({
id,
title,
body,
image,
viewed,
this.investmentOpportunityModel,
}) : super(id: id, title: title, image: image, body: body, viewed: viewed);
factory ApiNotificationModel.fromJson(Map<String, dynamic> json) {
return ApiNotificationModel(
id: json['id'],
title: json['title'],
body: json['body'],
image: json['image'],
viewed: json['viewed'],
investmentOpportunityModel: json['investment'] != null
? InvestmentOpportunityModel.fromJson(json['investment'])
: null,
);
}
}
扩展的另一个类:
class AndroidNotificationsModel extends NotificationsModel {
AndroidNotificationsModel({id, opportunityId, title, body, image, viewed})
: super(title: title, image: image, body: body, viewed: viewed, id: id);
factory AndroidNotificationsModel.fromJson(Map<String, dynamic> json) {
return AndroidNotificationsModel(
title: json['notification']['title'],
body: json['notification']['body'],
opportunityId: json['data']['id'],
image: json['data']['image'],
);
}
}
例子:
// Works fine
List<NotificationModel> notifications = [ApiNotificationModel(), ApiNotificationModel()];
// Exception
notifications.add(AndroidNotificationsModel());
【问题讨论】:
-
你能提供一个minimal reproducible example吗?我在 DartPad 中不会发生这种情况。