2

First I created the GetxController class

  final languageController = GetStorage();

  var myLocal = [];

  void saveLocale(List list) {
    languageController.write('savedLocale', list);
  }

  @override
  void onInit() {
    List<dynamic>? savedLocale = languageController.read('savedLocale');
    if (savedLocale != null) {
      myLocal = savedLocale;
    }
    super.onInit();
  }
}

Then I initialized GetStorage in main.dart

final myLocal = LanguageController().myLocal;

void main() async {
  print(myLocal);
  await GetStorage.init();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      translations: LocaleString(),
      locale: myLocal.isNotEmpty
          ? Locale(myLocal[0], myLocal[1])
          : Locale('en', 'US'),
      debugShowCheckedModeBanner: false,
      home: HomeScreen(),
    );
  }
}

And then in the dialog after setting the locale I writes it in storage

Future<dynamic> myMaterialDialog(BuildContext context) {
  final LanguageController languageController = Get.find();

  return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(chooseLanguage.tr),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextButton(
                onPressed: () {
                  Get.back();
                  Get.updateLocale(Locale('en', 'US'));
                  languageController.saveLocale(['en', 'US']);
                },
                child: Text(englishLanguage.tr),
              ),
              TextButton(
                onPressed: () {
                  Get.back();
                  Get.updateLocale(Locale('ru', 'RU'));
                  languageController.saveLocale(['ru', 'RU']);
                },
                child: Text(russianLanguage.tr),
              ),
            ],
          ),
        );
      });
}

And it's not working, every time I restarted my app it's shows 1 what myLocale is empty

To check if saveLocale() method is working, I created printSavedLocale() method

 void printSavedLocale() {
    print(languageController.read('savedLocale'));
  }

and put it to dialoge button after saveLocale() and it's printing my saved locale, but after restarting saved locale is null

brennschluss
  • 21
  • 1
  • 1
  • 3
  • I solved this problem with reading from getx storage directly from main.dart, somehow it's not parsing data from the GetxController class – brennschluss Sep 21 '21 at 20:54

3 Answers3

4

use this static methods. put them anywhere in your project:

void setData(String key, dynamic value) => GetStorage().write(key, value);

int? getInt(String key) => GetStorage().read(key);

String? getString(String key) => GetStorage().read(key);

bool? getBool(String key) => GetStorage().read(key);

double? getDouble(String key) => GetStorage().read(key);

dynamic getData(String key) => GetStorage().read(key);

void clearData() async => GetStorage().erase();
SinaMN75
  • 6,742
  • 5
  • 28
  • 56
  • I am already using this, for setData I am using ```void saveLocale(List list) { languageController.write('savedLocale', list); } ``` for getting I am using ``` List? savedLocale = languageController.read('savedLocale'); ``` now I will try with strings instead of list – brennschluss Sep 21 '21 at 19:48
0

I can solove this by reading from the storage directly from main.dart

final LanguageController languageController = Get.put(LanguageController());
final myLocal = LanguageController().readSavedLocale();

void main() async {
  await GetStorage.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      translations: LocaleString(),
      locale: myLocal.isNotEmpty
          ? Locale(myLocal[0], myLocal[1])
          : Locale('en', 'US'),
      debugShowCheckedModeBanner: false,
      home: HomeScreen(),
    );
  }
}

And readSavedLocale() method is

List readSavedLocale() {
    var savedLocale = languageController.read('savedLocale');
    return savedLocale;
  }
brennschluss
  • 21
  • 1
  • 1
  • 3
0

if you still needs this , I use my app differently but I just made it work he it my main file (minus what you don' need)

    void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await GetStorage.init();
  await firebaseInitialization.then((value) {
    Get.put(HomeController());
  });

  runApp(Start());
}

class Start extends StatelessWidget {
  Start({
    Key? key,
  }) : super(key: key);
  final storage = GetStorage();

  @override
  Widget build(BuildContext context) {
    Get.put(HomeController());
    print(storage.read('langCode'));
    print(storage.read('countryCode'));

    return GetMaterialApp(
        translations: LocaleString(),
        fallbackLocale: const Locale('en', 'US'),
        locale: storage.read('langCode') != null
            ? Locale(storage.read('langCode'), storage.read('countryCode'))
            : const Locale('ar', 'MA'),
        title: 'title'.tr,
        
        }));
  }
}

i have a button on my drawer that switches between arabic and english, you can put it wherever you want, you just need to have the widget

class Page extends GetView<HomeController>

which gives you the value 'controller' to represent the controller responsible for the language. and this is the button responsible for the switch:

SizedBox(
                      height: 70,
                      child: OutlinedButton(
                        child: ListTile(
                          title: Text(
                            'language'.tr,
                            style: Theme.of(context).textTheme.headline6,
                            textDirection: TextDirection.rtl,
                          ),
                          leading: const Icon(Icons.language),
                        ),
                        onPressed: () {
                          controller.switchLang();
                        },
                      )),

and here is my homeController which is responsible for the locale:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class HomeController extends GetxController {
  static HomeController instance = Get.find();
  final storage = GetStorage();
  var ar = const Locale('ar', 'MA');
  var us = const Locale('en', 'US');


  switchLang() {
    
     if (Get.locale == us) {
       Get.updateLocale(ar);
       storage.write('langCode', 'ar');
       storage.write('countryCode', 'MA');
     } else {
       Get.updateLocale(us);
       storage.write('langCode', 'en');
       storage.write('countryCode', 'US');
     }
    update();
   
  }

  
}

in your case if you have multiple locales , just change my switchlang function to handle multiple locales, you can do that easily with a switch case

phaylali
  • 33
  • 1
  • 7