gpt4 book ai didi

serialization - 是否可以扩展类并仍将DSON Generator用于Dart?

转载 作者:行者123 更新时间:2023-12-03 04:08:44 25 4
gpt4 key购买 nike

我有使用sdk 1.24的dart Web应用程序,并且一直在使用dson:0.11.0为要保存到Firestore数据库的对象生成可序列化的类/模型。

我喜欢dson生成的类的方式,使我能够从 map 创建dart对象,或将dart对象序列化为 map 以保存在Firebase中。

话虽如此,dson生成器要求我的模型类扩展可序列化的抽象生成的类。

我的应用程序开始变得越来越大,而我却无法使用继承和开发类层次结构而苦苦挣扎。

除非我缺少一些似乎无法自行破解的概念,否则我无法弄清楚如何在dson生成器中使用类继承。

例如,这是我要尝试做的一个非常简单的示例。

class EmploymentIncome extends Object {        
String employerName;
Address employerAddress;
DateTime hireDate;
}


class SalaryIncome extends EmploymentIncome {
double annualSalary;
}


class HourlyIncome extends EmploymentIncome {
double hourlyRate;
double hoursPerWeek;
}


class hourlyPaystub extends HourlyIncome {
double yearToDateHourlyEarnings;
double hoursWorked;
DateTime payDate;
DateTime periodEndingDate;
}


class salaryPaystub extends SalaryIncome {
double yearToDateSalaryEarnings;
DateTime payDate;
DateTime periodEndingDate;
}

问题是,dson生成器要求我的模型扩展生成的抽象类,请参见下文:
@serializable
class EmploymentIncome extends _$EmploymentIncomeSerializable {
class EmploymentIncome extends Object {
String employerName;
Address employerAddress;
DateTime hireDate;
}

很明显,现在的问题是,我无法用另一个可序列化的dson类扩展EmploymentIncome。

我是否错过了一个基本概念或技术,该概念或技术将使我能够扩展这些类,同时又保持将 Dart 对象与 map 转换的能力?

预先感谢您的指导!

最佳答案

需要完成两件事:

  • 使用serializable运算符
  • 扩展生成的 with
  • 添加评论以忽略分析错误

  • 例如,您可以执行以下操作:
    @serializable
    class EmploymentIncome extends _$EmploymentIncomeSerializable {
    String employerName;
    Address employerAddress;
    DateTime hireDate;
    }

    @serializable
    // ignore: mixin_inherits_from_not_object
    class SalaryIncome extends EmploymentIncome with _$SalaryIncomeSerializable {
    double annualSalary;
    }

    @serializable
    // ignore: mixin_inherits_from_not_object
    class HourlyIncome extends EmploymentIncome with _$HourlyIncomeSerializable {
    double hourlyRate;
    double hoursPerWeek;
    }

    @serializable
    // ignore: mixin_inherits_from_not_object
    class HourlyPaystub extends HourlyIncome with _$HourlyPaySerializable {
    double yearToDateHourlyEarnings;
    double hoursWorked;
    DateTime payDate;
    DateTime periodEndingDate;
    }

    @serializable
    // ignore: mixin_inherits_from_not_object
    class SalaryPaystub extends SalaryIncome with _$SalaryPayStubSerializable {
    double yearToDateSalaryEarnings;
    DateTime payDate;
    DateTime periodEndingDate;
    }

    关于serialization - 是否可以扩展类并仍将DSON Generator用于Dart?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50752175/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com