In my Flutter project, I have defined a set of constant variables like this in a Dart file (constants.dart):
var spaceS = const SizedBox(height: 10);
var spaceM = const SizedBox(height: 15);
var spaceL = const SizedBox(height: 30);
I find it convenient to use these constants throughout my application to add spacing. However, I’m wondering if this approach could potentially lead to any performance issues or memory leaks. Would it be better to create these SizedBox widgets directly where I need them instead of using constants like this?
I appreciate any insights or best practices related to this. Thanks!
Please consider below A and B usages
Usage A
Column(
children: [
const SizedBox(height: 15),
const LogoBig(),
const SizedBox(height: 15),
]
)
Usage B
Column(
children: [
spaceM,
const LogoBig(),
spaceM,
]
)
2
Answers
There are no problems using it that way, including the flutter documentation and many packges use it in a similar way, which can cause memoryliking in the app and the lifecycle of changeable widgets, for example TextFormField
create a folder name it
const
, create a file callspaces.dart
.in flutter we call static const value a lot, like
Colors.white
,Icons.person
,static
mean, its only take 1 single memory across the entire app.