Reputation: 13
I am implementing an app in flutter having checkboxes on the homepage. The user has a chance to select items from the list and then he can share. Everything is fine until now. but, after sharing I want to add a reset option to the user that he can start from the beginning. Like, Unchecking and resetting all items and related data to that checked items. How can I function my reset button to do this?
Upvotes: 0
Views: 2277
Reputation: 785
You can simply reset checkboxes or any other control widget by initializing them to their initial value in onPressed
property of the ResetButton and calling setState((){})
. See the code below on how to do that:
import 'package:flutter/material.dart';
class MyForm extends StatefulWidget {
MyFormState createState() => MyFormState();
}
class MyFormState extends State<MyForm> {
bool checkBoxValue1 = false;
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
Text(
"CheckBox1 Value : $checkBoxValue1",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
Form(
child: FormField<bool>(
initialValue: false,
builder: (FormFieldState<bool> state) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Checkbox(
value: checkBoxValue1,
onChanged: (value) {
checkBoxValue1 = value;
setState(() {});
},
),
const Text("Check Box 1")
],
);
},
),
),
RaisedButton(
child: const Text("Reset"),
onPressed: () {
//Reset All Checkboxes
checkBoxValue1 = false;
//checkBoxValue2 = false;
//checkBoxValue3 = false;
//checkBoxValue4 = false;
setState(() {});
},
)
],
);
}
}
You can also provide a GlobalKey<FormState> _key
to Form
, if you have many textfields , radiobuttons etc and want to reset them to their initial value , just call _key.currentState.reset()
.
Upvotes: 1