flutterflutter-form-builderflutter-dropdownbutton

Showing different forms based on dropdown selection in flutter


I'm creating a mobile application in which I want to use a dropdown to select a "note type" (to create a new note) and based on the selection from the dropdown I want to show a specific form for the selected note type (each note type should have their own mix of formfields, both dropdowns and text) in the section below the "note type dropdown menu".

Have yet not been able to find any example on how to achieve this and therefor giving this a try!:)

Update: The buildNoteTypeForm() functions are linked to each forms individual .dart file where each individual form will be built. This is giving me an error on onChanged: Printscreen of error

class _NoteState extends State<NoteWidget>
Map<String, Widget> noteTypeOptions = {
'First note type': buildFirstNoteTypeForm(),
'Second note type': buildSecondNoteTypeForm()
};
late String noteType;

@override
void InitState() {
noteType = noteTypeOptions.keys.first;
}

@override
Widget build(BuildContext context) {

Widget noteTypeMenu = buildNoteTypeMenu();

Widget noteTypeForm = buildNoteTypeForm();

return MaterialApp(
 theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
 home: Scaffold(
      body: ListView(children: [noteTypeMenu, noteTypeForm])),
  );
}

buildNoteTypeForm() {
//Get noteType from selected dropdown option and build selected form
}

buildNoteTypeMenu() {
 DropdownButton(
    items: noteTypeOptions
        .map((key, value) {
          return MapEntry(
              key,
              DropdownMenuItem(
                value: value,
                child: Text(key),
              ));
        })
        .values
        .toList(),
    value: noteType,
    onChanged: (noteType? selected) {
      if (selected != null) {
        setState(() {
          noteType = selected;
   });
  }
 });
}

Solution

  • If your forms has too much differences, then the most optimal way is to create different "FormPart" widgets. Note they are not specific widget types. You will create them yourself. I am just naming it like that.

    For simplicity you can declare
    Map<String, Widget> typeToForm = {'type1': Form1(), ...}
    where you associate types with FormPart widgets

    Dropdown items will be like

    Then you can declare like that in State class of your stateful widget:
    late String type;.

    Inside initState method you will give value to it like type = typeToForm.keys.first;

    Then inside build method you need to put that formPart widget in appropriate node of widget tree, like

    Column(
       children: <Widget>[
          ...,
          ...,
          typeToForm[type],
          ...,
      ],
    

    ),

    The last key element is inside onChanged like function of dropdown menu, which you are changing types. You will write here

    setState((){type = value;});