首页 > 建站教程 > APP开发,混合APP >  Flutter笔记9:DropdownButton下拉框组件正文

Flutter笔记9:DropdownButton下拉框组件

Flutter的DropdownButton下拉框组件和html的select下拉选择框非常类似,使用也非常简单,属性不多,代码如下:
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'DropdownButton',
        home: Scaffold(
          appBar: AppBar(
            title: Text('DropdownButton'),
          ),
          body: DropdownButtonDemo(),
        ));
  }
}

class DropdownButtonDemo extends StatefulWidget {
  DropdownButtonDemo({Key key}) : super(key: key);

  @override
  _DropdownButtonDemoState createState() => _DropdownButtonDemoState();
}

class _DropdownButtonDemoState extends State<DropdownButtonDemo> {
  var selectItemValue = '北京';
  List<DropdownMenuItem> generateItemList() {
    final List<DropdownMenuItem> items = new List();
    final DropdownMenuItem item1 = DropdownMenuItem(
      child: Text('北京'),
      value: '北京',
    );
    final DropdownMenuItem item2 = DropdownMenuItem(
      child: Text('上海'),
      value: '上海',
    );
    final DropdownMenuItem item3 = DropdownMenuItem(
      child: Text('广州'),
      value: '广州',
    );
    final DropdownMenuItem item4 = DropdownMenuItem(
      child: Text('深圳'),
      value: '深圳',
    );
    items.addAll([item1, item2, item3, item4]);
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      //提示文本
      hint: Text('请选择一个城市'),
      //下拉列表项
      items: generateItemList(),
      //默认值
      value: selectItemValue,
      //下拉三角大小
      iconSize: 48.0,
      //阴影大小
      elevation: 1,
      //是否和父容器宽度保持一致(默认false,占一般左右),通常用这个设置宽度
      isExpanded: true,
      //下拉文本样式
      style: TextStyle(color: Colors.green),
      //下拉改变事件
      onChanged: (value) {
        setState(() {
          this.selectItemValue = value;
        });
      },
    );
  }
}