Reputation: 23
Which is the correct usage? Also I'm confused about if we should do "extract method" or "extract widget"? Flutter recommends to extract widgets. But I'm not sure where should I extract widget?
class TopBarTitle extends StatelessWidget {
const TopBarTitle();
static const String title = 'FLASHCARDS';
static const String fontFamily = 'Itim';
@override
Widget build(BuildContext context) {
return Text(
title,
style: TextStyle(
fontSize: 18.sp,
color: Theme.of(context).iconTheme.color,
fontWeight: FontWeight.w500,
fontFamily: fontFamily,
),
);
}
}
or
class TopBarTitle extends StatelessWidget {
const TopBarTitle();
@override
Widget build(BuildContext context) {
const String title = 'FLASHCARDS';
const String fontFamily = 'Itim';
return Text(
title,
style: TextStyle(
fontSize: 18.sp,
color: Theme.of(context).iconTheme.color,
fontWeight: FontWeight.w500,
fontFamily: fontFamily,
),
);
}
}
Upvotes: 2
Views: 1455
Reputation: 151
First one is preferred, it will be declare each time you reach to that class There is problem with the second one each time the set is updating it will will declare those variables again and again
Upvotes: 0
Reputation: 9039
The first one is preferred. build
method is supposed to be called many times in a short time and you should keep it simple. In the second code, you're defining two variables every time the method gets called (of course it's a very cheap operation considering they're constant but still it should be prevented whenever possible).
And to answer your question about "extract method" or "extract widget", Flutter recommends "extract widget" since there are lot's optimizations applied in that case and it's easier to debug too. There are lot's of discussions about that which you can easily find by searching. For example read this one: https://stackoverflow.com/a/53234826/5204833
Upvotes: 2