Reputation: 1983
All three of them do basically the same thing. What are the best practices? In which case shall I use which extracting way? What is the standard?
I guess these could be some points that could matter:
Extract the Container. Which way would you prefer and why?
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ExtractedAsWidget();
}
}
class ExtractedAsWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
return buildContainer();
}
Container buildContainer() => Container();
}
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
var container = Container();
return container;
}
}
Upvotes: 7
Views: 1914
Reputation: 2793
Extracting as Widget
is the best practice as the Flutter framework can optimize widgets rather than methods or variables. But for this particular case, I would extract Container
as method
. Extracting as Widget
would be too overkill.
Extracting as Variable
Extracting as variable
should only be done when your widget is fixed, being used only in a single file & doesn't need any parameters.
Extracting as Method
Extracting as method
should be done when your widget is being used only in a single file (and it can also use some parameters for additional customization). It also increases code readability.
Extracting as Widget
Extracting as Widget
is the most optimal way to create a widget that is being used multiple times in different files. Flutter recommends creating as much StatelessWidget
as possible.
The most simple example that I can suggest is the use of buttons. Every app has a fixed primary color button that we use. So, instead of creating a variable or method, we should create a StatelessWidget
of that button & use that in multiple screens of our app.
Upvotes: 10