Change the value of the radio button when selected - flutter

Ive got a list of strings
List<String> answerOptions=['Apple','Orange','Grapes','Kiwi'];
and I've created a custom radio button file named QuizRadioButton
class QuizRadioButton extends StatefulWidget {
final String label;
final void Function(dynamic) onChanged;
const QuizRadioButton(
{required this.label, required this.onChanged, Key? key})
: super(key: key);
#override
_QuizRadioButtonState createState() => _QuizRadioButtonState();
}
class _QuizRadioButtonState extends State<QuizRadioButton> {
int? _value = 0;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
children: [
Radio<int>(
value: 1,
groupValue: _value,
onChanged: (value) => setState(() => _value = value),
),
Text(widget.label, style: Theme.of(context).textTheme.headline3),
],
),
);
}
}
I've used this radio button class and I've populated 4 radio buttons using the list mentioned above
Widget content(BuildContext context){
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
Text('which fruit of these are red in color ?'),
SizedBox(height: 30.0,),
for(int i=0;i<answerOptions.length;i++)Container(
child:QuizRadioButton(label: answerOptions[i], onChanged: (value){}) ,
)
],
),
);
}
and I get the output as
Right now we can select all 4 radio buttons at once, what I want is if I want to pick apple, the radio button with apple as the label should be true and others as false. Please help

int groupVal=0;
Implementation:
Widget content(BuildContext context){
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
Text('which fruit of these are red in color ?'),
SizedBox(height: 30.0,),
for(int i=0;i<answerOptions.length;i++)
Container(
child:QuizRadioButton(label: answerOptions[i], onChanged: (value){
setState(() {
groupVal=value;
});
}, index: i, groupVal: groupVal) ,
)
],
),
),
}
Your QuizRadioButton:
class QuizRadioButton extends StatefulWidget {
final String label;
final void Function(dynamic) onChanged;
int index,groupVal;
QuizRadioButton(
{required this.label, required this.groupVal, required this.onChanged, required this.index, Key? key})
: super(key: key);
#override
_QuizRadioButtonState createState() => _QuizRadioButtonState();
}
class _QuizRadioButtonState extends State<QuizRadioButton> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
children: [
Radio<int>(
value: widget.index,
groupValue: widget.groupVal,
onChanged: widget.onChanged,
),
Text(widget.label, style: Theme.of(context).textTheme.headline3),
],
),
);
}
}

Related

All checkboxes in Flutter checkbox Listtile are checked at the same time

