簡體   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