Trouble with flutter radio button - dart

I just want to have normal radio buttons where only one button in the group can be selected. According to tutorials online we need to set the groupvalue variable to the value in the setState method in onChanged. If i do this i can select all buttons and i dont want this to happen. I want only one button to be a selected at a time(from that group). if there is anything wrong with my code or any other way to do it let me know.
option is the string parameter for title optionvalue is the value for that option.
class Option extends StatefulWidget {
final String option;
final int optionvalue;
Option(this.option, this.optionvalue);
_OptionState createState() => _OptionState();
}
class _OptionState extends State<Option> {
int groupvalue;
#override
Widget build(BuildContext context) {
return Container(
child: Container(
child: RadioListTile(
title: Text(
widget.option,
style: TextStyle(fontSize: 20.0),
),
activeColor: Colors.black,
value: widget.optionvalue,
groupValue: groupvalue,
onChanged: (int a) {
print(a);
setState(() {
groupvalue = a;
});
},
),
),
);
}
}

Try this code
int _groupValue = -1;
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
_myRadioButton(
title: "Checkbox 0",
value: 0,
onChanged: (newValue) => setState(() => _groupValue = newValue),
),
_myRadioButton(
title: "Checkbox 1",
value: 1,
onChanged: (newValue) => setState(() => _groupValue = newValue),
),
],
);
}
Widget _myRadioButton({String title, int value, Function onChanged}) {
return RadioListTile(
value: value,
groupValue: _groupValue,
onChanged: onChanged,
title: Text(title),
);
}
Output:

Try this for horizontal radio button list:
int _groupValue = -1;
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text('Gender', style: TextStyle(fontSize: 18)),
Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
flex: 1,
child: RadioListTile(
value: 0,
groupValue: _groupValue,
title: Text("Male"),
onChanged: (newValue) =>
setState(() => _groupValue = newValue),
activeColor: Colors.red,
selected: false,
),
),
Expanded(
flex: 1,
child: RadioListTile(
value: 1,
groupValue: _groupValue,
title: Text("Female"),
onChanged: (newValue) =>
setState(() => _groupValue = newValue),
activeColor: Colors.red,
selected: false,
),
),
],
),
],
),
),
],
),
),

Related

Flutter - DropdownButtonFormField value not updating

