【问题标题】:How to save my locale language even after restarting my app即使在重新启动我的应用程序后如何保存我的语言环境
【发布时间】:2022-11-01 17:47:45
【问题描述】:

重新启动我的应用程序后,我获得了默认语言,但我想获得更新的语言

`

void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {


  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    
    return GetMaterialApp(
      translations:  LocalString(),
      locale: const Locale('en', 'US'),
      debugShowCheckedModeBanner: false,
      ),
      home:  homeScreen();

`

【问题讨论】:

标签: flutter dart flutter-dependencies flutter-animation flutter-test


【解决方案1】:

您可以使用共享首选项来存储区域设置,然后在需要时从共享首选项中检索存储的区域设置值。

【讨论】:

    【解决方案2】:

    使用共享首选项:https://pub.dev/packages/shared_preferences

    根据我的经验,使用单例。例子:

    class PrefsInstance {
      static PrefsInstance _instance = new PrefsInstance.internal();
    
      PrefsInstance.internal();
    
      factory PrefsInstance() => _instance;
    
      Future<void> saveAccessToken(String token) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        print("saveAccessToken");
    
        await prefs.setBool(GeneralPrefsConstant.PREF_KEY_LOGIN, true);
        await prefs.setString(GeneralPrefsConstant.PREF_KEY_ACCESS_TOKEN, token);
        DataInstance().isLogin = true;
        DataInstance().accessToken = token;
      }
    
      Future<void> logOut() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        print("LOG OUT -> FIX SHARED PREFERENCES");
    
        await prefs.setBool(GeneralPrefsConstant.PREF_KEY_LOGIN, false);
        await prefs.setString(GeneralPrefsConstant.PREF_KEY_ACCESS_TOKEN, "");
        await prefs.setString(GeneralPrefsConstant.PREF_KEY_PROFILE, "");
        DataInstance().isLogin = false;
        DataInstance().accessToken = "";
      }
    
      saveLanguage() async {...}
    }
    

    共享偏好变量将保存到您手机的内存中,并且在您关闭应用程序时不会消失。每个变量都有特定的键 (GeneralPrefsConstant)。它很容易使用。如果要保存,请使用异步方法setString(key, value)。如果你想得到,使用getString(key)(不是异步的)。如果您的应用是第一次安装,则在获取共享偏好时可能会为空,因此需要仔细检查。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多