DropDownButton

DropDownButton可以实现一个下拉框效果的按钮。

 int selectedValue = 1;
 
@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('title'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed this button many times'),
            Text('test2'),
            DropdownButton(
                value: selectedValue,
                items: const [
                  DropdownMenuItem(
                      child: Text('A'),
                      value: 1,
                  ),
                  DropdownMenuItem(
                      child: Text('B'),
                      value: 2,
                  ),
                  DropdownMenuItem(
                      child: Text('C'),
                      value: 3,
                  )
                ],
                onChanged: (newValue){
                  setState((){
                    selectedValue = newValue as int;
                  });
                }
            )
          ],
        ),
      ),
    );
  }

### 如何在 Flutter 中使用 `DropdownButton2` 示例 为了创建一个带有自定义样式的下拉菜单,在 Flutter 应用程序中可以采用 `dropdown_button2` 这一插件[^2]。 #### 导入依赖项 首先,需确保项目中的 pubspec.yaml 文件已添加了对 `dropdown_button2` 插件的支持。接着执行命令来安装新的依赖关系: ```yaml dependencies: flutter: sdk: flutter dropdown_button2: ^0.3.0 # 版本号可能有所不同,请查阅最新文档获取确切版本 ``` #### 创建 DropdownButton2 小部件 下面是一个简单的例子展示如何构建并配置 `DropdownButton2`: ```dart import 'package:flutter/material.dart'; import 'package:dropdown_button2/dropdown_button2.dart'; class CustomDropDown extends StatefulWidget { @override _CustomDropDownState createState() => _CustomDropDownState(); } class _CustomDropDownState extends State<CustomDropDown> { String? selectedValue; List<String> items = ['Item1', 'Item2', 'Item3']; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Dropdown Button Example')), body: Center( child: DropdownButtonFormField2( decoration: InputDecoration( isDense: true, contentPadding: EdgeInsets.zero, border: OutlineInputBorder(), ), hint: const Text('Select Item'), icon: Icon(Icons.arrow_drop_down), buttonHeight: 40, itemHeight: 40, onChanged: (value){ setState(() { selectedValue=value; }); }, onSaved: (newValue) {}, value: selectedValue, items: items.map((item) => DropdownMenuItem<String>( value: item, child: Text(item, style: TextStyle(fontSize: 14),), ) ).toList(), ), ), ); } } ``` 此代码片段展示了如何通过设置不同的属性来自定义外观以及行为方式,比如改变提示文字、图标样式等参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值