Skip to content

Conversation

@NitinSohal
Copy link

@NitinSohal NitinSohal commented Apr 6, 2025

Fixes #

Describe the changes you have made in this PR -

This PR improves the language switcher in the app drawer by turning it into a custom-designed toggle-like segmented control. Instead of a standard switch, it uses two stylized buttons ("English" and "हिंदी") to clearly represent the current language. The switcher is placed on the left side with an accompanying translate icon for better visual context.

  • Replaced the basic language toggle with a visually appealing segmented control.
  • Positioned the toggle on the left with an icon to enhance alignment and clarity.
  • Added smooth animation to transitions between English and Hindi for better feedback.
  • Ensured visual balance between both language options with consistent padding and minimum width.
  • Improved accessibility and visual appeal by making the text size adaptive while keeping design consistency.

Screenshots of the changes (If any) -

Screenshot 2025-04-06 at 6 12 15 PM Screenshot 2025-04-06 at 6 11 53 PM Screenshot 2025-04-06 at 6 11 22 PM Screenshot 2025-04-06 at 6 10 46 PM

Note: Please check Allow edits from maintainers. if you would like us to assist in the PR.

Summary by CodeRabbit

  • New Features

    • Introduced an in-app language toggle enabling users to switch seamlessly between English and Hindi.
    • Enhanced overall localization so the app dynamically updates content based on the selected language.
    • Updated the user interface to remove development banners, ensuring a cleaner and more polished experience.
    • Added a language selection feature within the drawer for improved accessibility.
  • Localization Updates

    • Expanded localization files to include new entries for the term "Language" in both English and Hindi.

@coderabbitai
Copy link

coderabbitai bot commented Apr 6, 2025

Walkthrough

This update introduces a dedicated LanguageController to manage the application's locale. A new LanguageController class is added to handle locale settings and toggling between English and Hindi. The application startup in main.dart is updated to initialize this controller and configure the localization settings, including a fallback locale and title generation. Additionally, the UI in the drawer is enhanced with a language selection feature using reactive widgets, allowing users to switch languages directly from the drawer.

Changes

Files Change Summary
lib/controllers/language_controller.dart Added a new LanguageController class that extends GetxController. It manages an observable locale and provides methods to change and toggle the language selection state.
lib/main.dart Integrated the LanguageController by adding an import statement, initializing it with Get.put(), and updating GetMaterialApp with locale settings and a fallback locale. The onGenerateTitle method's syntax was simplified.
lib/ui/components/cv_drawer.dart Added a language selection feature in the CVDrawer class, including an Obx widget to react to language changes and an ExpansionTile for language options, allowing users to select between English and Hindi.
lib/l10n/app_en.arb Added a new key-value pair "language": "Language" to the English localization file to expand localization capabilities.
lib/l10n/app_hi.arb Added a new key-value pair "language": "भाषा" to the Hindi localization file and reformatted an existing string for consistent spacing.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc0ce74 and 9631571.

