繁体   English   中英

如何在颤振中将任何 class object 传递给有状态的 class(遗传类型)

[英]how to pass any class object to a stateful class in flutter(genetic type)

我有几个有状态的类,如收入、支出、借方、事件等,每个 class 都有自己的一组属性(int、double、string) . 而不是为收入、支出等编写不同的 class 来执行特定任务,我想创建一个 class ,这在所有类别中都很常见

这是我常见的 class 的部分代码


class CheckBoxAlertDialog extends StatefulWidget {
  CheckBoxAlertDialog({
    Key key,
    this.anyobjectype,
    this.database
  }) : super(key: key);

  final T anyobjectype;
  final AppDatabase database;

  @override
  CheckBoxAletDialogState createState() {
    return new CheckBoxAletDialogState();
  }
}

class CheckBoxAletDialogState extends State<CheckBoxAlertDialog> {

  @override
  Widget build(BuildContext context) {
      If(anyobjectype is type income)
          print(anyobjectype.amount)     //assume income class has type double income
      If(anyobjectype is type expense)
          print(anyobjectype.paid_amount)  //assume expense class has type double paid_amount
       If(anyobjectype is type event)
          print(anyobjectype.event_date)   //assume event class has type date event_date

       //and so on
      
   }
}

我希望能够调用 CheckBoxAlertDialog 并传递 class 收入、费用、借方、事件的任何 object。 例如,我希望能够如下调用

income = new income();
CheckBoxAlertDialog(anyobjectype : income, database: database,);

expense = new expense();
CheckBoxAlertDialog(anyobjectype : expense, database: database,);

debit = new debit();
CheckBoxAlertDialog(anyobjectype : debit, database: database,);


基本上,我希望能够将任何 class object 传递给 CheckBoxAlertDialog,并能够在 CheckBoxAlertDialog class 中访问类的数据类型。 请参阅 CheckBoxAlertDialog 中的构建 function
我听说遗传数据类型可以提供帮助,但我对此并不陌生。 有人可以告诉我如何将任何 class object 传递给 CheckBoxAlertDialog 并能够像上面的示例一样访问 CheckBoxAlertDialog 中的 class 数据类型吗? 提前致谢

尝试使用InheritedWidget 它允许您的子小部件访问父 class 的成员。 检查文档: https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html

这个网站也很有帮助: https://ericwindmill.com/articles/inherited_widget/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM