I'm new to flutter, and I heard that creating widgets as classes is better. So I'm trying to change functions to classes.
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),
]
)
),
);
}
the code above is one of the functions I want to change to stateless class. And I tried like this,
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),
]
)
),
);
}
}
But I still don't know where I should get that 'size'. How can I do that? Thank you for reading, and I'll wait for your advice!
You need to pass the arguments in the constructor, for example:
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),
]
)
),
);
}
}
And then when you call it, you can do:
Head(size : 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.