How to reset a DropdownButtonFormField value to default value or reset DropdownButtonFormField after submitting a form.
CodePudding user response:
you can do so using a GlobalKey like:
GlobalKey<FormFieldState> newKey = GlobalKey<FormFieldState>();
and assign it to your DropdownButtonFormField like:
DropdownButtonFormField(
key: newKey,
)
and when you want to reset it you call :
newKey.currentState.reset();
CodePudding user response:
I'll add this to Tareq's answer. To reset the whole form you could use GlobalKey<Form>
, but to reset the elements of the form only you must assign each of them a GlobalKey<FormFieldState>
.
Try out this code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
final _formKey = GlobalKey<FormState>();
final _cityDropdownButtonKey = GlobalKey<FormFieldState>();
List<String> cities = ["Paris", "New york", "Yaoundé"];
String cityValue = "Paris";
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Reset DropDownButton Field"),
),
body: Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.all(32.0),
child: Column(
children: [
DropdownButtonFormField<String>(
key: _cityDropdownButtonKey,
value: cityValue,
items: cities
.map<DropdownMenuItem<String>>(
(e) => DropdownMenuItem(
value: e,
child: Text(e),
),
)
.toList(),
onChanged: (String? newValue) {//Any code},
),
TextFormField(),
ElevatedButton(
onPressed: () {
//Call this to reset the field
_cityDropdownButtonKey.currentState!.reset();
},
child: const Text('Reset the Button Only'),
),
ElevatedButton(
onPressed: () {
//call this to reset the form
_formKey.currentState!.reset();
},
child: const Text('Reset the whole form'),
)
],
),
),
),
),
);
}
}
Make you GlobalKeys static if you want to reset from another page.