[英](flutter) How can I get argument in class?
我是 flutter 的新手,我聽說將小部件創建為類更好。 所以我試圖將函數更改為類。
Widget Head(Size size){
return Container(
height: size.height*0.3 + 100,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xff3D1472),
Color(0xff771887),
]
)
),
);
}
上面的代碼是我想更改為無狀態類的功能之一。 我像這樣試過,
class Head extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: size.height*0.3 + 100,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xff3D1472),
Color(0xff771887),
]
)
),
);
}
}
但我仍然不知道我應該從哪里得到那個“大小”。 我怎樣才能做到這一點? 感謝您的閱讀,我會等待您的建議!
您需要在構造函數中傳遞參數,例如:
class Head extends StatelessWidget {
Head({this.size});
final int size;
@override
Widget build(BuildContext context) {
return Container(
height: size.height*0.3 + 100,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xff3D1472),
Color(0xff771887),
]
)
),
);
}
}
然后當你調用它時,你可以這樣做:
Head(size : 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.