Maintain radiobutton value when navigating to and from page flutter - flutter

I have the following radio button and would like to maintain it's value when a user re-navigates to this screen. Currently, when a user goes to another screen and comes back, it default to the pick up option.
I know that this can be achieved by SharedPreferences but I was wondering if there is another way.
enum DeliveryMethod { delivery, pickup }
DeliveryMethod _character = DeliveryMethod.pickup;
children: <Widget>[
Expanded(
child: ListTile(
title: const Text('Please deliver'),
leading: Radio(
value: DeliveryMethod.delivery,
groupValue: _character,
onChanged: (value) {
_character = value;
});
},
),
),
),
Expanded(
child: ListTile(
title: const Text('I will pick up'),
leading: Radio(
value: DeliveryMethod.pickup,
groupValue: _character,
onChanged:
(DeliveryMethod value) {
setState(() {
_character = value;
});
},
),
),
),
]

you can use
Navigator.pop(context,DeliveryMethod.pickup);
and in your screen
delivery = await Navigator.push(...);
you can use NotifierValue to rebuild widget without need to use setState

Related

How to make checkbox ListTile with rounded box using Getx in Flutter

I am relatively new to Flutter development and I want to implement checkbox as shown in the screenshot attached using GetX flutter. Also I want the borders of my check-boxes to be round.
screenshot
You can make a CheckBox round by using the shape field and the CircleBorder class or RoundedRectangleBorder (if you want them to have rounded corners):
Checkbox(
checkColor: Colors.white,
value: isChecked,
shape: CircleBorder(),
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
);
Result:
Or:
Checkbox(
checkColor: Colors.white,
value: isChecked,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0))),
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
);
Result:
To use GetX I think you should provide some code or example to explain what do you mean and what you want to exactly achieve, otherwise the best advice is probably to read the documentation and check some example.
As you've mentioned in the screenshot.
You can achieve it with GetX as following:
Create a variable for keep tracking the checked value
final Rxn<int> selected = Rxn<int>();
Now you have to implement the UI with Obx widget to listen for the changes of observing variable 'selected'
Obx(
() => Column(
children: [
CheckboxListTile(
title: const Text('This is the title 1'),
subtitle: const Text('This is the subtitle with ID 1'),
checkColor: Colors.white,
activeColor: Colors.blueGrey,
controlAffinity: ListTileControlAffinity.leading,
checkboxShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
value: selected.value == 1,
onChanged: (val) {
val ?? true ? selected.value = 1 : selected.value = null;
},
),
CheckboxListTile(
title: const Text('This is the title 2'),
subtitle: const Text('This is the subtitle with ID 2'),
checkColor: Colors.white,
activeColor: Colors.blueGrey,
controlAffinity: ListTileControlAffinity.leading,
checkboxShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
value: selected.value == 2,
onChanged: (val) {
val ?? true ? selected.value = 2 : selected.value = null;
},
),
],
),
))
The following will be the output:

Uncheck a checkbox when user checking another one (bool of checkbox is in a map)

I have in my app a few checkboxes and I want, when the user checks a checkbox, that the other checkboxes are unchecked. That's normally not difficult at all, but the problem is that I have the bool and the title of the checkbox in a map. How can I uncheck all checkboxes except the one the user checkt?
This is the map:
Map<String, bool> filterOptions = {
'Test1': false,
'Test2': false,
};
This is the code where I "build" the checkboxes:
ListView(
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: filterOptions.keys.map((String key) {
return CheckboxListTile(
title: Text(key),
value: filterOptions[key],
onChanged: (bool value) {
setState(() {
filterOptions[key] = value;
});
},
);
}).toList(),
),
What you are looking for is not a checkbox, but a Radio Button. You can only select one radio button at a time and you don't have to manually check the state. However, if you insist on the checkboxes you can iterate through the map
filterOptions.forEach((key, value) => filterOptions[key] = false);
If you set value to false, you will just change the copy of the value. You might consider dropping the map and go for a single int selectedBox variable.
The purpose of a checkbox is for multiple user group selection.
In other words, if you want to unselect when a user selects another option then
RadioButton
would be the best option.
SingingCharacter _character = SingingCharacter.lafayette;
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListTile(
title: const Text('Male'),
leading: Radio(
value: SingingCharacter.lafayette,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
),
ListTile(
title: const Text('Female'),
leading: Radio(
value: SingingCharacter.jefferson,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
),
],
);
}
Screenshot
Source: Flutter RadioButton

