【问题标题】:How to show a clear button in dropdown in flutter?如何在颤动的下拉菜单中显示一个清晰的按钮?
【发布时间】:2021-10-10 04:10:00
【问题描述】:

我想在选择项目时在下拉列表中添加一个清晰的图标。而且,点击清除按钮后,我想清除所选项目。我怎样才能做到这一点?

这不是How to clear the dropdown button in flutter的重复项

谢谢

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您可以使用DropdownButtonFormFieldsuffixIcon 装饰,并根据是否选择某些内容,使用setState 显示或不显示它。

    试试这个代码:

    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(),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2015-07-06
      • 2021-11-04
      • 2021-11-21
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多