how to pass index inside Radio listTile in Flutter? - 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.
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. You can pass index on setLocale(0) and it doesnt need to have setState because we already call setState end of onChanged

Related

Flutter: Not able to select items in Radio button, in ListTile

Im a newbie, Not able to select items in Radio button, inside a ListTile. I tied to use same code without ListTile and working as expected. Looks like combination is not correct or i might be missing something.
class _TempState extends State<Temp> {
int selectedValue = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
child: Column(children: [
Row(
children: [
Expanded(
child: Text("Radio button with ListView",))],),
Expanded(
child: ListView.builder(
itemCount: 1,
itemBuilder: (BuildContext context, int index) {
return OrderItem();
}),),
]))));}
Widget OrderItem() {
int selectedValue = 0;
return ListTile(
title: Container(
child: Column(children: [
Row(
children: [
Expanded(
child: Text(
"Product Type :",
)),
Radio<int>(
value: 1,
groupValue: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value != null ? value.toInt() : 1;
});
},
),
Text('NRML'),
Radio<int>(
value: 2,
groupValue: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value != null ? value.toInt() : 1;
});
}),
Text('MARKET'),
],), ])));
}}
You are updating your selectedValue in wrong way ,first define your selectedValue like this:
int? selectedValue;
then update your widget like this:
Widget OrderItem() {//remove int selectedValue = 0; here
return ListTile(
title: Container(
child: Column(
children: [
Row(
children: [
Expanded(
child: Text(
"Product Type :",
)),
Radio<int>(
value: 1,
groupValue: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value; //<-- change this
});
},
),
Text('NRML'),
Radio<int>(
value: 2,
groupValue: selectedValue,
onChanged: (value) {
setState(() {
selectedValue = value; //<-- change this
});
}),
Text('MARKET'),
],
),
],
),
),
);
}
Also another reason that is not working is that you are define another int selectedValue = 0; in your OrderItem method, you need to remove it.
In your second radio you should change your setState to
selectedValue = value != null ? value.toInt() : 2;
Value you assign to radio will be used to determine which radio is selected. So if you want to select second radio you should assign its value when selecting
selectedValue = value != null ? value.toInt() : 2;
Value you assign to radio will be used to determine which radio is selected. So if you want to select second radio you should assign its value when selecting

Change elevated button color via radio buttons in flutter

I want to change the Elevated button color when I press the radio buttons. 1.button -> red, 2.button -> yellow, 3.button -> green. In the Elevated.stylefrom if condition did not work. Just ternary condition works but it is only for one condition. I want to add 3 conditions. I hope it was clear.
Or do I need to create a model for this?
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:task_shopping_app/const/const.dart';
import 'package:task_shopping_app/screens/city_input_screen.dart';
import 'package:task_shopping_app/screens/weather.dart';
class RadioButton extends StatefulWidget {
#override
_RadioButtonState createState() => _RadioButtonState();
}
class _RadioButtonState extends State<RadioButton> {
int selectedValue = 0;
final enteredCityInfo = TextEditingController();
String name = '';
// if selectedValue and group value matches then radio button will be selected.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
Radio<int>(
value: 1,
groupValue: selectedValue,
onChanged: (value) => setState(() {
selectedValue = value!;
print(selectedValue);
})),
Radio<int>(
value: 2,
groupValue: selectedValue,
onChanged: (value) => setState(() {
selectedValue = value!;
print(selectedValue);
})),
Radio<int>(
value: 3,
groupValue: selectedValue,
onChanged: (value) => setState(() {
selectedValue = value!;
print(selectedValue);
})),
],
),
Padding(
padding: const EdgeInsets.all(25.0),
child: TextField(
controller: enteredCityInfo,
),
),
ElevatedButton(
onPressed: () {
setState(() {
name = enteredCityInfo.text;
//Here we want to see user entry for the text field area in the debug console.
print(name);
// Get.to(() => WeatherScreen());
});
},
child: Text('Create'),
style: ElevatedButton.styleFrom(
primary: selectedValue == 1 ? Colors.red : Colors.yellow,
),
)
],
),
);
}
}
enter code here
I think you can create a function to convert the value into Colors
Color valueToColor(int value) {
switch (value) {
case 1:
return Colors.red;
case 2:
return Colors.yellow;
case 3:
return Colors.green;
default:
/// return whatever you like to deal with some exceptional case
}
}
And make the style parameter of ElevatedButton like following
style: ElevatedButton.styleFrom(
primary: valueToColor(selectedValue),
),
Use like this for multiple conditions:
primary:(selectedValue == 1) ? Colors.red : (selectedValue == 2)?
Colors.yellow:Colors.green,

