Skip to content

3、Chat Observer

林洵锋 edited this page Sep 23, 2023 · 3 revisions

3.1、Basic usage

We only need three steps to implement the chat session page effect.

  • 1、All chat data are displayed at the top of the listView when there is less than one screen of chat data.
  • 2、When inserting a chat data
    • If the latest message is close to the bottom of the list, the listView will be pushed up.
    • Otherwise, the listView will be fixed to the current chat position.

Step 1: Initialize the necessary ListObserverController and ChatScrollObserver.

/// Initialize ListObserverController
observerController = ListObserverController(controller: scrollController)
  ..cacheJumpIndexOffset = false;

/// Initialize ChatScrollObserver
chatObserver = ChatScrollObserver(observerController)
  // Greater than this offset will be fixed to the current chat position.
  ..fixedPositionOffset = 5
  ..toRebuildScrollViewCallback = () {
    // Here you can use other way to rebuild the specified listView instead of [setState]
    setState(() {});
  };

Step 2: Configure ListView as follows and wrap it with ListViewObserver.

Widget _buildListView() {
  Widget resultWidget = ListView.builder(
    physics: ChatObserverClampingScrollPhysics(observer: chatObserver),
    shrinkWrap: chatObserver.isShrinkWrap,
    reverse: true,
    controller: scrollController,
    ...
  );

  resultWidget = ListViewObserver(
    controller: observerController,
    child: resultWidget,
  );
  return resultWidget;
}

Step 3: Call the [standby] method of ChatScrollObserver before inserting or removing chat data.

onPressed: () {
  chatObserver.standby();
  setState(() {
    chatModels.insert(0, ChatDataHelper.createChatModel());
  });
},
...
onRemove: () {
  chatObserver.standby(isRemove: true);
  setState(() {
    chatModels.removeAt(index);
  });
},

This feature only handles inserting one message by default. If you need to insert multiple messages at once, you can pass the changeCount parameter to the standby method.

_addMessage(int count) {
  chatObserver.standby(changeCount: count);
  setState(() {
    needIncrementUnreadMsgCount = true;
    for (var i = 0; i < count; i++) {
      chatModels.insert(0, ChatDataHelper.createChatModel());
    }
  });
}

Note: This feature relies on the latest message view before the message is inserted as a reference to calculate the offset, so if too many messages are inserted at once and the reference message view cannot be rendered, this feature will fail, and you need to try to avoid this problem by setting a reasonable value for cacheExtent of ScrollView by yourself!

3.2、The result callback for processing chat position.

chatObserver = ChatScrollObserver(observerController)
  ..onHandlePositionResultCallback = (result) {
    switch (result.type) {
      case ChatScrollObserverHandlePositionType.keepPosition:
        // Keep the current chat position.
        // updateUnreadMsgCount(changeCount: result.changeCount);
        break;
      case ChatScrollObserverHandlePositionType.none:
        // Do nothing about the chat position.
        // updateUnreadMsgCount(isReset: true);
        break;
    }
  };

This callback is mainly used to display the unread bubbles of new messages when adding chat messages.

3.3、Generative message keeps position

The generative messages like ChatGPT also need to keep the message position when looking through old messages, you only need to adjust the processing mode in the standby method.

chatObserver.standby(
  mode: ChatScrollObserverHandleMode.generative,
  // changeCount: 1,
);

Note: The referenced item will be determined internally based on changeCount, and this mode only supports the case where generative messages are continuous.

3.4、Specifies the referenced item

If your generative messages are discontinuous, or there are generative message updates and the behavior of adding and deleting messages at the same time, in this complex case, you need to specify the referenced item by yourself, and This processing mode is more flexible.

chatObserver.standby(
  changeCount: 1,
  mode: ChatScrollObserverHandleMode.specified,
  refItemRelativeIndex: 2,
  refItemRelativeIndexAfterUpdate: 2,
);
  1. Set mode to .specified.
  2. Set refItemRelativeIndex to relative index of the referenced item before the update.
  3. Set refItemRelativeIndexAfterUpdate to relative index of the referenced item after the update.

Note: The relativeIndex refers to the relative index of the item being displayed on screen, as shown below

     trailing        relativeIndex
-----------------  -----------------
|     item4     |          4
|     item3     |          3
|     item2     |          2
|     item1     |          1
|     item0     |          0 
-----------------  -----------------
     leading
     trailing        relativeIndex
-----------------  -----------------
|     item14    |          4
|     item13    |          3
|     item12    |          2
|     item11    |          1
|     item10    |          0 
-----------------  -----------------
     leading

Remember, your refItemRelativeIndex and refItemRelativeIndexAfterUpdate should point to the same message object whatever you set!