Flutter How to create a DropDownFormField after the previous DropDownFormField has data

Viewed 73

I'm new to Flutter. What I want to ask is when I have a DropDownFormField and have 3 values. How can when I select one of the 3 values I will display a new DropDownFormField with a dataSource associated with the previously selected value.

For example I have House, Hotel, Apartment => Select House => display new DropDownFormField has Room, Kitchen

Or Select Hotel => display new DropDownFormField has Single Room, Double Room

Are there any examples that I can refer to?

1 Answers

There are a few ways to do what you're asking, but let me restate your query using Flutter nomenclature which should help you find more info. (DDFF = DropDownFormField)

You have two widgets, and when the first widget changes state you want to show the other widget.

The simplest way to do this is to create a custom Stateful widget that will contain two DDFF (in a Column(), Row(), etc). A widget's state is the values in its variables. In the case of this custom widget, you want to know at least if a value was selected for the first DDFF and what that value is so you can change things about the second widget. So there is one state variable: String ddff1Value;

When you build() your widget you will decide based on the state what to show. You can change what is returned from your widget's build() function using if() or ternary operators. If ddff1Value==null (nothing has been selected yet), don't show the second DDFF.

You also want to know when your first DDFF widget selection has changed, and DDFF provides a callback called onChanged that will be called when it changes. When it changes you want to update (set) the state of your widget to store that change, then redraw your widget reflecting the change.

To set the state of a Stateful widget, you call setState(). In your first DDFF:

onChanged: (val) {
    setState(() {
      ddff1Value = val;
    }
}

When you call setState(), Flutter will automatically redraw your widget afterward. That's it.

  • Create your custom Stateful widget
  • In the build() method, decide what to draw based on state
  • Use onChanged() to get values when DDFF changes
  • Call setState() to update your widget's state and redraw
Related