如何使Flutter自定义下拉按钮? [英] How to make flutter custom drop down button?

查看:445
本文介绍了如何使Flutter自定义下拉按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要自定义 DropDownButton ,不会呈现 DropdownItem 的内容.相反,它应该在从DropDown选择项目之前和之后呈现我的自定义"布局/小部件. 用简单的话来说,我想自定义 DropDownButton ./p>

谢谢

解决方案

当下拉DropdownButton项目时,如何以不同的方式呈现它?

我通过DropdownMenuItem找到了解决方案.对于关闭状态和下拉状态,分别执行其build().您可以使用上下文来确定它是处于关闭状态还是处于下拉状态.例如,您可以检查祖先状态微件.

我使用的是这样的伪代码片段:

DropdownButton<String>(
    value: selectedItem.id,
    items: items.map((item) {
        return DropdownMenuItem<String>(
            value: item.id,
            child: Builder(builder: (BuildContext context) {
                final bool isDropDown = context.ancestorStateOfType(TypeMatcher<PageState>()) == null;

                if (isDropDown) {
                    return Text(item.name);
                } else {
                    return Text(item.name, style: TextStyle(color: Colors.red));
                }
            },)
        );
    }).toList(),
);

其中 items id-name 实例的列表,而 PageState 是我自己的有状态小部件的状态.

I want to Customise DropDownButton, so that it does not render the content of DropdownItem. Instead it should render my Custom layout/widget before and after selecting an item from DropDown. In simple Words, I want to customise my DropDownButton.

Thanks,

解决方案

How to render DropdownButton items differently when it is dropped down?

I found a solution through DropdownMenuItem. Its build() is executed separately for closed and dropped down state. You can use the context to find out if it is closed or dropped down state. e.g you can check for an ancestor stateful widget.

I use something like this dummy code fragment:

DropdownButton<String>(
    value: selectedItem.id,
    items: items.map((item) {
        return DropdownMenuItem<String>(
            value: item.id,
            child: Builder(builder: (BuildContext context) {
                final bool isDropDown = context.ancestorStateOfType(TypeMatcher<PageState>()) == null;

                if (isDropDown) {
                    return Text(item.name);
                } else {
                    return Text(item.name, style: TextStyle(color: Colors.red));
                }
            },)
        );
    }).toList(),
);

Where items is a list of id-name instances, and PageState is the state of my own stateful widget.

这篇关于如何使Flutter自定义下拉按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