何自定义DropdownButtons和DropdownMenu

何自定义DropdownButtons和DropdownMenu

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

问题描述

带有 DropdownMenuItems 的默认

class TestPage 扩展 StatelessWidget {@覆盖小部件构建(BuildContext 上下文){返回新的脚手架(应用程序栏:新的应用程序栏(标题:新文本(测试"),),身体:新中心(孩子:新的DropdownButton(项目:新的List.generate(20,(int index){return new DropdownMenuItem(child: new Container(孩子:新文本(Item#$index"),宽度:200.0,//200.0 到 100.0));}), onChanged: null)),);}}

The default DropdownButton with DropdownMenuItems returns a light-grey dropdown. How should I customize the dropdown (e.g. background color, dropdown width)? I can change the style property in both DropdownButton and DropdownMenuItem, like this:

return new DropdownButton(
      value: ...,
      items: ...,
      onChanged: ...,
      style: new TextStyle(
        color: Colors.white,
      ),
    );

but this doesn't change the dropdown's background color.

Should I copy DropdownMenu and extend it? Does Flutter plan to add customization for this widget in the near future?

解决方案

As Collin said, your DropdownMenuItem will follow your ThemeData class. Not only its backgroundColor will match the canvasColor in your ThemeData class, but also it will follow the same TextStyle.

So, for a quick example:

new ThemeData(
        fontFamily: "Encode Sans", //my custom font
        canvasColor: _turquoise, //my custom color
//other theme data)

Furthermore, if you want to control the width of the menu, you can feed its child property a new Container and add the desired width, check the following GIF, I started with width: 100.0 then hot reloaded after changing it to 200.0, notice how the width was manipulated, just make sure you use a suitable width so that you do not get overflow problems later on when you use the menu within a more complex layout.

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title:new Text ("Test"),
      ),
      body: new Center(
        child: new DropdownButton(items: new List.generate(20, (int index){
          return new DropdownMenuItem(child: new Container(
            child: new Text ("Item#$index"),
            width: 200.0, //200.0 to 100.0
          ));
        })
            , onChanged: null)
      ),
    );
  }
}

这篇关于Flutter中如何自定义DropdownButtons和DropdownMenuItems?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:11