[英](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.