How to show active mark on RadioListTile?

How to show active mark on RadioListTile? I used selected and activeColor but it does not work.
RadioListTile(
selected: true,
activeColor: Theme.of(context).primaryColor, //
title: Text(AppLocalizations.key(context, 'setDark')),
value: ThemeMode.dark,
groupValue: _themeMode,
onChanged: (value) {},
),
Documentation
"groupValue → T?
The currently selected value for this group of radio buttons.
This radio button is considered selected if its value matches the groupValue.
"
The one selected is the one whose group value matches the value.
Therefore your radio buttons should have as groupValue Theme.Dark or Theme.Light and update it on onChanged.
You need to create two RadioListTile for this and will contain the same groupValue. Based on groupValue it will decide active RadioListTile.
When value match with groupValue it will show active mark status.
class _HomesState extends State<Homes> {
ThemeMode _themeMode = ThemeMode.dark;
#override
Widget build(BuildContext context) {
return Scaffold(body: LayoutBuilder(
builder: (context, constraints) {
return Center(
child: Column(
children: [
RadioListTile<ThemeMode>(
selected: true,
activeColor: Theme.of(context).primaryColor,
title: Text(
'setDark',
),
value: ThemeMode.dark,
groupValue: _themeMode,
onChanged: (value) {
setState(() {
_themeMode = value!;
});
},
),
RadioListTile<ThemeMode>(
selected: true,
activeColor: Theme.of(context).primaryColor,
title: Text(
'setLight',
),
value: ThemeMode.light,
groupValue: _themeMode,
onChanged: (value) {
setState(() {
_themeMode = value!;
});
},
),
],
),
);
},
));
}
}

Flutter - I have two issue with RadioListTile

I have a problem with RadioListTile it doesn't work when I make the change that does not change unless I leave it and return to it I find it changed.
The second problem is I want to save the option when the application is run for the first time, it is the first choice.
if someone has answered, please?
this is my code:
int radioValue = 0;
int tafIbnkatheer = 1;
int tafBaghawy = 2;
int tafQurtubi = 3;
int tafSaadi = 4;
int tafTabari = 5;
var showTaf;
void handleRadioValueChanged(int val) {
TranslateRepository2 translateRepository2 = new TranslateRepository2();
TranslateRepository translateRepository = new TranslateRepository();
TranslateRepository3 translateRepository3 = new TranslateRepository3();
TranslateRepository4 translateRepository4 = new TranslateRepository4();
TranslateRepository5 translateRepository5 = new TranslateRepository5();
setState(() {
radioValue = val;
switch (PrefService.getInt('$radioValue')) {
case 1:
setState(() {
showTaf = translateRepository2;
});
break;
case 2:
setState(() {
showTaf = translateRepository;
});
break;
case 3:
setState(() {
showTaf = translateRepository3;
});
break;
case 4:
setState(() {
showTaf = translateRepository4;
});
break;
case 5:
setState(() {
showTaf = translateRepository5;
});
break;
}
print(showTaf);
});
}
#override
void initState() {
setState(() {
radioValue = 1;
});
super.initState();
}
...
RadioListTile(
value: tafIbnkatheer,
groupValue: radioValue,
title: Text("Radio 1"),
subtitle: Text("Radio 1 Subtitle"),
onChanged: (val) {
setState(() {
handleRadioValueChanged(val);
});
},
activeColor: Colors.red,
selected: true,
),
RadioListTile(
value: tafBaghawy,
groupValue: radioValue,
title: Text("Radio 2"),
subtitle: Text("Radio 2 Subtitle"),
onChanged: (val) {
setState(() {
handleRadioValueChanged(val);
});
},
activeColor: Colors.red,
selected: false,
),
RadioListTile(
value: tafQurtubi,
groupValue: radioValue,
title: Text("Radio 3"),
subtitle: Text("Radio 3 Subtitle"),
onChanged: (val) {
setState(() {
handleRadioValueChanged(val);
});
},
activeColor: Colors.red,
selected: false,
),
RadioListTile(
value: tafSaadi,
groupValue: radioValue,
title: Text("Radio 4"),
subtitle: Text("Radio 4 Subtitle"),
onChanged: (val) {
setState(() {
handleRadioValueChanged(val);
});
},
activeColor: Colors.red,
selected: false,
),
RadioListTile(
value: tafTabari,
groupValue: radioValue,
title: Text("Radio 5"),
subtitle: Text("Radio 5 Subtitle"),
onChanged: (val) {
setState(() {
handleRadioValueChanged(val);
});
},
activeColor: Colors.red,
selected: false,
),
...
To make a Radio List Tile selected, as the documentation says, you can use checked. In fact
checked → bool
Whether this radio button is checked
selected → bool
Whether to render icons and text in the activeColor.

