【问题标题】:Flutter abstract class type exceptionFlutter 抽象类类型异常
【发布时间】: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());

【问题讨论】:

标签: flutter dart


【解决方案1】:

您在NotificationsModelList&lt;NotificationModel&gt; notifications 中缺少一个 s

【讨论】:

  • 我在使用 bloc 时遇到问题。我将添加集团代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
相关资源
最近更新 更多