Home > Enterprise >  Flutter SharedPreference Not updating values RealTime When Changed Unless App Closes and Restarts
Flutter SharedPreference Not updating values RealTime When Changed Unless App Closes and Restarts

Time:10-24

Please check the gif below.

enter image description here

I changed the language from English to French. It doesn't update realtime.

But when I close the app and open it, it shows French (Meaning it was saved in the preference)

I want it to change realtime as I update it.

SharedPrefence.dart

static String selectedLanguageKey = "language";
static SharedPreferences? _prefs;

static Future<SharedPreferences?> init() async {
_prefs = await SharedPreferences.getInstance();
return _prefs;
}

static String? getSelectedLanguage() {
return _prefs?.getString(selectedLanguageKey);
}

Home.dart

class _HomeState extends State<Home> {

String? _selectedLanguage;

void getSelectedLanguage() {
setState(()  {
_selectedLanguage = 
LocalPreference.getSelectedLanguage();
});
}

@override
void initState() {
super.initState();
getSelectedLanguage();
}

@override
Widget build(BuildContext context) {
.........

//there is a widget here that when tapped shows a modalbottomsheet where 
user selects a language

onTap: () {    
   showModalBottomSheet() 
}


//now here I display the current selected language, but it doesn't update 
 real time. Only when I close and open app
 Text(
  _selectedLanguage?? Strings.hindi, 
  }
 }

CodePudding user response:

Thats because getSelectedLanguage() wont be called unless an Instance of Home is created which is the case when restarting the app. What you can do is using a state management pattern for this, ex: provider and calling notifyListeners() when changing setting the language and you can access the language variable by calling the provider value, i.e. Provider.of<LanguageProvider>(context, listen: false).language or putting the language on the desired pages in a consumer.

You have other state managements patterns which may be also easier like GetX, Bloc...

CodePudding user response:

You need update your _selectedLanguage every time came back from ModalBottomSheet. So change your onTap function to this:

onTap: () {    
   Future future = showModalBottomSheet() 
   
   future.then((_) {
      getSelectedLanguage();
    });
}
  • Related