Skip to content

fix: resolve BuildContext async gaps across patient and therapist apps#210

Open
suhas2006-code wants to merge 1 commit intoAOSSIE-Org:mainfrom
suhas2006-code:fix/build-context-async-gaps-197
Open

fix: resolve BuildContext async gaps across patient and therapist apps#210
suhas2006-code wants to merge 1 commit intoAOSSIE-Org:mainfrom
suhas2006-code:fix/build-context-async-gaps-197

Conversation

@suhas2006-code
Copy link
Copy Markdown

@suhas2006-code suhas2006-code commented Mar 22, 2026

Summary

Resolves #197 by fixing all BuildContext usage across async gaps in both patient and therapist applications.

Changes Made

Patient App

book_appointment.dart:

  • Refactored _selectDate() method to use instance context instead of parameter
  • Added proper mounted check before using BuildContext after async operations
  • Eliminated "unrelated mounted check" by restructuring conditional logic

therapist_provider.dart:

  • Captured ScaffoldMessengerState before any async gaps to prevent context usage issues
  • Moved context capture to the beginning of the method before the first await call

Therapist App

personal_details_screen.dart:

  • Captured Navigator and ScaffoldMessenger states before async operations
  • Added proper mounted check after async call
  • Restructured error handling to use captured states instead of raw context

Technical Details

  • Root Cause: Flutter's BuildContext becomes invalid after async operations when widgets are disposed
  • Solution: Capture widget context references before await calls and add mounted checks
  • Safety: All UI operations (navigation, snackbars) now safely handle widget disposal scenarios

Testing

  • ✅ Ran flutter analyze on both apps - no use_build_context_synchronously warnings remain
  • ✅ Verified all async operations handle context safely
  • ✅ Confirmed proper memory leak prevention with mounted checks
  • ✅ Tested UI interactions work correctly after async operations

Quality Assurance

  • All changes maintain existing functionality while improving safety
  • Error handling remains intact with proper user feedback
  • No breaking changes to existing workflows

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Refactor
    • Enhanced code robustness in appointment booking, therapist management, and authentication flows with improved handling of UI state during screen transitions and dialog interactions, ensuring more reliable and stable user experience across these workflows.

Fixes AOSSIE-Org#197

## Changes
**Patient App:**
- Fixed BuildContext usage in `book_appointment.dart` by refactoring `_selectDate()` to use instance context and added proper mounted checks
- Fixed BuildContext usage in `therapist_provider.dart` by capturing ScaffoldMessengerState before async gaps

**Therapist App:**
- Fixed BuildContext usage in `personal_details_screen.dart` by capturing Navigator and ScaffoldMessenger states before async operations

## Technical Details
- Resolved "Don't use BuildContext across async gaps" warnings by capturing widget context before await calls
- Added proper mounted checks to prevent memory leaks and context usage after widget disposal
- Ensures UI operations (navigation, snackbars) are safely performed after async operations

## Testing
Verified with `flutter analyze` - no use_build_context_synchronously warnings remain in either app.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 22, 2026

📝 Walkthrough

Walkthrough

Three files updated to fix use_build_context_synchronously lint warnings by capturing context references before async operations and adding mounted guards after awaits. Refactored method signatures to remove unnecessary BuildContext parameters in favor of ambient context field access.

Changes

Cohort / File(s) Summary
Context Capture Before Async
patient/lib/provider/therapist_provider.dart, therapist/lib/presentation/auth/personal_details_screen.dart
Captured ScaffoldMessenger.of(context) and/or Navigator.of(context) into local variables before awaiting async operations, then used captured references instead of re-calling context methods after the await to prevent lint violations.
Method Signature Cleanup & Mounted Guards
patient/lib/presentation/result/book_appointment.dart
Removed BuildContext parameters from _selectDate() and _selectTimeSlot() private methods, added early-return logic for null/unchanged values, and introduced if (!mounted) return; guard after setState to prevent context access on unmounted widgets. Updated button handler to use method reference instead of closure.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • jddeep

Poem

🐰 Hopping through the async fray,
We captured context before the await-delay,
No more lint warnings, mounted checks in place,
BuildContext walks at a safer pace!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: fixing BuildContext async gaps across both patient and therapist apps, which matches the core objective of the PR.
Linked Issues check ✅ Passed All four flagged locations identified in issue #197 have been addressed with appropriate fixes: context capture before awaits and mounted guards added where needed.
Out of Scope Changes check ✅ Passed All changes are directly related to resolving issue #197. No unrelated modifications to other functionality or systems were introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

You can customize the tone of the review comments and chat replies.

Configure the tone_instructions setting to customize the tone of the review comments and chat replies. For example, you can set the tone to Act like a strict teacher, Act like a pirate and more.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
patient/lib/provider/therapist_provider.dart (1)

