我想要重置DropdownButtonFormField的值,值被更改为null,但DropdownButtonFormField没有更改。问题出在哪里?如果我使用了DropdownButton,它正确地改变了值,值被清除了。我需要使用DropdownButtonFormField。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
String abc;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center (
child: Column(
children: <Widget>[DropdownButtonFormField(
hint: Text('select value'),
value: abc,
items: <String>['A', 'B', 'C', 'D'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
abc = newValue;
});
},
),
Text("value is $abc"),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
setState((){
abc = null;
});
},
tooltip: 'Reset',
child: Icon(Icons.clear),
)
),
);
}
}
发布于 2020-09-20 17:28:02
您可以使用GlobalKey<FormFieldState>
。
class SomeWidget extends StatelessWidget {
final GlobalKey<FormFieldState> _key;
@override
Widget build() {
return DropdownButtonFormField(
key: _key,
//...
)
}
reset() {
_key.currentState.reset();
}
}
发布于 2020-12-30 22:36:18
class SomeWidget extends StatelessWidget {
final GlobalKey<FormFieldState> _key = GlobalKey<FormFieldState>();
@override
Widget build() {
return DropdownButtonFormField(
key: _key,
//...
)
}
reset() {
_key.currentState.reset();
}
}
https://stackoverflow.com/questions/61463276
复制相似问题