How can i use controllers in radio group in flutter?

I am trying to get user input data with different types such as text data and radio button grouped data.
In text type inputs, i use TextEditingControllers, for example ;
final quantNumberController = TextEditingController();
String quant = quantNumberController.text;
var data = {'quant': quant, 'capp': capp}
...
Container(
width: 280,
padding: EdgeInsets.all(10.0),
child: TextField(
controller: quantNumberController,
autocorrect: true,
decoration: InputDecoration(hintText: 'Enter location'),
)
),
And i want to receive radio button data like below, but is there any way to use controllers within ListTiles or how can i get user choice to my json data ;
Container(
margin: EdgeInsets.fromLTRB(0, 0, 0, 10),
child: Column(
children: <Widget>[
Text('Location'),
ListTile(
title: const Text('First value'),
leading: Radio(
value: Cap.Cap33,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap33';
});
},
),
),
ListTile(
title: const Text('Second value'),
leading: Radio(
value: Capp.Cap22,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap22';
});
},
),
),
ListTile(
title: const Text('Third value'),
leading: Radio(
value: Capp.Cap44,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap44';
});
},
),
),
],
) ,
),
In your example, the user choice is saved in _capp.
Let's make a new one:
int every_many_days;
RadioListTile<int>(
title: Text('Every Day'),
value: 1,
groupValue: every_many_days,
onChanged: (int value){
setState(() {every_many_days = value;});
},
),
RadioListTile<int>(
title: Text('Every Week'),
value: 7,
groupValue: every_many_days,
onChanged: (int value){
setState(() {every_many_days = value;});
},
),
Now the choice is available in the variable every_many_days, it will be 1 or 7, and you don't need a controller.

List view radio buton not selecting when selected