📒 Files selected for processing (4)
  • lib/controllers/language_controller.dart (1 hunks)
  • lib/l10n/app_en.arb (1 hunks)
  • lib/l10n/app_hi.arb (1 hunks)
  • lib/ui/components/cv_drawer.dart (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: build (macos-latest)
🔇 Additional comments (5)
lib/l10n/app_hi.arb (1)

118-119: LGTM! Added Hindi translation for the language label.

The translation for "language" has been properly added as "भाषा" in the Hindi localization file, which will be displayed in the new language toggle component in the drawer.

lib/l10n/app_en.arb (1)

118-119: LGTM! Added English translation for the language label.

The localization string for "language" has been properly added to the English localization file, supporting the new language toggle feature in the drawer.

lib/controllers/language_controller.dart (1)

1-17: Well-structured controller for language management.

The LanguageController follows good practices with GetX by:

  1. Using observable variables for reactive state management
  2. Implementing clear methods for changing language and toggling expansion
  3. Properly updating the app locale with Get.updateLocale()

The controller fulfills its responsibility of managing the application's language state.

lib/ui/components/cv_drawer.dart (2)

6-6: LGTM! Added import for the LanguageController.

Properly imports the new controller for language management functionality.


46-100: Well-implemented language selection component in the drawer.

The language toggle implementation:

  1. Uses reactive state management with Obx for automatic UI updates
  2. Provides clear visual feedback with radio buttons for selected language
  3. Follows existing drawer UI patterns for consistency
  4. Properly handles language changing and expansion state

This implementation nicely fulfills the PR objective of adding language toggle functionality to the drawer section.


🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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

🧹 Nitpick comments (3)
lib/controllers/language_controller.dart (1)

1-15: Good implementation of language toggle functionality

The LanguageController class is well-structured and correctly implements a simple language toggle between English and Hindi using GetX's reactive state management.

I have a few suggestions for improvements:

Consider adding the following enhancements:

  1. Add documentation comments to describe the class and method purpose
  2. Implement persistence of language preference across app restarts
  3. Make the implementation more extensible for supporting additional languages in the future
 import 'package:get/get.dart';
 import 'package:flutter/material.dart';
+import 'package:shared_preferences/shared_preferences.dart';
 
+/// Controller responsible for managing application language/locale
+/// Currently supports toggling between English and Hindi
 class LanguageController extends GetxController {
   final currentLocale = const Locale('en').obs;
+  static const String _localeKey = 'app_locale';
+  
+  @override
+  void onInit() {
+    super.onInit();
+    _loadSavedLocale();
+  }
+
+  Future<void> _loadSavedLocale() async {
+    final prefs = await SharedPreferences.getInstance();
+    final savedLocale = prefs.getString(_localeKey);
+    if (savedLocale != null) {
+      currentLocale.value = Locale(savedLocale);
+      Get.updateLocale(currentLocale.value);
+    }
+  }
 
+  /// Toggles the application language between English and Hindi
   void toggleLanguage() {
     if (currentLocale.value.languageCode == 'en') {
       currentLocale.value = const Locale('hi');
     } else {
       currentLocale.value = const Locale('en');
     }
     Get.updateLocale(currentLocale.value);
+    _saveLocale(currentLocale.value.languageCode);
+  }
+  
+  Future<void> _saveLocale(String languageCode) async {
+    final prefs = await SharedPreferences.getInstance();
+    await prefs.setString(_localeKey, languageCode);
   }
 }
lib/ui/components/cv_drawer.dart (1)

46-139: Well-implemented language toggle UI with smooth animations

The language toggle UI implementation aligns with the PR objectives, featuring a custom-designed segmented control with stylized buttons, a translate icon, and smooth animations.

Consider these improvements to enhance maintainability and accessibility:

  1. Extract the repeated container styles into a reusable widget to reduce code duplication
  2. Use localized strings instead of hardcoded text labels
  3. Add semantic labels for accessibility
 Obx(() {
   final langController = Get.find<LanguageController>();
   final isEnglish =
       langController.currentLocale.value.languageCode == 'en';

   return Padding(
     padding: const EdgeInsets.symmetric(
       horizontal: 16,
       vertical: 10,
     ),
     child: Row(
       mainAxisAlignment: MainAxisAlignment.start,
       children: [
         Icon(
           Icons.translate_sharp,
           color: CVTheme.drawerIcon(
             context,
-          ), // You can pick any color
+          ),
+          semanticLabel: 'Language selection icon',
         ),
         const SizedBox(
           width: 12,
-        ), // spacing between icon and toggle
+        ),
         Container(
           decoration: BoxDecoration(
             borderRadius: BorderRadius.circular(30),
           ),
           padding: const EdgeInsets.all(4),
           child: Row(
             children: [
-              GestureDetector(
-                onTap: () {
-                  if (!isEnglish) langController.toggleLanguage();
-                },
-                child: AnimatedContainer(
-                  duration: const Duration(milliseconds: 250),
-                  curve: Curves.easeInOut,
-                  padding: const EdgeInsets.symmetric(
-                    horizontal: 16,
-                    vertical: 8,
-                  ),
-                  decoration: BoxDecoration(
-                    color:
-                        isEnglish
-                            ? CVTheme.primaryColor
-                            : Colors.transparent,
-                    borderRadius: BorderRadius.circular(20),
-                  ),
-                  child: Text(
-                    'English',
-                    style: TextStyle(
-                      color:
-                          isEnglish
-                              ? Colors.white
-                              : CVTheme.textColor(context),
-                    ),
-                  ),
-                ),
-              ),
-              GestureDetector(
-                onTap: () {
-                  if (isEnglish) langController.toggleLanguage();
-                },
-                child: AnimatedContainer(
-                  duration: const Duration(milliseconds: 250),
-                  curve: Curves.easeInOut,
-                  padding: const EdgeInsets.symmetric(
-                    horizontal: 16,
-                    vertical: 8,
-                  ),
-                  decoration: BoxDecoration(
-                    color:
-                        !isEnglish
-                            ? CVTheme.primaryColor
-                            : Colors.transparent,
-                    borderRadius: BorderRadius.circular(20),
-                  ),
-                  child: Text(
-                    'हिंदी',
-                    style: TextStyle(
-                      color:
-                          !isEnglish
-                              ? Colors.white
-                              : CVTheme.textColor(context),
-                    ),
-                  ),
-                ),
-              ),
+              _buildLanguageButton(
+                label: 'English',
+                isSelected: isEnglish,
+                onTap: () => !isEnglish ? langController.toggleLanguage() : null,
+                context: context,
+              ),
+              _buildLanguageButton(
+                label: 'हिंदी',
+                isSelected: !isEnglish,
+                onTap: () => isEnglish ? langController.toggleLanguage() : null,
+                context: context,
+              ),
             ],
           ),
         ),
       ],
     ),
   );
 }),

