I want to unselect the radio button after pressing the submit button - flutter

I want to unselect the radio button after pressing the submit button .And also I want to validate radio button how I can do that the user must select radio button .
This is my code
int? _selectedValue;
#override
void initState() {
super.initState();
_selectedValue = -1;
}
//radio
///Option A
child: RadioListTile(value: 1, groupValue: _selectedValue,
title: Text(option1controller.text.toString()),
subtitle: Text("Option A"),
activeColor: Colors.green,
onChanged: (value){
setState(() {
_selectedValue=value;
// if (option1controller.text.toString()==null) {
//
// }
});
}
),
),
///Submit button
child: ElevatedButton(onPressed:(){
// _selectedValue=-1;
final id=DateTime.now().microsecondsSinceEpoch.toString();
final ref=FirebaseFirestore.instance.collection("Politics");
if (_formKey.currentState!.validate()) {
ref.doc(id).set({"id":id,"Question":questioncontroller.text,"Option A":option1controller.text,"Option B":option2controller.text,
"Option C":option3controller.text,"Option D":option4controller.text,"Correct":_selectedValue.toString();
questioncontroller.clear();
option1controller.clear();
option3controller.clear();
option2controller.clear();
option4controller.clear();
}
}, child: Text("Submit",style: TextStyle(color: Colors.yellowAccent),)),
),
)

