Skip to content
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

Problem when switching system language on android #1704

Closed
uberchilly opened this issue Jul 29, 2021 · 8 comments
Closed

Problem when switching system language on android #1704

uberchilly opened this issue Jul 29, 2021 · 8 comments
Assignees

Comments

@uberchilly
Copy link

Describe the bug
Switching system language in settings and going back to the app on android doesn't change the app's language

**Reproduction code
example:

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:google_fonts/google_fonts.dart';

void main() async {
  runApp(MyApp());
}

class Messages extends Translations {
  @override
  Map<String, Map<String, String>> get keys => {
        'en_US': {
          'login': 'Login',
          'registration': "Registration",
          'nexoslav': 'Nexoslav',
        },
        'fr_FR': {
          'login': 'sdkadmka',
          'registration': 'sad,amdkadmka',
          'nexoslav': 'n21uijn31n3hjqnhj',
        }
      };
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      translations: Messages(),
      // your translations
      fallbackLocale: Locale('en', 'US'),
      locale: Get.deviceLocale,
      supportedLocales: [Locale('en', 'US'), Locale('fr', 'FR')],
      title: 'Flutter Demo',
      theme: MyTheme.themeLight(),
      darkTheme: MyTheme.themeDark(),
      home: LoginStartScreen(),
    );
  }
}

class LoginStartScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    context
        .theme; //this is necessary so that widget gets rebuild with new theme
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 34.0),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 15.0),
                child: Icon(
                  Icons.wc,
                  size: 20.0,
                ),
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Flexible(
                      child: Container(),
                      flex: 1,
                    ),
                    GestureDetector(
                      onTap: () {},
                      child: Text(
                        "Hello ${Get.deviceLocale.toString()}",
                        style: MyTheme.pageTitle(),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 16.0),
                      child: Text(
                        "Bring transparency to your energy and be part of tomorrow\'s energy supply. With \"Home\" you build up the necessary knowledge and know-how about your energy and CO₂ consumption. You can track and analyse your data in real-time and make the right decisions, e.g. choose an electricity product from local, sustainable energy sources.",
                        style: MyTheme.body(),
                      ),
                    ),
                    Flexible(
                      child: Container(),
                      flex: 2,
                    ),
                  ],
                ),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(vertical: 12),
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(34.0)),
                  ),
                ),
                onPressed: () {
                  Get.updateLocale(Locale("en", "US"));
                },
                child: Text('registration'.tr),
              ),
              ElevatedButton(
                onPressed: () {
                  Get.updateLocale(Locale("fr", "FR"));
                },
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(vertical: 12),
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(34.0)),
                  ),
                ),
                child: Text(
                  'login'.tr,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class MyColors {
  static final backgroundColorLight = HexColor.fromHex('#F0F7F3');
  static final backgroundColorDark = HexColor.fromHex('#293330');
  static Color backgroundColor =
  Get.isPlatformDarkMode ? backgroundColorDark : backgroundColorLight;

  static final textColorLight = HexColor.fromHex('#293330');
  static final textColorDark = HexColor.fromHex('#FFFFFF');
  static Color textColor() =>
      Get.isPlatformDarkMode ? textColorDark : textColorLight;
}

class MyTheme {
  static themeLight() => ThemeData.light().copyWith(
    scaffoldBackgroundColor: MyColors.backgroundColorLight,
  );

  static themeDark() => ThemeData.dark().copyWith(
    scaffoldBackgroundColor: MyColors.backgroundColorDark,
  );

  static TextStyle mainTextStyle() => GoogleFonts.openSans(
    fontWeight: FontWeight.w400,
    color: MyColors.textColor(),
  );

  static TextStyle mainTextStyleBold() => mainTextStyle().copyWith(
    fontWeight: FontWeight.w700,
  );

  static TextStyle pageTitle() => mainTextStyleBold().copyWith(fontSize: 22.0);

  static TextStyle paragraph() => mainTextStyle().copyWith(fontSize: 14.0);

  static TextStyle body() => mainTextStyle().copyWith(
    fontSize: 16.0,
    fontFeatures: [FontFeature("tnum"), FontFeature('lnum')],
    height: 1,
  );

  static TextStyle bodyBold() => body().copyWith(
    fontWeight: FontWeight.w700,
  );
}

extension HexColor on Color {
  /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${alpha.toRadixString(16).padLeft(2, '0')}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';
}

To Reproduce
Steps to reproduce the behavior:

  1. Open the app, it will pick up system language correctly
  2. Open android's system settings and swich language from en_US to fr_FR
  3. Return back to the app
  4. See app still displaying en_US

Expected behavior
App changes language to fr_FR

Screenshots
image
image
image

Flutter Version:
Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19042.1110]

Getx Version:
^4.3.0

Describe on which device you found the bug:
Samsung galaxy s21 and every other device and emulator that I have tried

@eduardoflorence
Copy link
Collaborator

Hi @uberchilly, I have an example of language switching at the link below, see if it can help you

https://gist.github.com/eduardoflorence/9503ca35950559618da71f55a74b6562

@uberchilly
Copy link
Author

@eduardoflorence Thank you. I am not trying to switch language by user action, I am trying to make my app follow the system's language like it is the default behavior on Android. Will the code sample above do that?

@ghost
Copy link

ghost commented Aug 9, 2021

Hello, i am irritated too, how do i watch the device locale with getX? When deviceLocale (Get.deviceLocale) is changed in system settings i want to change my app automatically - but actually I have no idea how to hook in the deviceLocale?

I would like to get the minimum sample code for it please

@ghost
Copy link

ghost commented Aug 10, 2021

@uberchilly Do you have a solution so far?

@ghost
Copy link

ghost commented Aug 15, 2021

@jonataslaw can you help please? How to simply watch deviceLocale ?

@ghost
Copy link

ghost commented Aug 17, 2021

I did it using WidgetsBindingObserver in AppLifecycleState.resumed. This is the preferred solution @uberchilly

You can go this way (...Get.updateLocale(Get.deviceLocale!);...) or even directly in didChangeLocales().

@jonataslaw
Copy link
Owner

Maybe related #2019

@uberchilly
Copy link
Author

This works for me in getx 4.5.1. I am closing the issue.

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

No branches or pull requests

3 participants