Gordon Hayes
Gordon Hayes

Reputation: 271

Initialise Stream Chat Flutter in part of the application (widget tree)

I'm creating an application with chat functionality and I'm using Stream Chat Flutter. I followed the official tutorial: https://getstream.io/chat/flutter/tutorial/

The tutorial says to use the builder in MaterialApp and wrap the child route with StreamChat.

return MaterialApp(
  builder: (context, widget) {
    return StreamChat(
      client: client,
      child: widget,
    );
  },
  home: StreamChannel(
    channel: channel,
    child: const ChannelPage(),
  ),
);

And to then call client.connectUser.

I want to know how I can efficiently disconnect and reconnect a user and make sure the web socket connections are closed, without wrapping my whole application with StreamChat.

Most of the Stream examples show how to initialise and connect users for the whole application and then they stay connected. But I only want to initialise and connect to Stream when the chat portion of the app is opened.

Upvotes: 2

Views: 773

Answers (1)

Gordon Hayes
Gordon Hayes

Reputation: 271

The solution to this requires two things:

  • understanding routing in Flutter
  • and managing the connection status of your Stream user depending on the current route

It is important to understand that a WebSocket connection is only made to Stream when you call connectUser. And that there is only a small overhead when wrapping your entire widget tree with StreamChat. The WebSocket connection is then closed when you call disconnectUser.

This official guide demos three ways to manage a Stream Chat Flutter connection and only have Stream chat in a part of an application (widget tree) and explains everything in detail.

  1. Builder and Connect/Disconnect User
  2. A Nested Navigator
  3. Flutter Navigator 2.0 - Using GoRouter

Upvotes: 10

Related Questions