Firstly provide dataType on RadioListTile to nullable int while you are using int? _selectedValue;
RadioListTile<int?>(
Now when you like to reset or have to unselect state , assign null on _selectedValue. You can skip providing default value on initState.
onPressed:(){
setState(() {
_selectedValue = null;

Related

How to disable Dropdownlist once user has selected an item in the Dropdownlist in flutter

My DropdownMenuItem coming from API. How to disable the dropDown once user select a item from the list?
child: DropdownButton<Partner>(
value:
_selectedLab, //USER SELECTED DROPDOWN ITEM VALUE
hint: Text("Select Lab"),
isExpanded: true,
items: data.map((Partner data) =>
DropdownMenuItem<Partner>(
child: Text("${data.partnerName}"),
value: data,
)).toList().cast<DropdownMenuItem<Partner>>(),
onChanged: (val) {
setState(() {
_selectedLab = val!;
encLabId = val.encPartnerId;
getTestByLabResult = getTestByLab();
});
},
),
Create a bool on state bool absoreTap = false; and wrap you DropdownButton with AbsorbPointer like
AbsorbPointer(
absorbing: absoreTap,
child: DropdownButton<Partner>(
value:
_selectedLab, //USER SELECTED DROPDOWN ITEM VALUE
hint: Text("Select Lab"),
isExpanded: true,
items: data.map((Partner data) =>
DropdownMenuItem<Partner>(
child: Text("${data.partnerName}"),
value: data,
)).toList().cast<DropdownMenuItem<Partner>>(),
onChanged: (val) {
setState(() {
_selectedLab = val!;
encLabId = val.encPartnerId;
getTestByLabResult = getTestByLab();
absoreTap = true; ///
});
},
),
You can also check Ignore-pointer here is the different between them

Widget Test Doesn't Fire DropdownButton onChanged

I have a widget test that taps an item in the DropdownButton. That should fire the onChanged callback but it doesn't. Here is the test code. The mock is Mockito.
void main() {
//Use a dummy instead of the fake. The fake does too much stuff
final mockServiceClient = MockTheServiceClient();
final apiClient = GrpcApiClient(client: mockServiceClient);
when(mockServiceClient.logEvent(any))
.thenAnswer((_) => MockResponseFuture(LogEventResponse()));
testWidgets("select asset type", (tester) async {
//sets the screen size
tester.binding.window.physicalSizeTestValue = const Size(3840, 2160);
// resets the screen to its orinal size after the test end
addTearDown(tester.binding.window.clearPhysicalSizeTestValue);
await tester.pumpWidget(AssetApp(apiClient), const Duration(seconds: 5));
//Construct key with '{DDLKey}_{Id}'
await tester
.tap(find.byKey(ValueKey("${assetTypeDropDownKey.value}_PUMP")));
await tester.pumpAndSettle(const Duration(seconds: 5));
verify(mockServiceClient.logEvent(any)).called(1);
});
}
This is the build method of the widget:
#override
Widget build(BuildContext context) {
return DropdownButton<DropDownItemDefinition>(
underline: Container(),
dropdownColor: Theme.of(context).cardColor,
hint: Text(
hintText,
style: Theme.of(context).textTheme.button,
),
//TODO: Use the theme here
icon: Icon(
Icons.arrow_drop_down,
color: Theme.of(context).dividerColor,
),
value: getValue(),
onChanged: (ddd) {
setState(() {
onValueChanged(ddd!);
});
},
items: itemss.map<DropdownMenuItem<DropDownItemDefinition>>((value) {
return DropdownMenuItem<DropDownItemDefinition>(
key: ValueKey(
"${(key is ValueKey) ? (key as ValueKey?)?.value.toString() :
''}_${value.id}"),
value: value,
child: Tooltip(
message: value.toolTipText,
child: Container(
margin: dropdownPadding,
child: Text(value.displayText,
style: Theme.of(context).textTheme.headline3))),
);
}).toList(),
);
}
Note that the onValueChanged function calls the logEvent call. The onChanged callback never happens and the test fails. This is the code it should fire.
Future onAssetTypeChange(DropDownItemDefinition newValue) async {
await assetApiClient.logChange(record.id, newValue, DateTime.now());
}
Why does the callback never fire?
Note: I made another widget test and the Mock does verify that the client was called correctly. I think there is some issue with the callback as part of the widget test.
You need to first instruct the driver to tap on the DropdownButton itself, and then, after the dropdown popup shows up, tap on the DropdownMenuItem.
The driver can't find a DropdownMenuItem from the dropdown if the dropdown itself is not active/painted on the screen.

Flutter Radio button not highlighting

I built an app that has a list of users and a user can invite another user so I wanted the user to select multiple users at once and call the invite function I'm trying to accomplish this using a radio list tile button and when the user tap, it adds the user id to a list then when the user submits, the list is sent everything works fine but the problem is the radio list tile button group value does not get updated so the radio does not highlight so, the user does not know it's selected or not I have tried a lot of things but nothing seems to work so if anybody has an idea please help
List<String> users = [];
List<String> userName = ['A', 'N', 'A', 'W', 'J', 'Jo'];
void addRemoveFun(
String selectedVal,
) {
bool selected = users.contains(selectedVal);
if (selected) {
users.remove(selectedVal);
} else {
users.add(selectedVal);
}
}
Widget buildRadio(int index) {
return RadioListTile<List<String>>(
activeColor: ContentTheme.userPreffered(context).greenHighlightColor,
value: userName,
groupValue: selectedNames,
onChanged: (value) {
setState(() {
value = userName;
addRemoveFun(userName[index]);
});
print('$selectedNames');
},
title: Text(
"${userName[index]}",
style: TextStyle(
color: ContentTheme.userPreffered(context).bodyTextColor,
fontSize: ContentSize.fromMediaSize(widget.mediaSize).tileTitleSize,
),
),
);
}
}
Try this
Widget buildRadio(int index) {
return RadioListTile<List<String>>(
activeColor: ContentTheme.userPreffered(context).greenHighlightColor,
// Change userName to index
value: index,
// Change selectedNames to userName
groupValue: userName[index],
onChanged: (value) {
setState(() {
// Change here
userName = value;
addRemoveFun(userName[index]);
});
print('$selectedNames');
},
title: Text(
"${userName[index]}",
style: TextStyle(
color: ContentTheme.userPreffered(context).bodyTextColor,
fontSize: ContentSize.fromMediaSize(widget.mediaSize).tileTitleSize,
),
),
);
}
}

how to update selected radio button in flutter using getx statemanagment

I am using Flutter with GetX plugin and I have two radio buttons inside statelessWidget
but the radio button doesn't changed to selected when user click on it
my question is how I can update screen to show selected radio the groupValue attribute changed using GetX pluing.
here is my code
Radio(
value: reportController.period[0],
groupValue: reportController.selectedPeriod,
onChanged: (val) {
reportController.selectedPeriod = val;
},
)
and this is my controller
import 'package:get/get.dart';
import 'package:ycom/models/report.dart';
class ReportController extends GetxController {
var report = Report().obs;
List<String> period = ["evening", "morning"];
void set selectedPeriod(String selectedPeriod) {
report.update((report) {
report.selectedPeriod = selectedPeriod;
});
}
String get selectedPeriod => report.value.selectedPeriod;
}
I solved it by wrapping Radio widget inside Obx() function as following
Obx(() => Radio(
value: reportController.period[0],
groupValue: reportController.selectedPeriod,
onChanged: (val) {
reportController.selectedPeriod = val;
},
))
Here is what I did to achieve this:
My Controller:
class ProfilePageController extends GetxController {
String selectedGender;
final List<String> gender = ["Male", "Female"];
String select;
void onClickRadioButton(value) {
print(value);
select = value;
update();
}
}
My View Code:
Row addRadioButton(int btnIndex, String title) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
GetBuilder<ProfilePageController>(
builder: (_) => Radio(
activeColor: Colors.blue,
value: profilePageController.gender[btnIndex],
groupValue: profilePageController.select,
onChanged: (value) =>
profilePageController.onClickRadioButton(value)),
),
Text(title)
],
);
}
To use, call addRadioButton:
Row(
children: [
addRadioButton(0, "Male"),
addRadioButton(1, "Female"),
],
),
Try {setState(() {reportController.selectedPeriod = val;});} instead {reportController.selectedPeriod = val;},

Flutter TextField calls onSubmitted unexpectedly

My case is I have a widget with TextField used for search. When I type something in TextField the cross icon become visible in suffixIcon (to clear). I do not do search and just click the cross icon to clear the entered input but onSubmitted is called and search executed!!! But I don't need it! I do not submit the text input, I cancel it!!
final searchClear = ValueNotifier(false);
final searchController = TextEditingController();
// in initState method:
searchController.addListener(() {
searchClear.value = searchController.text.isNotEmpty;
});
// in build method:
TextField(
...
controller: searchController,
suffixIcon: ValueListenableBuilder<bool>(
valueListenable: searchClear,
builder: (_,visible,child) {
return Visibility(
visible: visible,
child:child,
);
},
child: InkWell(
child: Icon(Icons.close),
onTap: () {
searchController.clear();
searchFocus.unfocus();
}
),
),
onSubmitted: (value) {
if(value.isEmpty) {
FocusScope.of(context).requestFocus(searchFocus);
} else {
widget.search(value);
}
}
),
P.S. Any ideas to work around this?