简体   繁体   English

如何在 Flutter 的 Radio listTile 中传递索引?

[英]how to pass index inside Radio listTile in Flutter?

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.现在在Save button上,使用 onPressed 方法,我可以保存设置,但我无法设置语言环境。 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);

}

You can do something like this你可以做这样的事情

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

If your setLocale is not using/updating the _selectedIndex .如果您的setLocale没有使用/更新_selectedIndex You can pass index on setLocale(0) and it doesnt need to have setState because we already call setState end of onChanged您可以在setLocale(0)上传递索引,它不需要 setState 因为我们已经调用了onChanged的 setState end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM