下面是一個嘗試的嵌套物件。
class AppColors {
static const light = {
final backgroundSolid = const Color.fromRGBO(255, 255, 255, 1);
final backgroundPrimary = const Color.fromRGBO(255, 255, 255, 0.84);
},
static const dark = {
final backgroundSolid = const Color.fromRGBO(0, 0, 0, 1);
final backgroundPrimary = const Color.fromRGBO(0, 0, 2550 0.84);
}
}
錯誤在于在第一行專案上使用了 final。創建嵌套物件的正確方法是什么?
uj5u.com熱心網友回復:
Dart 是一種非常靈活的語言,沒有真正的correct方法
你當然可以使用 Maps 來實作它,但是你會失去一個類所具有的自動完成和安全性:
class AppColors {
//These are maps, note the `:` to separate key and values
static const light = {
'backgroundSolid' : const Color.fromRGBO(255, 255, 255, 1);
'backgroundPrimary' : const Color.fromRGBO(255, 255, 255, 0.84);
};
static const dark = {
'backgroundSolid' : const Color.fromRGBO(0, 0, 0, 1);
'backgroundPrimary' : const Color.fromRGBO(0, 0, 2550 0.84);
};
}
void main()
{
final backgroundLight=AppColors.light['backgroundPrimary'];
}
但是,這就是我將其編碼的方式。這樣你就有了一個包含你需要的屬性的類,如果添加更多,dart 分析器會讓你重構工廠建構式以添加/洗掉新欄位。并且對屬性的訪問也感覺很干凈。
class AppColors {
final Color backgroundSolid;
final Color backgroundPrimary;
AppColors({required this.backgroundSolid, required this.backgroundPrimary});
factory AppColors.light()=>
AppColors(backgroundSolid: const Color.fromRGBO(255, 255, 255, 1),
backgroundPrimary: const Color.fromRGBO(255, 255, 255, 0.84));
factory AppColors.dark()=>
AppColors(backgroundSolid: const Color.fromRGBO(0, 0, 0, 1),
backgroundPrimary: const Color.fromRGBO(0, 0, 0, 0.84));
}
void main()
{
final backgroundLight=AppColors.light().backgroundPrimary;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336802.html
上一篇:將CSV行匯入類
