79519002

Date: 2025-03-19 02:48:49
Score: 2
Natty:
Report link

Excerpt from [Basic memory concepts](https://docs.flutter.dev/tools/devtools/memory?hl=en-GB#basic-memory-concepts):

\> The Dart VM allocates memory for the object at the moment of the object creation, and releases (or deallocates) the memory when the object is no longer used (see [Dart garbage collection](https://medium.com/flutter/flutter-dont-fear-the-garbage-collector-d69b3ff1ca30)).

The local variables with known size (e.g. bool, int) within a function are allocated to the stack memory. Those objects whose size and lifespan is not known at compile time are allocated to the heap memory. Objects allocated on the heap have a longer lifespan and are managed by Dart’s garbage collector. ([source](https://medium.com/@maksymilian.pilzys/deep-analysis-of-darts-memory-model-and-its-impact-on-flutter-performance-part-1-c8feedcea3a1))

Once a function finishes executing, all its local variables go out of scope, and the function’s stack frame is removed, and the memory occupied becomes available for reuse.

A code sample, stated “good practice”, [in official Flutter documentation](https://docs.flutter.dev/tools/devtools/memory?hl=en-GB#how-to-fix-leak-prone-code) using `build variables` declaration. This code sample is exemplified under title - “How to fix leak prone code”.

``` dart

// GOOD

@override

Widget build(BuildContext context) {

final theme = Theme.of(context);

final handler = () => apply(theme);

useHandler(handler);

```

So, for simple types and objects, it is okay to declare them within `build` method or callback functions’ block. We should avoid declaration in build when the objects use streams, timers, controllers, etc.

Reasons:
  • Blacklisted phrase (0.5): medium.com
  • Long answer (-1):
  • No code block (0.5):
  • User mentioned (1): @override
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: rusty