skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. create a folder name it const, create a file call spaces.dart.

    import 'package:flutter/material.dart';
    
    class MySpaces {
      MySpaces._();
    
      static const Widget mediumVertical =  SizedBox(height: 10);
      static const Widget mediumHorizontal =  SizedBox(width: 10);
      
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search