首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在颤动DropdownButtonFormField中重置值

如何在颤动DropdownButtonFormField中重置值
EN

Stack Overflow用户
提问于 2020-04-28 00:11:39
回答 2查看 2.5K关注 0票数 2

我想要重置DropdownButtonFormField的值,值被更改为null,但DropdownButtonFormField没有更改。问题出在哪里?如果我使用了DropdownButton,它正确地改变了值,值被清除了。我需要使用DropdownButtonFormField。

代码语言:javascript
运行
复制
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),
       )        
       ),
    );
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-20 17:28:02

您可以使用GlobalKey<FormFieldState>

代码语言:javascript
运行
复制
class SomeWidget extends StatelessWidget {
  final GlobalKey<FormFieldState> _key;

  @override
  Widget build() {
    return DropdownButtonFormField(
      key: _key,
      //...
    )
  }

  reset() {
    _key.currentState.reset();
  }
}

https://dartpad.dev/04247868fa2e86c5f417532486b48870

票数 9
EN

Stack Overflow用户

发布于 2020-12-30 22:36:18

代码语言:javascript
运行
复制
class SomeWidget extends StatelessWidget {
  final GlobalKey<FormFieldState> _key = GlobalKey<FormFieldState>();

  @override
  Widget build() {
    return DropdownButtonFormField(
      key: _key,
      //...
    )
  }

  reset() {
    _key.currentState.reset();
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61463276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档