0

I want to add a clear icon in dropdown when an item is selected. And, upon tapping the clear button I want to clear the selected item. How can I achieve this?

This is not a duplicate of How to clear the dropdown button in flutter

Thank you

Anoop Thiruonam
  • 2,567
  • 2
  • 28
  • 48

1 Answers1

1

You can use a DropdownButtonFormField with suffixIcon decoration, and depending on whether something is selected or not, you display it or not using setState.

Try this code:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Padding(
            padding: EdgeInsets.all(16.0),
            child: MyDropDownButton(),
          ),
        ),
      ),
    );
  }
}

class MyDropDownButton extends StatefulWidget {
  const MyDropDownButton({Key? key}) : super(key: key);

  @override
  State<MyDropDownButton> createState() => _MyDropDownButtonState();
}

class _MyDropDownButtonState extends State<MyDropDownButton> {
  String? _value;

  @override
  Widget build(BuildContext context) {
    return DropdownButtonFormField<String>(
      value: _value,
      decoration: InputDecoration(
        hintText: 'select...',
        suffixIcon: _value == null
            ? null
            : IconButton(
                icon: const Icon(Icons.clear),
                onPressed: () => setState(() {
                      _value = null;
                    })),
      ),
      onChanged: (newValue) => setState(() {
        _value = newValue;
      }),
      items: <String>['first', 'second', 'third']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}
Peter Koltai
  • 8,296
  • 2
  • 10
  • 20