簡體   English   中英

Flutter 抽象類類型異常

[英]Flutter abstract class type exception

我創建了一個名為NotificationModel的抽象類,並擴展了兩個類。 當我嘗試添加List<NotificationModel>類型的List<NotificationModel> ,它僅適用於一種類型(如果我有一種類型效果很好,但是當我添加另一個擴展相同NotificationModel類型時,我會收到錯誤消息)。 錯誤是下一個:

[錯誤:flutter/lib/ui/ui_dart_state.cc(177)] 未處理的異常:未處理的錯誤類型“AndroidNotificationsModel”不是“NotificationBloc”實例中發生的“元素”的“ApiNotificationModel”類型的子類型。

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

您在List<NotificationModel> notificationsNotificationsModel中缺少一個s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM