I'm trying to change the DropdownButtonFormField value on event (button press for example) using setState. But it's not working.
Note: it works in case I use DropdownButton, but with DropdownButtonFormField it's not responding.
Here is a simple code showing what I'm trying to implement.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Testing(),
);
}
}
class Testing extends StatefulWidget {
@override
_TestingState createState() => _TestingState();
}
class _TestingState extends State<Testing> {
String selectedValue;
@override
Widget build(BuildContext context) {
return Material(
child: Column(
children: <Widget>[
DropdownButtonFormField(
value: selectedValue,
items: ['one', 'two'].map((value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (value) {
setState(() {
selectedValue = value;
});
},
),
RaisedButton(
child: Text('test'),
onPressed: (){
setState(() {
selectedValue = 'two';
});
},
),
],
),
);
}
}
Define instance variable from Global Key and pass it to DropdownButtonFormField
final dropdownState = GlobalKey<FormFieldState>();
You can change the value of dropDownFieldItem by calling this method
dropdownState.currentState.didChange('two');
final code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Testing(),
);
}
}
class Testing extends StatefulWidget {
@override
_TestingState createState() => _TestingState();
}
class _TestingState extends State<Testing> {
String selectedValue;
final dropdownState = GlobalKey<FormFieldState>();
@override
Widget build(BuildContext context) {
return Material(
child: Column(
children: <Widget>[
DropdownButtonFormField(
key: dropdownState,
value: selectedValue,
items: ['one', 'two'].map((value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (value) {
setState(() {
selectedValue = value;
});
},
),
RaisedButton(
child: Text('test'),
onPressed: () {
dropdownState.currentState.didChange('one');
},
),
],
),
);
}
}
Here working normally with DropdownButtonFormField and DropdownButton.
flutter --version
Flutter 1.12.13+hotfix.9 • channel stable •
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With