Add this helper method after the build method:

Widget _buildLanguageButton({
  required String label,
  required bool isSelected,
  required VoidCallback? onTap,
  required BuildContext context,
}) {
  return Semantics(
    button: true,
    selected: isSelected,
    label: 'Switch to $label',
    child: GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 250),
        curve: Curves.easeInOut,
        padding: const EdgeInsets.symmetric(
          horizontal: 16,
          vertical: 8,
        ),
        decoration: BoxDecoration(
          color: isSelected ? CVTheme.primaryColor : Colors.transparent,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : CVTheme.textColor(context),
          ),
        ),
      ),
    ),
  );
}
lib/main.dart (1)

81-87: Proper configuration of localization settings

The localization settings are correctly configured with the LanguageController. Setting the fallback locale to English is appropriate, and removing the debug banner enhances the app's appearance.

For better separation of concerns, consider moving the controller initialization to a dedicated setup method:

 Future<void> main() async {
   WidgetsFlutterBinding.ensureInitialized();

   // Register all the models and services before the app starts
   await setupLocator();

   // Init Hive
   await locator<DatabaseService>().init();
-  Get.put(LanguageController());
+  _initializeControllers();

   runApp(const CircuitVerseMobile());
 }

+// Initialize GetX controllers
+void _initializeControllers() {
+  Get.put(LanguageController());
+  // Add other controllers here as needed
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between da4e7ed and fc0ce74.

📒 Files selected for processing (3)
  • lib/controllers/language_controller.dart (1 hunks)
  • lib/main.dart (3 hunks)
  • lib/ui/components/cv_drawer.dart (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (1)
lib/main.dart (1)

7-7: Good integration of the LanguageController

The import and initialization of the LanguageController is properly implemented.

Also applies to: 23-23

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.

1 participant