Skip to content

Ignore _savedLocale on start when saveLocale is false (#430) #683

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

gkhloptov
Copy link

@gkhloptov gkhloptov commented Jun 3, 2024

Always use startLocale when it's provided and saveLocale is false. Fixes #430

Summary by CodeRabbit

  • Bug Fixes
    • Improved initial language selection: when saving is enabled and a saved language exists, the app now starts in the saved language instead of the configured start language.
    • If saving is disabled or no saved language exists, the app falls back to the configured start language, otherwise to the device language.
    • No behavior changes to logs or settings screens. No public API changes. No user action required.

@gkhloptov gkhloptov changed the title Ignore _savedLocale on start when saveLocale is false Ignore _savedLocale on start when saveLocale is false (#430) Jun 3, 2024
Copy link

coderabbitai bot commented Aug 11, 2025

Walkthrough

Updated locale initialization in EasyLocalizationController to prioritize startLocale when saveLocale is disabled or no saved locale exists. Adjusted conditional logic; no public API changes or logging changes. All modifications are confined to lib/src/easy_localization_controller.dart.

Changes

Cohort / File(s) Summary
Localization init logic
lib/src/easy_localization_controller.dart
Broadened startLocale selection condition to ((!saveLocale

Sequence Diagram(s)

sequenceDiagram
  actor App
  participant Controller as EasyLocalizationController
  participant SP as SharedPreferences
  participant Device as Device Locale

  App->>Controller: initialize(saveLocale, startLocale, forceLocale)
  Controller->>SP: read('locale')
  SP-->>Controller: _savedLocale

  alt forceLocale provided
    Controller->>App: _locale = forceLocale
  else saveLocale && _savedLocale exists
    Controller->>App: _locale = _savedLocale
  else (!saveLocale || _savedLocale == null) && startLocale provided
    Controller->>App: _locale = startLocale (with fallback)
  else
    Controller->>Device: get device locale
    Device-->>Controller: _deviceLocale
    Controller->>App: _locale = match or fallback
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Assessment against linked issues

Objective Addressed Explanation
Ensure startLocale is used when saveLocale=false even if a saved locale exists (#430)
Use a package-specific SharedPreferences key (e.g., easy_localization_locale) to avoid conflicts (#430) Preference key not changed; still reads 'locale'.

Poem

A twitch of whiskers, code hops light,
StartLocale shines, restored to right;
Saved burrow checked—only when told,
Else we choose the start so bold.
Device winds whisper, “maybe later”—
The rabbit stamps: “flow is straighter!” 🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
lib/src/easy_localization_controller.dart (1)

45-51: Add targeted tests for locale resolution order

Existing tests cover saveLocale: false with a provided startLocale, but we’re missing key scenarios around saved locales and device defaults. Please add or verify tests for:

  • saveLocale=false, saved locale exists, startLocale provided → startLocale wins
  • saveLocale=true, saved locale exists, startLocale provided → savedLocale wins
  • saveLocale=false, no startLocale → device locale is used
🧹 Nitpick comments (3)
lib/src/easy_localization_controller.dart (3)

10-15: Consider namespacing the SharedPreferences key and migrating gracefully.

While the logic now ignores _savedLocale when saveLocale=false, using a generic 'locale' key still risks collisions with app-defined values. To avoid interference and be future-proof, consider a namespaced key with backward-compatible migration.

Proposed diffs:

Add a namespaced key constant:

 class EasyLocalizationController extends ChangeNotifier {
   static Locale? _savedLocale;
   static late Locale _deviceLocale;
+  static const String _prefsKey = 'easy_localization.locale';

Use the new key when saving:

   Future<void> _saveLocale(Locale? locale) async {
     if (!saveLocale) return;
     final preferences = await SharedPreferences.getInstance();
-    await preferences.setString('locale', locale.toString());
+    await preferences.setString(_prefsKey, locale.toString());
     EasyLocalization.logger('Locale $locale saved');
   }

Read with migration (prefer new key; fall back to old key once):

   static Future<void> initEasyLocation() async {
     final preferences = await SharedPreferences.getInstance();
-    final strLocale = preferences.getString('locale');
+    String? strLocale = preferences.getString(_prefsKey);
+    strLocale ??= preferences.getString('locale'); // legacy fallback
     _savedLocale = strLocale?.toLocale();

Remove both keys on delete:

   Future<void> deleteSaveLocale() async {
     _savedLocale = null;
     final preferences = await SharedPreferences.getInstance();
-    await preferences.remove('locale');
+    await preferences.remove(_prefsKey);
+    await preferences.remove('locale'); // legacy cleanup
     EasyLocalization.logger('Saved locale deleted');
   }

Also applies to: 199-204, 206-213, 215-220


57-64: Nit: add an explicit log when ignoring a saved locale because saveLocale=false.

Helps diagnose startup behavior when a stray saved value exists.

   } else {
-    // From Device Locale
+    // From Device Locale
+    if (!saveLocale && _savedLocale != null) {
+      EasyLocalization.logger(
+        'Ignoring saved locale $_savedLocale because saveLocale=false',
+      );
+    }
     _locale = selectLocaleFrom(
       supportedLocales,
       _deviceLocale,
       fallbackLocale: fallbackLocale,
     );
   }

45-48: Optional: choose the best supported locale for startLocale.

Today this path sets _locale via _getFallbackLocale(..., startLocale) which returns startLocale directly. If startLocale isn’t in supportedLocales, consider selecting the closest supported match (same language, etc.) for consistency with other code paths.

-    } else if ((!saveLocale || _savedLocale == null) && startLocale != null) {
-      _locale = _getFallbackLocale(supportedLocales, startLocale);
+    } else if ((!saveLocale || _savedLocale == null) && startLocale != null) {
+      _locale = selectLocaleFrom(
+        supportedLocales,
+        startLocale,
+        // fallback to startLocale if nothing matches; behavior remains similar
+        fallbackLocale: startLocale,
+      );
       EasyLocalization.logger('Start locale loaded ${_locale.toString()}');
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c818108 and 856fbac.

📒 Files selected for processing (1)
  • lib/src/easy_localization_controller.dart (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (1)
lib/src/easy_localization_controller.dart (1)

45-48: Fix: startLocale now honored when saveLocale=false (resolves #430).

The widened condition correctly applies startLocale whenever saving is disabled, even if a saved value exists. Precedence is now: forceLocale > startLocale (when !saveLocale or no saved) > savedLocale > device. LGTM.

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.

startLocale may not be used
1 participant