1

I am new to flutter, and I want to make sure that I dont have any loose initializations when i pop a screen. Is there a way to check for loose initializations from variables, listeners or streams to avoid memory leaks?

slimboy
  • 1,633
  • 2
  • 22
  • 45

3 Answers3

1

You can remove all listener or streams by overriding dispose method

  @override
  void dispose() {
    super.dispose();
    //listeners to remove
  }

check the flutter life cycle examples: Life cycle in flutter

Itamar Garcia
  • 882
  • 10
  • 17
0

create a dispose method in your BLoC

  final _someSubject = BehaviorSubject<List<int>>();

  ...

  Stream<List<int>> get someStream => _someSubject.stream;

  ...

  dispose() async {
    await _someSubject.drain();
    _someSubject.close();
  }

and then call dispose on your page

  @override
  void dispose() {
    _someBloc.dispose();
    super.dispose();
  }

read more about drain and close

Stellar Creed
  • 384
  • 5
  • 14
0

Short answer: there's no easy way.


By default, Dart, at least considering it as a language and VM and not all the tooling around it, won't warn you about leaking memory, You may use profiling tools that may help you identify and fix memory leaks, but it is, after all, a manual work.

If we consider all the tooling that we have, there are tools that may help you to identify potential memory leaks statically. For example, the dart analyzer tool has a built-in linter that detects unclosed sinks, which is one of the potential causes of memory leaks.

Besides this linter, I am not aware of any other tool that statically give you hints about potential memory leaks. Maybe the SonarQube plugin for Dart/Flutter has something, but I never used it so I can't tell.

If you like, you may develop your own static analysis tools for the job by using the analyzer package, and even make it integrated in your editor through analyzer_plugin.

Mateus Felipe
  • 1,071
  • 2
  • 19
  • 43