【问题标题】:How to reset value in Flutter DropdownButtonFormField如何在 Flutter DropdownButtonFormField 中重置值
【发布时间】:2020-08-11 06:25:15
【问题描述】:

我想在 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),
       )        
       ),
    );
  }
}

【问题讨论】:

  • 给出第一个值而不是空值。在你的情况下,那是“A”或Assing“”
  • 这不是我需要的...我知道可以有空项目..它必须以这种方式工作,使用 DropdownButton 是可能的...空值没有问题,按下按钮时,它不能从项目中设置任何值。
  • 试试DropdownButton小部件
  • 使用 DropDownButton 它可以像写的那样工作.. 但它没有 DropDownButtonFormField 的某些功能
  • @Maroshb 你找到了 DropdownButtonFormField 的解决方案吗?

标签: forms flutter dropdownbutton


【解决方案1】:

您可以使用GlobalKey&lt;FormFieldState&gt;。


class SomeWidget extends StatelessWidget {
  final GlobalKey<FormFieldState> _key;

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

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

https://dartpad.dev/04247868fa2e86c5f417532486b48870

【讨论】:

    【解决方案2】:
    class SomeWidget extends StatelessWidget {
      final GlobalKey<FormFieldState> _key = GlobalKey<FormFieldState>();
    
      @override
      Widget build() {
        return DropdownButtonFormField(
          key: _key,
          //...
        )
      }
    
      reset() {
        _key.currentState.reset();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2020-02-06
      • 2022-08-17
      相关资源
      最近更新 更多