Unhandled Exception: Bad State: Stream has already been listened to

Viewed 1993

I have the following code to navigate the user to the Home Screen upon successful authentication

Future navigateToHomeScreen(
    StreamedResponse value,
    BuildContext context,
  ) async {
    print('Navigating to Home Screen');
    String userString = await value.stream.bytesToString();
    Map<String, dynamic> logInResponseData = jsonDecode(userString)['data'];
    UserManager.persistUser(logInResponseData);
    Navigator.of(context).pushReplacementNamed(HomeWidget.routePath);
  }

After a successful sign up or sign in the above function is called but I keep getting:

Unhandled Exception: Bad state: Stream has already been listened to.

How do I fix this?

1 Answers

You can't add multiple listeners to a regular stream. In your code, if your navigateToHomeScreen function is getting called multiple times, you are basically adding that many listeners to the stream. You have two ways to fix it.

  1. Check if the stream is already having any listener or not. If it has, remove it before adding a new one.

  2. This is a bit easier one but not the best solution. You can convert your stream to a BroadcastStream by doing : value.stream.asBroadcastStream().bytesToString(); This will convert your regular stream to broadcast stream. By doing this you can add multiple listeners to your stream by why it's not the best option becuase if your previous stream listeners are not killed, they will keep getting notified and will keep consuming your reads. If you are using a service which charge you based on read writes(like cloud firestore) then this might not be a good idea.

https://medium.com/flutter-community/flutter-stream-basics-for-beginners-eda23e44e32f Here is a link to gain better understanding of Streams in Dart and Flutter

Related