My Dropdown button value doesn't update until the AlertDialog box is closed and reopened.
I have the variable set at the top of my class
class _ItemListState extends State<ItemList> {
int _ratingController;
...
}
Within the class I have an AlertDialog that opens a form, within here I have the DropdownButtonFormField
AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: _eateryController,
autofocus: true,
decoration:
InputDecoration(labelText: 'Eatery', hintText: 'eg Pizza Hut'),
),
TextField(
controller: _supplierController,
decoration: InputDecoration(
labelText: 'Supplier', hintText: 'eg Deliveroo'),
),
TextField(
controller: _descriptionController,
decoration: InputDecoration(
labelText: 'Description', hintText: 'eg cheese pizza'),
),
DropdownButtonFormField<int>(
value: _ratingController,
items: [1, 2, 3, 4, 5]
.map((label) => DropdownMenuItem(
child: Text(label.toString()),
value: label,
))
.toList(),
hint: Text('Rating'),
onChanged: (value) {
setState(() {
_ratingController = value;
});
},
),
],
),
actions: <Widget>[
FlatButton(
onPressed: () {
_handleSubmit(_eateryController.text, _supplierController.text,
_descriptionController.text, _ratingController);
Navigator.pop(context);
},
child: Text('Save'),
),
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancel'),
)
],
);
the setState doesn't seem to be dynamically updating the fields value. The updated value will only show once I close and re open the AlertDialog.
How can I get this to update instantly?
Thanks
You need to create a new StatefulWidget class that should return your AlertDialog
class MyDialog extends StatefulWidget {
#override
_MyDialogState createState() => _MyDialogState();
}
class _MyDialogState extends State<MyDialog> {
int _ratingController;
#override
Widget build(BuildContext context) {
return AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: _eateryController,
autofocus: true,
decoration:
InputDecoration(labelText: 'Eatery', hintText: 'eg Pizza Hut'),
),
TextField(
controller: _supplierController,
decoration: InputDecoration(
labelText: 'Supplier', hintText: 'eg Deliveroo'),
),
TextField(
controller: _descriptionController,
decoration: InputDecoration(
labelText: 'Description', hintText: 'eg cheese pizza'),
),
DropdownButtonFormField<int>(
value: _ratingController,
items: [1, 2, 3, 4, 5]
.map((label) => DropdownMenuItem(
child: Text(label.toString()),
value: label,
))
.toList(),
hint: Text('Rating'),
onChanged: (value) {
setState(() {
_ratingController = value;
});
},
),
],
),
actions: <Widget>[
FlatButton(
onPressed: () {
_handleSubmit(_eateryController.text, _supplierController.text,
_descriptionController.text, _ratingController);
Navigator.pop(context);
},
child: Text('Save'),
),
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancel'),
)
],
);
}
}
Use it like this
showDialog(
context: context,
builder: (context) {
return MyDialog();
},
);
You can use statefulBuilder inside alert dialog.
return AlertDialog(
title: new Text('Table'),
content: StatefulBuilder(builder:
(BuildContext context,
StateSetter setState) {
return Container(
child: new SingleChildScrollView(
scrollDirection: Axis.vertical,
child: new Column(
children: <Widget>[
DropdownButtonFormField<String>(
value: dropdownValue,
style: TextStyle(
color: Colors.black87),
items: <String>[
'Lot 1',
'Lot 2',
'Lot 3',
'Lot 4',
].map<
DropdownMenuItem<
String>>(
(String value) {
return DropdownMenuItem<
String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
),
```
It looks like you're calling setState in a wrong widget. The AlertDialog doesn't belong to ItemList's tree because it's located inside another Route. So calling setState inside _ItemListState won't rebuild the AlertDialog.
Consider pulling out content of AlertDialog into a separate StatefulWidget and putting int _ratingController into it's state.

How to buid Card?

I'm new on Flutter and I'm now working on my first project, then in one of my page I'm building form in order to collect informations, so I created two Card but went I'm trying adding some TextField in the second one, all the the content disappear.
Please Help :(
import 'package:flutter/material.dart';
import 'customInputField.dart';
class DropDown extends StatefulWidget {
#override
_DropDownState createState() => _DropDownState();
}
class _DropDownState extends State<DropDown> {
// Here we're going to define the LIST
List _cities = ["Douala","Yaoundé"];
List _weight = ["0-1","1-3","3-5"];
List _dimensions = ["A5","A4","A3","A2"];
// End
var resultsList = new List.filled(3, "");
#override
void initState(){
// Here we're going to set the initial values
resultsList[0] = "Douala";
resultsList[1] = "0-1";
resultsList[2] = "A5";
return super.initState();
}
// Here we're going to create the method which will build and update the dropDown menu
_fieldDropDown(List theList, int resultPosition, var dbField) {
return new FormField(
builder: (FormFieldState state) {
return InputDecorator(
decoration: InputDecoration(),
child: new DropdownButtonHideUnderline(
child: new DropdownButton(
value: this.resultsList[resultPosition],
isDense: true,
onChanged: (dynamic newValue) {
setState(() {
this.resultsList[resultPosition] = newValue;
state.didChange(newValue);
print(
'The List result = ' + this.resultsList[resultPosition]);
//write newValue to a database field, which can be used in the override init to set the field originally
});
},
// Comment to remove Error
items: theList.map((dynamic value) {
return new DropdownMenuItem(
value: value,
child: new Text(value),
);
}).toList(),
),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Container(
decoration: new BoxDecoration(
color: Color.fromRGBO(0x12, 0x34, 0x55, 0.9),
),
child: new Form(
//key: _formKey,
autovalidate: true,
child: new ListView(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
children: [
Card(
child: Padding(
padding: EdgeInsets.fromLTRB(8, 20, 8, 10),
child: Column(
children: <Widget>[
Text('Informations sur le colis',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, ),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('Pli'),
new Radio(
value: 0,
groupValue: null,
onChanged: null
),
new Text('Colis'),
new Radio(
value: 1,
groupValue: null,
onChanged: null
)
]
),
//create some fields, hand in the list
Row(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width*.3,
child: Text('Départ:', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
),
Container(
width: MediaQuery.of(context).size.width*.5,
child: _fieldDropDown(_cities, 0, 'colorDBfield')
)
],
),
Row(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width*.3,
child: Text('Poids:', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
),
Container(
width: MediaQuery.of(context).size.width*.5,
child: _fieldDropDown(_weight, 1, 'dogDBfield'),
)
],
),
Row(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width*.3,
child: Text('Dimensions:', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
),
Container(
width: MediaQuery.of(context).size.width*.5,
child: _fieldDropDown(_dimensions, 2, 'peopleDBfield'),
)
],
),
],
)),
),
Card(
child: Padding(
padding: EdgeInsets.fromLTRB(8, 20, 8, 10),
child: Column(
children: <Widget>[
Text('Informations sur le destinataire',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, ),
),
Row(
children: <Widget>[
new TextField(
decoration: InputDecoration(
border: OutlineInputBorder()
),
),
],
)
],
),
),
)
],
)
),
),
);
}
}

How to customize dropdown button

am trying to create a dropdown button which has an icon .. i want the whole dropdown to be underlined and also i want to set icon from my assets not from the icons.. plus i want to manage its height..
how to achive all of this?
what am doing right now is:
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new InputDecorator(
decoration: const InputDecoration(
icon: const Icon(
Icons.flag,
color: Color(0xFF49C275),
),
),
child: DropdownButtonHideUnderline(
child: new DropdownButton<Gender>(
hint: new Text("المدينة"),
value: selectedGender,
onChanged: (Gender newValue) {
setState(() {
selectedGender = newValue;
});
},
items: genders.map((Gender gender) {
return new DropdownMenuItem<Gender>(
value: gender,
child: new Text(
gender.gender,
style:
new TextStyle(color: Color(0xFF707070)),
),
);
}).toList(),
),
),
),
],
),
and am getting this result:
when i want it to look like this:
How to do this?
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new InputDecorator(
decoration: const InputDecoration(
// use prefixIcon instead of icon
prefixIcon: const Icon(
Icons.flag,
color: Color(0xFF49C275),
),
),
child: DropdownButtonHideUnderline(
child: new DropdownButton<Gender>(
hint: new Text("المدينة"),
value: selectedGender,
onChanged: (Gender newValue) {
setState(() {
selectedGender = newValue;
});
},
items: genders.map((Gender gender) {
return new DropdownMenuItem<Gender>(
value: gender,
child: new Text(
gender.gender,
style:
new TextStyle(color: Color(0xFF707070)),
),
);
}).toList(),
),
),
),
],
),

Programmatically expand ExpansionTile in Flutter

I’m just trying to use ExpansionTile in Flutter, from example I modified to become like this:
I want to hide the arrow and use Switch to expand the tile, is it possible? Or do I need custom widget which render children programmatically? Basically, I just need to show/hide the children
Here’s my code:
import 'package:flutter/material.dart';
void main() {
runApp(ExpansionTileSample());
}
class ExpansionTileSample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('ExpansionTile'),
),
body: ListView.builder(
itemBuilder: (BuildContext context, int index) =>
EntryItem(data[index]),
itemCount: data.length,
),
),
);
}
}
// One entry in the multilevel list displayed by this app.
class Entry {
Entry(this.title,[this.question='',this.children = const <Entry>[]]);
final String title;
final String question;
final List<Entry> children;
}
// The entire multilevel list displayed by this app.
final List<Entry> data = <Entry>[
Entry(
'Chapter A',
'',
<Entry>[
Entry(
'Section A0',
'',
<Entry>[
Entry('Item A0.1'),
Entry('Item A0.2'),
Entry('Item A0.3'),
],
),
Entry('Section A1','text'),
Entry('Section A2'),
],
),
Entry(
'Chapter B',
'',
<Entry>[
Entry('Section B0'),
Entry('Section B1'),
],
),
Entry(
'Chapter C',
'',
<Entry>[
Entry('Section C0'),
Entry('Section C1')
],
),
];
// Displays one Entry. If the entry has children then it's displayed
// with an ExpansionTile.
class EntryItem extends StatelessWidget {
const EntryItem(this.entry);
final Entry entry;
Widget _buildTiles(Entry root) {
if (root.children.isEmpty) return Container(
child:Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 32.0,
),
child:Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:[
Text(root.title),
Divider(height: 10.0,),
root.question=='text'?Container(
width: 100.0,
child:TextField(
decoration: const InputDecoration(helperText: "question")
),
):Divider()
]
)
)
);
return ExpansionTile(
//key: PageStorageKey<Entry>(root),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:[
Text(root.title),
Switch(
value:false,
onChanged: (_){},
)
]
),
children: root.children.map(_buildTiles).toList(),
);
}
#override
Widget build(BuildContext context) {
return _buildTiles(entry);
}
}
#diegoveloper 's answer is almost ok,one small issue not covereed is: it doesn't propogate click on Switch further to ExpansionTile, so if you click outside switch it's expanding, while clicking on Switch does nothing. Wrap it with IgnorePointer, and on expansion events set the value for switch. It's a bit backwards logic, but works good.
...
return ExpansionTile(
onExpansionChanged: _onExpansionChanged,
// IgnorePointeer propogates touch down to tile
trailing: IgnorePointer(
child: Switch(
value: isExpanded,
onChanged: (_) {},
),
),
title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Text(root.title),
]),
children: root.children.map((entry) => EntryItem(entry)).toList(),
);
...
I think this will help you
initiallyExpanded : true
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Divider(
height: 17.0,
color: Colors.white,
),
ExpansionTile(
key: Key(index.toString()), //attention
initiallyExpanded : true,
leading: Icon(Icons.person, size: 50.0, color: Colors.black,),
title: Text('Faruk AYDIN ${index}',style: TextStyle(color: Color(0xFF09216B), fontSize: 17.0, fontWeight: FontWeight.bold)),
subtitle: Text('Software Engineer', style: TextStyle(color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.bold),),
children: <Widget>[
Padding(padding: EdgeInsets.all(25.0),
child : Text('DETAİL ${index} \n' + 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using "Content here, content here", making it look like readable English.',)
)
],
onExpansionChanged: ((newState){
if(newState)
setState(() {
Duration(seconds: 20000);
selected = index;
});
else setState(() {
selected = -1;
});
})
),
]
);
Yes, it's possible, I modified your code a little :
class EntryItem extends StatefulWidget {
const EntryItem(this.entry);
final Entry entry;
#override
EntryItemState createState() {
return new EntryItemState();
}
}
class EntryItemState extends State<EntryItem> {
var isExpanded = false;
_onExpansionChanged(bool val) {
setState(() {
isExpanded = val;
});
}
Widget _buildTiles(Entry root) {
if (root.children.isEmpty)
return Container(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 32.0,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(root.title),
Divider(
height: 10.0,
),
root.question == 'text'
? Container(
width: 100.0,
child: TextField(
decoration: const InputDecoration(
helperText: "question")),
)
: Divider()
])));
return ExpansionTile(
onExpansionChanged: _onExpansionChanged,
trailing: Switch(
value: isExpanded,
onChanged: (_) {},
),
//key: PageStorageKey<Entry>(root),
title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Text(root.title),
]),
children: root.children.map((entry) => EntryItem(entry)).toList(),
);
}
#override
Widget build(BuildContext context) {
return _buildTiles(widget.entry);
}
}
Basically I changed from Stateless to Stateful because you need to handle the state of your Switch widget.
There is a trailing property from ExpansionTile where I put the Switch to remove the arrow widget by default.
Listen the onExpansionChanged: _onExpansionChanged,, to change the status of the Switch.
And finally build the children as new widgets:
children: root.children.map((entry) => EntryItem(entry)).toList(),
initiallyExpanded = true , this answer is correct but if we have a TextFiled inside the ExpansionTile's children , then the keyboard automatically hides(bug).
So my solution is wrap the children with Visibility widget and control visibilty.
initially declare bool _expansionVisibility = false;
ExpansionTile(
onExpansionChanged: (changed) {
setState(() {
print("changed $changed");
if (changed) {
_expansionVisibility = true;
} else {
_expansionVisibility = false;
}
});
},
title: Text(
"Change Password",
),
children: <Widget>[
Visibility(
visible: _expansionVisibility,
child: Container(),
),
],
),
Short answer: Set initiallyExpanded true or false, accordingly with the help of onExpansionChanged. But remember initiallyExpanded applies only for initial state, so the key of the widget should be changed to apply changes. Now to change key a workaround is:
ExpansionTile(
key: PageStorageKey("${DateTime.now().millisecondsSinceEpoch}"),
initiallyExpanded: ....
onExpansionChanged: ....
.
.
.
)

How can I remove internal padding on a RadioListTile so I can use 3 RadioListTiles in a row?

I am pretty new to Flutter and Dart and I can't seem to find any hints for this particular topic. I am trying to put 3 RadioListTiles in a Row like so:
Row(
children: [
Expanded(
child:RadioListTile<GoalSelection>(
title: Text(
'Net',
style: Theme.of(context).textTheme.body1,
),
value: GoalSelection.net,
groupValue: _goalSelection,
onChanged: (GoalSelection value) {
setState(() {
_goalSelection = value;
});
},
),
),
Expanded(
child: RadioListTile<GoalSelection>(
title: Text(
'Gross',
style: Theme.of(context).textTheme.body1,
),
value: GoalSelection.gross,
groupValue: _goalSelection,
onChanged: (GoalSelection value) {
setState(() {
_goalSelection = value;
});
},
),
),
Expanded(
child: RadioListTile<GoalSelection>(
title: Text(
'Salary',
style: Theme.of(context).textTheme.body1,
),
value: GoalSelection.salary,
groupValue: _goalSelection,
onChanged: (GoalSelection value) {
setState(() {
_goalSelection = value;
});
},
),
),
],
),
The buttons layout fine, but there seems to be a lot of wasted space for the label. I put a screenshot of what it currently looks like below. I have tried wrapping the Expanded, the RadioListTile, and the Text in Padding widgets (all one at a time) to manually set the padding to 0, but it didn't do anything. I have also tried to change Expanded to Flexible even though I didn't think that would change anything. I am at a loss now. Is there any way to get this layout to work? I am kind of assuming it is something really dumb that I am doing.
You can use Radio + text widget instead of RadioListTile. For removing internal padding in Radio widget set:
Radio(
visualDensity: const VisualDensity(
horizontal: VisualDensity.minimumDensity,
vertical: VisualDensity.minimumDensity),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
.....
),
You can use a Radio and Text widget in a row. But the Radio also has the same padding problem. To remove the padding you can put the Radio as a child of a SizedBox.
eg:- SizedBox(height: 20, width: 20, child: Radio(.......))
RadioListTile is used with the purpose of taking the full width in a vertical scroll list.
If you don't want this behavior, don't use it. Use Radio instead.
just set contentPadding: EdgeInsets.zero
RadioListTile(contentPadding: EdgeInsets.zero)
We can control the padding of the RadioListTile using Flexible widget. As you want to arrange 3 RadioListTiles inside a Row Widget. Please try with the below code, it will work.
Row(
children: <Widget>[
Flexible(
fit: FlexFit.loose,
child:
RadioListTile(
title: const Text('hello'),
onChanged: (value) {
setState(() {});
},
),
),
Flexible(
fit: FlexFit.loose,
child:
RadioListTile(
title: const Text('Lafayette'),
onChanged: (value) {
setState(() {});
},
),
)
],
),
Do, let me know. Once you tried with the above code. If it resolved you problem, please accept my answer as useful and provide your valuable comments.
I got the same problem. You could try to customize with Radio, Text, InkWell, Padding.
class LabeledRadio extends StatelessWidget {
const LabeledRadio({
this.label,
this.padding,
this.groupValue,
this.value,
this.onChanged,
});
final String label;
final EdgeInsets padding;
final bool groupValue;
final bool value;
final Function onChanged;
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
if (value != groupValue)
onChanged(value);
},
child: Padding(
padding: padding,
child: Row(
children: <Widget>[
Radio<bool>(
groupValue: groupValue,
value: value,
onChanged: (bool newValue) {
onChanged(newValue);
},
),
Text(label),
],
),
),
);
}
}
// ...
bool _isRadioSelected = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <LabeledRadio>[
LabeledRadio(
label: 'This is the first label text',
padding: const EdgeInsets.symmetric(horizontal: 5.0),
value: true,
groupValue: _isRadioSelected,
onChanged: (bool newValue) {
setState(() {
_isRadioSelected = newValue;
});
},
),
LabeledRadio(
label: 'This is the second label text',
padding: const EdgeInsets.symmetric(horizontal: 5.0),
value: false,
groupValue: _isRadioSelected,
onChanged: (bool newValue) {
setState(() {
_isRadioSelected = newValue;
});
},
),
],
),
);
}
The documentation: https://api.flutter.dev/flutter/material/RadioListTile-class.html#material.RadioListTile.3
This is how I fix the padding:
enum ContactSex { nam, nu, khac }
class CreateContactScreen extends StatefulWidget {
static const routeName = './create_contact';
#override
_CreateContactScreenState createState() => _CreateContactScreenState();
}
class _CreateContactScreenState extends State<CreateContactScreen> {
ContactSex _contaxtSex = ContactSex.nu;
final _form = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'TẠO LIÊN HỆ',
style: kHeaderTextStyle,
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('XONG', style: TextStyle(color: Colors.white),),
)
],
),
body: Container(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
child: Form(
key: _form,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: 'Tên*',
),
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) {
// TODO: when submit this text field
},
validator: (value) {
if (value.isEmpty) {
return 'Hãy nhập tên cho liên hệ.';
}
return null;
},
onSaved: (value) {
// TODO : when save the whole form
},
),
TextFormField(
decoration: InputDecoration(
labelText: 'Họ',
),
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) {
// TODO: when submit this text field
},
// validator: (value) {
// if (value.isEmpty) {
// return null;
// }
// return null;
// },
onSaved: (value) {
// TODO : when save the whole form
},
),
TextFormField(
decoration: InputDecoration(
labelText: 'Số điện thoại*',
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) {
// TODO: when submit this text field
},
validator: (value) {
if (value.isEmpty) {
return 'Hãy nhập số điện thoại cho liên hệ.';
}
return null;
},
onSaved: (value) {
// TODO : when save the whole form
},
),
TextFormField(
decoration: InputDecoration(
labelText: 'Email',
),
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) {
// TODO: when submit this text field
},
// validator: (value) {
// if (value.isEmpty) {
// return null;
// }
// return null;
// },
onSaved: (value) {
// TODO : when save the whole form
},
),
Container(
padding: EdgeInsets.only(top: 15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Giới tính',
style: TextStyle(fontSize: 14.0),
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
LabeledRadio(
label: 'Nữ',
padding: EdgeInsets.all(0),
groupValue: _contaxtSex,
value: ContactSex.nu,
onChanged: (ContactSex newValue) {
setState(() {
_contaxtSex = newValue;
});
},
),LabeledRadio(
label: 'Nam',
padding: EdgeInsets.all(0),
groupValue: _contaxtSex,
value: ContactSex.nam,
onChanged: (ContactSex newValue) {
setState(() {
_contaxtSex = newValue;
});
},
),LabeledRadio(
label: 'Khác',
padding: EdgeInsets.all(0),
groupValue: _contaxtSex,
value: ContactSex.khac,
onChanged: (ContactSex newValue) {
setState(() {
_contaxtSex = newValue;
});
},
),
],
),
],
),
)
],
)),
),
),
);
}
}
class LabeledRadio extends StatelessWidget {
final String label;
final EdgeInsets padding;
final ContactSex groupValue;
final ContactSex value;
final Function onChanged;
const LabeledRadio(
{this.label, this.padding, this.groupValue, this.value, this.onChanged});
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
if (value != groupValue) {
onChanged(value);
}
},
child: Padding(
padding: padding,
child: Row(
children: <Widget>[
Radio<ContactSex>(
groupValue: groupValue,
value: value,
onChanged: (ContactSex newValue) {
onChanged(newValue);
},
),
Text(label),
],
),
),
);
}
}
You just need to set the "dense" property to true, example:
RadioListTile<String>(
title: "My radio",
dense: true, // <= here it is !
value: '1',
);
you should achieve this manually like
make a group of Radio() and Text() and wrap with InkWell() for state handling. now remove extra space of radio by materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, That's it. Get idea by sample code.
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
setState(() {
_radioVenue = 0;
});
},
child: Row(
children: [
Radio(
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
activeColor: primaryColor,
groupValue: _radioVenue,
onChanged: (value) {},
value: 0,
),
Text('From our list')
],
),
),
InkWell(
onTap: () {
setState(() {
_radioVenue = 1;
});
},
child: Row(
children: [
Radio(
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
activeColor: primaryColor,
groupValue: _radioVenue,
onChanged: (value) {},
value: 1,
),
Text('From our list')
],
),
),
],
),
We covered both both the issues in this sample.
Removed extra spaces.
whole group is selectable radio + text, Now it behaves like RadioListTile().
Simply use RadioListTile and remove extra padding, by default it's 18
RadioListTile(contentPadding: EdgeInsets.symmetric(horizontal: 0.0)),
OR
RadioListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
value: null,
groupValue: null,
onChanged: null,
),
glad to answer
I was looking for same question and ended up on Flutter Documentation
I was working on Column and RadioListTile and I faced same issue, there's a horizontal padding between content inside RadioListTile
So, here it's the answer
Looking for this documentation ! RadioListTile content padding
Just add contentPadding: EdgeInsets.symmetric(horizontal: 0) and here you go, there's no horizontal padding anymore
Just copy paste this code and enjoy
Container(
height:35,
child: Row(
children: [
Radio(
groupValue: data.selected,
value: e,
onChanged: (DataBindModel? value) {
listener.value = MultiChoiceData(selected: value, items: listener.value.items);
onChanged(value);
onSelected(value);
},
),
Text(
e.value,
style: body14,
)
],
),
)
Copy the RadioListTile code and create your on new new file and paste it in there.
Remove the imports causing errors:
import 'package:flutter/widgets.dart'; // leave it
import 'package:flutter/material.dart'; //add
import 'list_tile.dart'; //remove
import 'radio.dart'; //remove
import 'theme.dart'; //remove
import 'theme_data.dart'; //remove
Then add the following padding to it, like this:
//Inside the file locate this widget and Add the padding or remove it. I needed to remove it and add 5.
return MergeSemantics(
child: ListTileTheme.merge(
contentPadding: EdgeInsets.only( // Add this
left: 5,
right: 0,
bottom: 0,
top: 0
),
selectedColor: activeColor ?? Theme.of(context).accentColor,
child: ListTile(
leading: leading,
title: title,
subtitle: subtitle,
trailing: trailing,
isThreeLine: isThreeLine,
dense: dense,
enabled: onChanged != null,
onTap: onChanged != null && !checked ? () { onChanged(value); } : null,
selected: selected,
),
),
);
then Import the file into your project like this:
import 'package:Project_Name/common/customComponets/custom_radio_list_tile.dart' as CustomRadioListTile;
Then use it like this:
CustomRadioListTile.RadioListTile(); // and that's how I managed to do it. Thought I should share.
This is my way of reducing the space. I have three Radio in one row.
Row(
children: [
Expanded(
child: RadioListTile(
contentPadding: EdgeInsets.all(0.0),
value: DayoffType.Range,
groupValue: _dayoffType,
title: Transform.translate(offset: const Offset(-18, 0), child: Text('Range')),
onChanged: (DayoffType? val) {
setState(() {
_dayoffType = val!;
});
},
),
),
Expanded(...Radio2...),
Expanded(...Radio3...)
)

Resources