gpt4 book ai didi

flutter - DropdownButtonFormField 不是第一次重置

转载 作者:行者123 更新时间:2023-12-03 03:35:18 28 4
gpt4 key购买 nike

我想重置 DropdownButtonFormField。我设法通过将其设置为 null 并使用 globalkey 作为以下代码来重置它。

在这里,问题是我需要 点击两次重置它。

注意:我知道使用 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;
FocusNode _node = FocusNode();
GlobalKey<FormState> _key = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Form(
key: _key,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Focus(
focusNode: _node,
onFocusChange: (bool focus) {
setState(() {});
},
child: Listener(
onPointerDown: (_) {
FocusScope.of(context).requestFocus(_node);
},
child: 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;
_key.currentState.reset();
});
},
tooltip: 'Reset',
child: Icon(Icons.clear),
)),
);
}
}

最佳答案

您可能需要手动对焦
您还需要提供全局键来形成


FocusNode _node = FocusNode();
...


Focus(
focusNode: _node,
onFocusChange: (bool focus) {
setState(() {});
},
child: Listener(
onPointerDown: (_) {
FocusScope.of(context).requestFocus(_node);
},
child: DropdownButtonFormField(
iconSize: 50,
onChanged: (s) {
setState(() {
abc = s;
});
},
hint: Text(
'Select Text',
),
items: [
DropdownMenuItem(value: '1', child: Text('A')),
DropdownMenuItem(value: '2', child: Text('B')),
DropdownMenuItem(value: '3', child: Text('C')),
DropdownMenuItem(value: '4', child: Text('D')),
],
),
),
),

...
FloatingActionButton(
onPressed: () {
setState(() {
print("hello");
abc = null;
_key.currentState.reset();
});
// _flyIronMan();
},
child: Icon(Icons.add),
),

关于flutter - DropdownButtonFormField 不是第一次重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61473133/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com