Skip to content

Move authStateChanges() Listener from App Constructor to initState() to Prevent Multiple Subscriptions in main.dart #2

@haider-nawaz

Description

@haider-nawaz

Is there a specific reason to why the authStateChanges() listener was placed in the Constructor instead of the initState() ?

Currently, the FirebaseAuth.instance.authStateChanges().listen(...) call is placed inside the App widget's constructor. This can lead to multiple redundant subscriptions if the App widget is reconstructed, causing unexpected behavior such as:

  1. Multiple listeners being attached to the Firebase authentication stream.
  2. Unnecessary state updates to LoginInfo.instance.user and ChatRepository.user.
  3. Potential memory leaks, since the listener is not properly managed within the widget lifecycle.

Proposed Change:
Move the listener logic to _AppState.initState(), ensuring that it is attached only once when the widget is first created.
Store the subscription in a variable and properly cancel it in dispose() to prevent memory leaks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions