我是新手,我听说将小部件创建为类更好。
所以我试图将函数更改为类。
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)
关于android - ( flutter )如何在类里面争吵?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64133271/