如何將方法應用于類中的靜態變數。顫振中的某些內置類似乎做了這樣的事情。
class UITextStyle {
static const TextStyle body = TextStyle(fontSize: 17);
addColor(Color color) {
TextStyle style = this as TextStyle;
style.merge(TextStyle(color: color));
}
}
然后可以這樣呼叫:
UITextStyle.body.addColor(Color.fromRGBA(0,0,0,1));
但是我不能這樣呼叫該方法,因為首先它不是靜態的,其次,如果是這樣,我將無法在.body首先宣告后呼叫它,并且只能在UITextStyle.addColor(...).
這是如何實作的?
uj5u.com熱心網友回復:
你可以試試這個解決方案,關鍵是TextStyle型別沒有定義addColor函式,所以要實作這個功能,你需要通過這個擴展將這個函式添加到TextStyle類中:
extension TextStyleEx on TextStyle{
TextStyle addColor(Color color) {
return merge(TextStyle(color: color,fontWeight: FontWeight.w600));
}
}
并使此方法回傳 TextStyle 以便您可以從合并的實體中獲取實體,因為您的靜態物件是最終的,因此您無法在其上接收新值。
像這樣離開你的班級
class UITextStyle { static const TextStyle body = TextStyle(fontSize: 17); }使用這個類和保存的靜態物件來獲取帶有新舊 TextStyles 的新 TextStyle。
在 main 中進行測驗運行,將清除前面的示例:
TextStyle mergedStyles = UITextStyl.body.addColor(Colors.black); print(mergedStyles);
uj5u.com熱心網友回復:
多虧了@pskink 的評論,我最終得以實作這一功能。
class UITextStyle {
const UITextStyle(this.style);
final TextStyle style;
static const body = UITextStyle(TextStyle(fontSize: 17));
addColor(Color color) {
TextStyle textStyle = style;
return textStyle.merge(TextStyle(color: color));
}
}
uj5u.com熱心網友回復:
在 Dartextensions中可以有靜態成員。
extension UITextStyle on TextStyle {
static const body = TextStyle(fontSize: 17);
TextStyle addColor(Color color) {
return this.merge(TextStyle(color: color));
}
}
然后你可以這樣做:
UITextStyle.body.addColor(Color.fromRGBO(0, 0, 0, 1));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515918.html
標籤:扑变量方法静止的
下一篇:使用R根據其他因素更改雕像
