clear DropDownButton flutter

Issue

i have a DropDownButton which add category for my product. after added product DropDownButton display category which i choosed. I want to refresh or clear DropDownButton after adding product. Better to display hint text.

code:

 child: StreamBuilder<List<Categories>>(
                              stream: categories,
                              builder: ((context, snapshot) {
                                if (!snapshot.hasData)
                                  return CircularProgressIndicator();
                                return DropdownButton(
                                  hint: Text('choose category'),
                                  value: _currentCategory,
                                  items: snapshot.data
                                      .map((doc) => DropdownMenuItem(
                                            child: Text(doc.categoryname),
                                            value: doc,
                                          ))
                                      .toList(),
                                  onChanged: (selectedCategory) =>
                                      setState(() {
                                    _currentCategory = selectedCategory;
                                  }),
                                );
                              })),
                        ),
                        SizedBox(height: 15),
                        RaisedButton(
                          onPressed: () {
                            if (_formKeyProduct.currentState.validate()) {
                              ProductService().addProduct(
                                  _nameproductController.text,
                                  _priceproductController.text,
                                  _currentCategory.categoryname.toString());
                              _formKeyProduct.currentState.reset();
                              _nameproductController.clear();
                              _priceproductController.clear();
                            }
                          },
                          child: Text('add product'),

Solution

Since the value you chose is _currentCategory using

setState(() {
    _currentCategory = null;
  }
)

should do the trick.

EDIT:

I see some downvotes on this. This answer was based on Flutter 1.22.6. If it doesn’t work on Flutter 2 that is why.

Answered By – Stijn2210

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.