Home > Blockchain >  how to pass index inside Radio listTile in Flutter?
how to pass index inside Radio listTile in Flutter?

Time:08-06

I am trying to pass the index inside the Radio button list tile in order to set Locale language and also save settings into shared preferences.

This is a the part of main code where i want to pass the index:

body: CupertinoPageScaffold(
    child: Container(
      child: SingleChildScrollView(
          child: Container(
            child: CupertinoFormSection.insetGrouped(
              header:  Text('choose_a_language'.tr()),
                children: [
                
                  RadioListTile( title: Text('English'), value: Language.English, groupValue: _selecLangIndex,  subtitle: Text('English'), selected: _selectedIndex == 0 , onChanged: (newValue) =>
                      setState(() => _selecIndex = newValue)),
                  RadioListTile(title: Text('French'), value: Language.French, groupValue: _selecLangIndex,  subtitle: Text('French'), selected: _selectedIndex == 1,  onChanged: (newValue) =>
                      setState(() => _selecIndex = newValue)),
                  RadioListTile(title: Text('Italian'), value: Language.Italian, groupValue: _selecLangIndex, subtitle: Text('Italian'), selected: _selectedIndex == 2, onChanged: (newValue) =>
                      setState(() => _selecIndex = newValue)),
                  TextButton(onPressed:
                    _saveSettings,
                    child: Text('save'.tr().toUpperCase(),
                    style: TextStyle(fontWeight: FontWeight.bold),),

Right now on Save button, with onPressed method, i am able to save settings, but i cannot set locale language. I also tried to implement this code, without any result.

void setLocale()  {
int index = 0;
setState(() =>  _selectedIndex == index  );
if (index == 0){
   context.setLocale(Locale('en','US'));

}
else if (index == 1){
   context.setLocale(Locale('fr','FR'));
}
else if (index == 2){
   context.setLocale(Locale('it','IT'));
}
print(index);

}

CodePudding user response:

You can do something like this

onChanged: (newValue) {
  setLocale(); //
  _selecIndex = newValue ;
 setState((){});
},

If your setLocale is not using/updating the _selectedIndex. You can pass index on setLocale(0) and it doesnt need to have setState because we already call setState end of onChanged

  • Related