1-7: ⚠️ Potential issue | 🟡 Minor

Duplicate import of flutter/material.dart.

Line 1 and Line 6 both import the same package. Remove one of the duplicates.

🧹 Proposed fix
 import 'package:flutter/material.dart';
 import 'package:flutter_dotenv/flutter_dotenv.dart';
 import 'package:patient/presentation/assessments/models/assessment_card_model.dart';
 import 'package:patient/repository/supabase_assessments_repository.dart';
 
-import 'package:flutter/material.dart';
 import 'package:supabase_flutter/supabase_flutter.dart';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@patient/lib/provider/therapist_provider.dart` around lines 1 - 7, Remove the
duplicate import of flutter/material.dart in therapist_provider.dart by deleting
one of the two identical lines (either the first or the sixth import) so only a
single import 'package:flutter/material.dart' remains; after removal, ensure the
remaining imports (including dotenv, assessment_card_model,
supabase_assessments_repository, and supabase_flutter) are correctly ordered and
there are no unused import statements left.
🧹 Nitpick comments (2)
patient/lib/presentation/result/book_appointment.dart (2)

49-59: Redundant mounted check on line 57.

The mounted check on line 50 already guards against widget disposal - if not mounted, the function returns early. The subsequent check on line 57 is therefore redundant since setState on lines 52-55 would have already been skipped or the function would have returned.

🧹 Proposed simplification
     if (picked == null || picked == selectedDate) return;
     if (!mounted) return;
 
     setState(() {
       selectedDate = picked;
       selectedTimeSlot = null; // Reset time slot when date changes
     });
 
-    if (mounted) {
-      _selectTimeSlot();
-    }
+    _selectTimeSlot();
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@patient/lib/presentation/result/book_appointment.dart` around lines 49 - 59,
Remove the redundant mounted check after setState: the early return if
(!mounted) already prevents running on a disposed widget, so delete the if
(mounted) { _selectTimeSlot(); } block and call _selectTimeSlot() directly after
setState (keeping the setState that updates selectedDate and resets
selectedTimeSlot) so the flow is: validate picked, return if not mounted,
setState(...), then _selectTimeSlot().

63-85: Consider using ctx in Navigator.pop for consistency.

Inside the builder callback, you have access to ctx (the builder's context). Using Navigator.pop(ctx) instead of Navigator.pop(context) on line 77 would be more consistent, though both work correctly in this case.

🧹 Proposed fix
                 onTap: () {
                   setState(() {
                     selectedTimeSlot = slot;
                   });
-                  Navigator.pop(context); // Close modal
+                  Navigator.pop(ctx); // Close modal
                 },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@patient/lib/presentation/result/book_appointment.dart` around lines 63 - 85,
The modal builder uses a local BuildContext variable named ctx but the code
calls Navigator.pop(context); update _selectTimeSlot to call Navigator.pop(ctx)
inside the builder's onTap so the pop uses the builder's context (replace
Navigator.pop(context) with Navigator.pop(ctx) in the ListTile onTap within the
builder closure).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@patient/lib/provider/therapist_provider.dart`:
- Around line 1-7: Remove the duplicate import of flutter/material.dart in
therapist_provider.dart by deleting one of the two identical lines (either the
first or the sixth import) so only a single import
'package:flutter/material.dart' remains; after removal, ensure the remaining
imports (including dotenv, assessment_card_model,
supabase_assessments_repository, and supabase_flutter) are correctly ordered and
there are no unused import statements left.

---

Nitpick comments:
In `@patient/lib/presentation/result/book_appointment.dart`:
- Around line 49-59: Remove the redundant mounted check after setState: the
early return if (!mounted) already prevents running on a disposed widget, so
delete the if (mounted) { _selectTimeSlot(); } block and call _selectTimeSlot()
directly after setState (keeping the setState that updates selectedDate and
resets selectedTimeSlot) so the flow is: validate picked, return if not mounted,
setState(...), then _selectTimeSlot().
- Around line 63-85: The modal builder uses a local BuildContext variable named
ctx but the code calls Navigator.pop(context); update _selectTimeSlot to call
Navigator.pop(ctx) inside the builder's onTap so the pop uses the builder's
context (replace Navigator.pop(context) with Navigator.pop(ctx) in the ListTile
onTap within the builder closure).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fdad5149-53e0-478a-ace6-39b3773cc9a2

📥 Commits

Reviewing files that changed from the base of the PR and between 051a4f3 and 491d578.

📒 Files selected for processing (3)
  • patient/lib/presentation/result/book_appointment.dart
  • patient/lib/provider/therapist_provider.dart
  • therapist/lib/presentation/auth/personal_details_screen.dart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: Don't use BuildContext across async gaps (use_build_context_synchronously)

1 participant