@@ -91,8 +91,8 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
9191
9292 void _handleScrollToBottom ({bool hasAnimation = true }) {
9393 WidgetsBinding .instance.addPostFrameCallback ((_) {
94- final double max = _scrollController.position.maxScrollExtent;
9594 if (! _scrollController.hasClients || ! mounted) return ;
95+ final double max = _scrollController.position.maxScrollExtent;
9696 if (hasAnimation) {
9797 _scrollController.animateTo (
9898 max,
@@ -160,6 +160,31 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
160160 final searchNotifier = ref.read (chatSearchProvider (widget.groupId).notifier);
161161 final isInviteMode = widget.inviteId != null ;
162162
163+ // Watch messages first so they're available for listeners
164+ final messages = ref.watch (
165+ chatProvider.select ((state) => state.groupMessages[widget.groupId] ?? []),
166+ );
167+
168+ // Move ref.listen calls to the main build method
169+ ref.listen (chatSearchProvider (widget.groupId), (previous, next) {
170+ if (next.query.isNotEmpty && next.query != previous? .query) {
171+ searchNotifier.performSearchWithMessages (next.query, messages);
172+ }
173+ });
174+
175+ ref.listen (chatSearchProvider (widget.groupId).select ((state) => state.currentMatchIndex), (
176+ previous,
177+ next,
178+ ) {
179+ final currentMatch = searchNotifier.currentMatch;
180+ if (currentMatch != null ) {
181+ WidgetsBinding .instance.addPostFrameCallback ((_) {
182+ if (! mounted) return ;
183+ _scrollToMessage (currentMatch.messageId);
184+ });
185+ }
186+ });
187+
163188 if (isInviteMode) {
164189 return ChatInviteScreen (
165190 groupId: widget.groupId,
@@ -190,28 +215,6 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
190215
191216 final groupType = groupTypeSnapshot.data! ;
192217
193- final messages = ref.watch (
194- chatProvider.select ((state) => state.groupMessages[widget.groupId] ?? []),
195- );
196-
197- ref.listen (chatSearchProvider (widget.groupId), (previous, next) {
198- if (next.query.isNotEmpty && next.query != previous? .query) {
199- searchNotifier.performSearchWithMessages (next.query, messages);
200- }
201- });
202-
203- ref.listen (chatSearchProvider (widget.groupId).select ((state) => state.currentMatchIndex), (
204- previous,
205- next,
206- ) {
207- final currentMatch = searchNotifier.currentMatch;
208- if (currentMatch != null ) {
209- WidgetsBinding .instance.addPostFrameCallback ((_) {
210- _scrollToMessage (currentMatch.messageId);
211- });
212- }
213- });
214-
215218 return PopScope (
216219 onPopInvokedWithResult: (_, _) {
217220 if (searchState.isSearchActive) {
0 commit comments