I created a checkbox Listtile, where I can click on an Info button to receive further info if neccessary. Therefore I created a main Widget which contains the Listtile widget. When the Info button gets clicked, the detail page opens and reads the specific details from the model class.Up to that point everything works fine.
My leading is a checkbox. If it gets clicked not just one checkbox gets checked, but all of them. how can I write my code, that they arent checked all at the same time automatically?
thank you very much for your help
Kind regards
Here is my code:
//This is my model
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class Info {
String title;
String description;
//String image;
Info(
{required this.title,
required this.description,
// #required this.image
});
}
List<Info> ModelList = [
Info(
title: 'title1',
description: 'description1'
),
Info(
title: 'title2',
description: 'description2'
),
];
//This is the widget
class MainWidget extends StatefulWidget {
const MainWidget({Key? key}) : super(key: key);
#override
State<MainWidget> createState() => _MainWidgetState();
}
class _MainWidgetState extends State<MainWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder
(itemCount: ModelList.length,
itemBuilder: (context,index)
{Info cardname = ModelList[index];
return Card(
child: CheckboxListTile(
tileColor: const Color(0xFF5D6D7E),
shape: RoundedRectangleBorder(
side: const BorderSide (color:Colors.white,width: 2),
borderRadius: BorderRadius.circular(10),
),
contentPadding: const EdgeInsets.symmetric(vertical: 10.0),
value: timeDilation !=1.0,
onChanged: (bool? value) {
setState (() {
timeDilation = value! ? 5.0 : 1.0;
});
},
title: Text(
cardname.title,
style: const TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
//an welcher Stelle die Checkbox ist (links oder rechts)
controlAffinity:
ListTileControlAffinity.leading,
secondary: IconButton(icon: const Icon(Icons.info_outlined,size: 40,color: Colors.orange,), onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> DetailScreen(cardname)
));
},),
)
);
}
,),
)
;
}
}
//Detail screen
//Detail Screen;
class DetailScreen extends StatelessWidget {
final Info cardname ;
const DetailScreen (this.cardname, {super.key});
//const DetailScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: customAppBar
((cardname.title),),
body: Padding(
padding: const EdgeInsets.all(8.0) ,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Image.network(
// cardname.imageUrl,
//height: 500,
//),
//
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
cardname.description,
textAlign: TextAlign.justify,
style: const TextStyle(fontSize: 22.0),
),
),
],
),
),
) ,
);
}
}
I tried to put the Item builder in an extra widget and return it into the main widget as shown below, but this didn`t work as well
class SubWidget extends StatefulWidget {
const SubWidget({Key? key}) : super(key: key);
#override
State<SubWidget> createState() => _SubWidgetState();
}
class _SubWidgetState extends State<SubWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder
(itemCount: ModelList.length,
itemBuilder: (context,index)
{Info cardname = ModelList[index];
return MainWidget()
Add variable is isSelected bool for Info class
And after onChanged change value: isSelected = !isSelected
Try this:
class Info {
String title;
String description;
bool isSelected;
//String image;
Info({
required this.title,
required this.description,
required this.isSelected,
// #required this.image
});
}
List<Info> ModelList = [
Info(title: 'title1', description: 'description1', isSelected: false),
Info(title: 'title2', description: 'description2', isSelected: false),
];
//This is the widget
class MainWidget extends StatefulWidget {
const MainWidget({Key? key}) : super(key: key);
#override
State<MainWidget> createState() => _MainWidgetState();
}
class _MainWidgetState extends State<MainWidget> {
double timeDilation = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: ModelList.length,
itemBuilder: (context, index) {
Info cardname = ModelList[index];
return Card(
child: CheckboxListTile(
tileColor: const Color(0xFF5D6D7E),
shape: RoundedRectangleBorder(
side: const BorderSide(color: Colors.white, width: 2),
borderRadius: BorderRadius.circular(10),
),
contentPadding: const EdgeInsets.symmetric(vertical: 10.0),
value: cardname.isSelected,
onChanged: (bool? value) {
setState(() {
cardname.isSelected = !cardname.isSelected;
});
},
title: Text(
cardname.title,
style: const TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
//an welcher Stelle die Checkbox ist (links oder rechts)
controlAffinity: ListTileControlAffinity.leading,
secondary: IconButton(
icon: const Icon(
Icons.info_outlined,
size: 40,
color: Colors.orange,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(cardname),
),
);
},
),
),
);
},
),
);
}
}

Show tickmark depending on drop down value in Dart

Need to tickmark this widget depending on drop down value pending
confirmed, dispatched, recieved.
if passed pending it display pending with tick and if its confirmed on
dropdown it shows confimed with two ticks and dispatched with three ticks
and so on. Tried creating drop down which selects the all four values dont understand how
to implement tickmarks based on the text value and show that widget that I made.
Please help. Thanks.
class OrderListScreen extends StatefulWidget {
const OrderListScreen({Key? key}) : super(key: key);
#override
State<OrderListScreen> createState() => _OrderListScreenState();
}
class _OrderListScreenState extends State<OrderListScreen> {
#override
Widget build(BuildContext context) {
return Material(
child: Container(
child: Column(
children: <Widget>[
Text(
" Please select the order status from the dropdown Below:",
style: TextStyle(backgroundColor: Colors.orange)),
Container(
child: Material(
child: DropdownButton<String>(
items: <String>[
'Pending',
'Confirmed',
'Dispatched',
'Recieved'
].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) {},
),
)),
],
),
),
);
}
}
OrderStatus Widget (that has all dropdown values):
OrderStatusBar(title: widget.order.orderStatus, status: true),
class OrderStatusBar extends StatefulWidget {
const OrderStatusBar({Key? key, required this.title, required this.status})
: super(key: key);
final String title;
final bool status;
#override
State<OrderStatusBar> createState() => _OrderStatusBarState();
}
class _OrderStatusBarState extends State<OrderStatusBar> {
#override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Row(
children: [
widget.status ? dottedCircleWithCheckMark() : dottedCircle(),
const SizedBox(width: 30),
Text(
widget.title.tr,
style: TextStyle(
fontSize: 20,
fontWeight: widget.status ? FontWeight.bold : null,
),
),
],
),
);
}
}
const size = 25.0;
const strokeWidth = 1.0;
const checkedColor = Color.fromRGBO(232, 113, 65, 1);
Widget dottedLine() {
return Directionality(
textDirection: TextDirection.rtl,
child: Align(
alignment: Alignment.topRight,
child: Container(
margin: const EdgeInsets.fromLTRB(0, 0, size / 2, 0),
child: const Padding(
padding: EdgeInsets.only(left: 27 / 2),
child: SizedBox(
height: size,
child: DottedLine(
dashColor: Colors.black,
direction: Axis.vertical,
lineLength: size,
lineThickness: strokeWidth,
dashLength: 5,
dashGapLength: 5,
),
),
),
),
),
);
}
dottedCircle() {
return DottedBorder(
borderType: BorderType.Circle,
dashPattern: const [5, 5],
child: Container(
height: size,
width: size,
decoration: const BoxDecoration(shape: BoxShape.circle),
));
}
dottedCircleWithCheckMark() {
return Container(
height: size + strokeWidth * 2,
width: size + strokeWidth * 2,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: checkedColor,
),
child: const Icon(
Icons.check,
color: Colors.white,
size: size / 4 * 3,
),
);
}
Create a callback on OrderListScreen to get selected item.
class OrderListScreen extends StatefulWidget {
final Function(String? selectedValue) callback;
const OrderListScreen({Key? key, required this.callback}) : super(key: key);
#override
State<OrderListScreen> createState() => _OrderListScreenState();
}
And get value from from onCHanged
onChanged: (v) {
widget.callback(v);
setState(() {
selectedValue = v;
});
},
Now on parent widget.
class _AppXState extends State<AppX> {
final items = <String>['Pending', 'Confirmed', 'Dispatched', 'Recieved'];
int selectedItemIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
OrderListScreen(
callback: (selectedValue) {
if (selectedValue != null && items.contains(selectedValue)) {
selectedItemIndex = items.indexOf(selectedValue);
setState(() {});
}
},
),
for (int i = 0; i < items.length; i++)
OrderStatusBar(title: items[i], status: i <= selectedItemIndex),
],
),
);
}
}
Test snippet
class AppX extends StatefulWidget {
AppX({Key? key}) : super(key: key);
#override
State<AppX> createState() => _AppXState();
}
class _AppXState extends State<AppX> {
final items = <String>['Pending', 'Confirmed', 'Dispatched', 'Recieved'];
int selectedItemIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
OrderListScreen(
callback: (selectedValue) {
if (selectedValue != null && items.contains(selectedValue)) {
selectedItemIndex = items.indexOf(selectedValue);
setState(() {});
}
},
),
for (int i = 0; i < items.length; i++)
OrderStatusBar(title: items[i], status: i <= selectedItemIndex),
],
),
);
}
}
class OrderListScreen extends StatefulWidget {
final Function(String? selectedValue) callback;
const OrderListScreen({Key? key, required this.callback}) : super(key: key);
#override
State<OrderListScreen> createState() => _OrderListScreenState();
}
class _OrderListScreenState extends State<OrderListScreen> {
String? selectedValue;
#override
Widget build(BuildContext context) {
return Material(
child: Container(
child: Column(
children: <Widget>[
Text(" Please select the order status from the dropdown Below:",
style: TextStyle(backgroundColor: Colors.orange)),
Container(
child: Material(
child: DropdownButton<String>(
value: selectedValue,
items: <String>[
'Pending',
'Confirmed',
'Dispatched',
'Recieved'
].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Row(
children: [
Text(value),
],
),
);
}).toList(),
onChanged: (v) {
widget.callback(v);
setState(() {
selectedValue = v;
});
},
),
)),
],
),
),
);
}
}

Get two different selected values from dropdowbutton from other class _ Flutter or GetX

To organize the code in a Form, I put the "Dropdownbutton" code in a separate class, and I call this class for each dropdown list. Indeed in this case, I have two drop down lists. At the level of the onChange() function, I assign the selected value to the selectedVal variable. So my question is how to access this value and pass it through the form after clicking on the submit button. Can anyone tell me how to solve this problem using Flutter or Getx?!
Thank you in advance.
Class of Form:
class InscriptionView extends StatefulWidget {
const InscriptionView({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() {
return InscriptionViewState();
}
}
class InscriptionViewState extends State<InscriptionView> {
GlobalKey<FormState> formstate2 = GlobalKey();
String? selectedValGender;
String? selectedDiploma;
inscription() async {
print(selectedValGender);
print(selectedDiploma);
//Code
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: const EdgeInsets.all(20),
child: Form(
key: formstate2,
child: Column(children: [
const CustomDropDownButton(
hint: "Gender",
listeItems: ["male", "female"],
icon: Icon(Icons.person),
),
const SizedBox(height: 20),
const CustomDropDownButton(
hint: "Diploma",
listeItems: ["Bachelor", "Master"],
icon: Icon(Icons.school_outlined),
),
const SizedBox(height: 20),
Center(
child: InkWell(
child: const Text("Page de connexion"),
onTap: () async {
await inscription();
},
))
]),
)));
}
}
Class of customise DropDownButton:
class CustomDropDownButton extends StatefulWidget {
final List<String>? listeItems;
final String? hint;
final Widget? icon;
String? selectedGender;
String? selectedDiploma;
const CustomDropDownButton(
{Key? key,
this.listeItems,
this.hint = '',
this.icon})
: super(key: key);
#override
State<CustomDropDownButton> createState() => _CustomDropDownButtonState();
}
class _CustomDropDownButtonState extends State<CustomDropDownButton> {
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(50)),
child: DropdownButton<String>(
dropdownColor: const Color.fromARGB(255, 192, 196, 220),
borderRadius: BorderRadius.circular(20),
isExpanded: true,
hint: Text(widget.hint!),
icon: widget.icon,
value: CustomDropDownButton.selectedGender,
items: widget.listeItems!
.map((e) => DropdownMenuItem(
value: e,
child: Text(e),
))
.toList(),
onChanged: (val) {
setState(() {
selectedGender = val!;
});
}),
);
}
}

How do I extract this switch widget

I have a StatefulWidget with a ListView, the ListView has the bunch of switches with text next to them.
Now i want to extract this into a custom switch widget because i have this more than once.
I don't know how to do this, also I need to know inside my parent widget what state each switch has.
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("Use custom dhcp server"),
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Switch(
value: _dhcp,
activeColor: Colors.blue,
onChanged: (bool value) {
setState(() {
_dhcp = value;
});
},
),
),
],
),
),
You can create your own stateless widget like this:
class CustomSwitch extends StatelessWidget {
const CustomSwitch({
Key key,
#required this.value,
#required this.onChanged,
}) : super(key: key);
final bool value;
final void Function(bool) onChanged;
#override
Widget build(BuildContext context) {
return Switch(
value: value,
activeColor: Colors.blue,
onChanged: onChanged,
);
}
}
Where you can use it anywhere like this:
class ParentWidget extends StatefulWidget {
#override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool switchValue = false;
#override
Widget build(BuildContext context) {
return ListView(
children: [
CustomSwitch(
value: switchValue,
onChanged: (newValue) {
setState(() {
switchValue = newValue;
});
},
),
],
);
}
}

Flutter How to Get Rid of Default fillColor for the First Item of DropdownButton

Question: title
So I have this DropdownButton
And here is the DropdownMenuItem
As you can see, the first item has a grey color on the background. So how to remove it?
To be more clear, here is what I want to achieve
Navbar Snippet:
class Navbar extends StatefulWidget {
#override
_NavbarState createState() => _NavbarState();
}
class _NavbarState extends State<Navbar> {
action() {
print('test');
}
#override
Widget build(BuildContext context) {
return Container(
height: 100,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
NavbarLogo(),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
NavbarItem(
title: 'welcome',
navigationPath: RouterDashboardView.welcomeView,
),
SizedBox(width: 50.0),
NavbarItemDropdown(
items: ['labelExitLabel', 'labelExitLabel', 'actionExitAction'],
functions: [action],
),
],
),
],
),
);
}
}
Nothing fancy, just contains a logo, a text and the dropdown
NavbarDropdown Snippet:
class NavbarItemDropdown extends StatefulWidget {
final List<String> items;
final List<Function> functions;
const NavbarItemDropdown({
Key key,
#required this.items,
this.functions,
}) : super(key: key);
#override
_NavbarItemDropdownState createState() => _NavbarItemDropdownState();
}
class _NavbarItemDropdownState extends State<NavbarItemDropdown> {
#override
Widget build(BuildContext context) {
return DropdownButtonHideUnderline(
child: DropdownButton(
items: widget.items.map((String _value) {
return DropdownMenuItem<String>(
value: _value,
child: _value.contains('label')
? Text(
'${_value.split('label')[1]}',
style: TextStyle(fontSize: 13.0),
)
: Text('${_value.split('action')[1]}'),
);
}).toList(),
onChanged: (String _value) {
if (_value.contains('action')) widget.functions[0]();
},
hint: Text('TestDropDown'),
),
);
}
}