Refactoring question: Extract as widget/method/variable... What are pros and cons?
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.
Tomas Baran
Updated on December 25, 2022Comments
-
Tomas Baran over 1 year
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:
- readability
- performance
- number of lines
Example:
Extract the Container. Which way would you prefer and why?
class Example extends StatelessWidget { @override Widget build(BuildContext context) { return Container(); } }
1. Extract Container as Widget (+6 lines):
class Example extends StatelessWidget { @override Widget build(BuildContext context) { return ExtractedAsWidget(); } } class ExtractedAsWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Container(); } }
2. Extract Container as Method (+1 (in some cases 3) line):
class Example extends StatelessWidget { @override Widget build(BuildContext context) { return buildContainer(); } Container buildContainer() => Container(); }
3. Extract Container as Variable (+1 line):
class Example extends StatelessWidget { @override Widget build(BuildContext context) { var container = Container(); return container; } }