Cannot Select Checkbox List Tile Flutter

I've created a map of values to make checkboxes. The map consists of String and bools and when the value of the bool is changed, the check box value should change.
EDIT 1:
My ListView Checkbox
CheckboxListTile(
title: new Text(
key,
style: textHeaderStyle,
),
value: _selectedOrders.contains(undeliveryOrders[key]),
activeColor: Colors.pink,
checkColor: Colors.white,
onChanged: (bool value) {
setState(() {
if(value){
_selectedOrders.add(undeliveryOrders[key]);
undeliveryOrders[key] = value;
}else{
setState(() {
_selectedOrders.remove(undeliveryOrders[key]);
});
}
});
},
)
Creating the Map:
void _formatOrders(availableOrders) {
for (int i = 0; i < availableOrders.length; i++) {
var tempOrder = '${availableOrders[i].customer.uniqueInfo.name} , ${availableOrders[i].address}';
undeliveryOrders['$tempOrder'] = false;
}
print('$undeliveryOrders');
print('$numbers');
}
Selected Order Method
var _selectedOrders = [];
getItems() {
undeliveryOrders.forEach((key, value) {
if (value == false) {
_selectedOrders.add(key);
}
});
print(_selectedOrders);
_selectedOrders.clear();
}
I think you might be over complicating things every value does not have to be mapped to a boolean the way I do it is I add the value that gets checked to an array then check if that item is in that array if it is its true if not its false. You just have to remember to remove the item if the checkbox is unchecked here is some sample code for you.
List<String> items = ['Item 1', 'Item 2', 'Item 3'];
List<String> isChecked = [];
//Initialized outside build
ListView(
children: <Widget>[
...items
.map(
(item) => CheckboxListTile(
subtitle: Text('This is a subtitle'),
secondary: Text('This is Secondary text'),
title: Text(item),
value: isChecked.contains(item),
onChanged: (bool value) {
if (value) {
setState(() {
isChecked.add(item);
});
} else {
setState(() {
isChecked.remove(item);
});
}
},
),
)
.toList()
],
),
In my case, the setState() is not responding, try to use StatefulBuilder().
For Example:
...
bool isSelected = false;
StatefulBuilder(
builder: (context, _setState) {
return ListView(
children: [
CheckboxListTile(
value: isSelected,
onChanged: (bool? value) {
_setState(() => isSelected = value);
},
),
],
);
},
);
...
You can try with this code bellow ?
onChanged: (bool value) {
setState(() {
undeliveryOrders[key] = value ?? false;
});
},