[英]Flutter DropdownButtonFormField is expanding but shouldn't
[英]How to reset value in Flutter DropdownButtonFormField
我想在 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),
)
),
);
}
}
您可以使用GlobalKey<FormFieldState>
。
class SomeWidget extends StatelessWidget {
final GlobalKey<FormFieldState> _key;
@override
Widget build() {
return DropdownButtonFormField(
key: _key,
//...
)
}
reset() {
_key.currentState.reset();
}
}
class SomeWidget extends StatelessWidget {
final GlobalKey<FormFieldState> _key = GlobalKey<FormFieldState>();
@override
Widget build() {
return DropdownButtonFormField(
key: _key,
//...
)
}
reset() {
_key.currentState.reset();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.