代码之家  ›  专栏  ›  技术社区  ›  Nifal Mohamed

DropdownButtonFormField在Flatter中提交表单后重置

  •  0
  • Nifal Mohamed  · 技术社区  · 3 年前

    如何在提交表单后将DropdownButtonFormField值重置为默认值或重置DropdownButtonFormField。

    1 回复  |  直到 3 年前
        1
  •  1
  •   tareq albeesh    3 年前

    您可以使用GlobalKey这样的工具:

       GlobalKey<FormFieldState> newKey =  GlobalKey<FormFieldState>();
    

    并将其分配给DropdownButtonFormField,如下所示:

       DropdownButtonFormField(
          key: newKey,
        )
      
    

    当你想重置它时,你可以调用:

       newKey.currentState.reset();
    
        2
  •  0
  •   Xavier Soh    3 年前

    我会把这个加到塔里克的回答中。要重置整个表单,可以使用 GlobalKey<Form> ,但要仅重置表单的元素,必须为每个元素分配一个 GlobalKey<FormFieldState> .

    试试这个代码

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      MyApp({Key? key}) : super(key: key);
      final _formKey = GlobalKey<FormState>();
      final _cityDropdownButtonKey = GlobalKey<FormFieldState>();
      List<String> cities = ["Paris", "New york", "Yaoundé"];
      String cityValue = "Paris";
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text("Reset DropDownButton Field"),
            ),
            body: Form(
              key: _formKey,
              child: Padding(
                padding: EdgeInsets.all(32.0),
                child: Column(
                  children: [
                    DropdownButtonFormField<String>(
                      key: _cityDropdownButtonKey,
                      value: cityValue,
                      items: cities
                          .map<DropdownMenuItem<String>>(
                            (e) => DropdownMenuItem(
                              value: e,
                              child: Text(e),
                            ),
                          )
                          .toList(),
                      onChanged: (String? newValue) {//Any code},
                    ),
                    TextFormField(),
                    ElevatedButton(
                      onPressed: () {
                        //Call this to reset the field
                        _cityDropdownButtonKey.currentState!.reset();
                      },
                      child: const Text('Reset the Button Only'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                       //call this to reset the form
                        _formKey.currentState!.reset();
                      },
                      child: const Text('Reset the whole form'),
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }
    
    

    如果要从另一页重置,请将GlobalKeys设置为静态。