When i run the program on a device when i tick 2nd or 3rd term it does not take effect.
I am developing an Electronic student attendance tracking system so i decided to use a radio to track the term and also use check box to track the attendance that is checked if the student is present and unchecked if the student is not present but when i check the term radio it gives the correct output on the console but does not take effect on the physical screen.
import 'package:flutter/material.dart';
import 'package:atttendance_register/dataFiles/pupils.dart';
import 'package:atttendance_register/dataFiles/attendance.dart';
import 'package:intl/intl.dart';
class attendance extends StatefulWidget {
static Future<void> show(BuildContext context) async {
await Navigator.of(context).push(
MaterialPageRoute(builder: (context)=>attendance(),fullscreenDialog: true),
);
}
#override
_attendanceState createState() => _attendanceState();
}
class _attendanceState extends State<attendance> {
// final List<Pupils> pupils =[
// Pupils('John', ' Doe', 'Brad', 'Male', '001', DateTime.now(), '21'),
// Pupils('Jane', ' Doe', 'Mary', 'Female', '002', DateTime.now(), '21'),
// Pupils('Mohamed', ' James', '', 'Male', '003', DateTime.now(), '33'),
// Pupils('Titus', ' Nabieu', 'Jusu', 'Male', '004', DateTime.now(), '21'),
// Pupils('Steven', ' kai', 'Rogers', 'Male', '005', DateTime.now(), '21'),
// Pupils('Josephine', ' Bah', 'Neneh', 'Female', '006', DateTime.now(), '23')
//
// ];
final List<Attendance> attendance =[
Attendance(false,'John Doe Brad',DateTime.now(),0),
Attendance(true,'Jane Doe Mary',DateTime.now(),2),
Attendance(false,'Mohamed James',DateTime.now(),1),
Attendance(false,'Titus Nabieu Jusu',DateTime.now(),2),
Attendance(false,'Steven kai Rogers',DateTime.now(),2),
Attendance(false,'Josephine Bah Neneh',DateTime.now(),1)
];
bool selectedCheck = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Enter Attendance'),
backgroundColor: Colors.blue[900],
),
backgroundColor: Colors.blue[100],
body:Container(
child: ListView.builder(
itemCount:attendance.length,
itemBuilder:(BuildContext context, int index){
int selectedRadio = attendance[index].Term;
bool selectedCheck = attendance[index].attendance;
return Container(
child: Card(
child: Column(
//final pupil =pupils[index];
children: <Widget>[
Text(attendance[index].pupilName),
Text('Select Term'),
Row(
children: <Widget>[
Radio(
value:0,
groupValue: selectedRadio,
activeColor: Colors.blue,
onChanged: (T){
print(T);
setState(() {selectedRadio = T;}
);},
),
new Text(
'1st Term'
),
new Radio(
value: 1,
groupValue: selectedRadio,
activeColor: Colors.blue,
onChanged: (T){
print(T);
setState(() {selectedRadio = T;}
);
},
),
new Text(
'2nd Term'
),
new Radio(
value: 2,
groupValue: selectedRadio,
activeColor: Colors.blue,
onChanged: (T){
print(T);
setState(() {selectedRadio = T;}
);
},
),
new Text(
'3rd Term',
),
],
),
Row(
children: <Widget>[
Checkbox(
value: selectedCheck,
activeColor: Colors.blue,
onChanged: (bool value){
print(value);
setState(() {selectedCheck = value;}
);},
),
new Text(
'Present'
),
],
),
],
),
),
);
} ,),
),
);
}
// Widget pupilsCard(BuildContext context, int index){
// final pupil =pupils[index];
// bool selectedRadio = false;
//
// return Container(
// child: Card(
// child: Column(
// children: <Widget>[
// Text(pupil.FirstName+' '+pupil.OtherName+' '+pupil.LastName),
// Text('Select Term'),
// Row(
// children: <Widget>[
//
//
// ],
// ),
// Checkbox(
// value: selectedRadio,
// activeColor: Colors.blue,
// onChanged: (bool value){
// print(value);
// setState(() {selectedRadio = value;}
// );},
// ),
// new Text(
// 'Present'
//
// ),
// ],
// ),
// ),
// );
// }
}
In the onChanged property of your Radio widgets and your Checkbox widget, you are assigning the user selected value to the variable selectedRadio / selectedCheck and here is the problem, because when the new State is created through setState, the ListView is rebuilding and you are reassigning selectedRadio / selectedCheck the old value of the objects in this lines:
int selectedRadio = attendance[index].Term;
bool selectedCheck = attendance[index].attendance;
So you were not changing the actual value of the objects in the List, but you have too:
onChanged: (T) {
print(T);
setState(() => attendance[index].Term = T);
},
and
onChanged: (value) {
print(value);
setState(() => attendance[index].attendance = value);
},

Flutter: How to get data in Firestore and show those data in a dropdownbutton?

I'm having a problem getting my data from Firestore and putting that data in a dropdown button. I want to get all of the entries with "Name of Organization" in my Firestore database and put them in a dropdown button.
My code:
child: DropdownButton<String>(
elevation: 5,
hint: Center(
child: Text(
"Choose type of Organization",
style: TextStyle(
color: Colors.black,
),
),
),
items: typesOfOrg.map((String dropDownString){
return DropdownMenuItem<String>(
value: dropDownString,
child: Text(dropDownString),
);
}).toList(),
onChanged: (value) {
setState(() {
_value = value;
print(value);
});
},
value: _value,
),
As of now, I have this dropdown button that creates "typesofOrg" as a static array.
var typesOfOrg = ["Breast Cancer", "DSWD"];
And in my database I have this structure: