flutter实现下拉框功能——基于DropdownButtonFormField

问题背景

客户端日常开发和学习过程,下拉框是一个很常见的组件,本文主要介绍flutter中实现下拉框的一个方案,基于DropdownButtonFormField来进行实现。

问题分析

DropdownButtonFormField 是一个组合控件,将[DropdownButton]包装在[FormField]中,用法如下:

var _value='语文';

@override
Widget build(BuildContext context) {
  return DropdownButtonFormField(
    value: _value,
    items: [
      DropdownMenuItem(
        child: Text('语文'),
        value: '语文',
      ),
      DropdownMenuItem(child: Text('数学'), value: '数学'),
      DropdownMenuItem(child: Text('英语'), value: '英语'),
    ],
    onChanged: (String value){
      setState(() {
        _value = value;
      });
    },
  );
}

问题解决

话不多说,直接上代码,实现下拉框的完整代码如下:

import 'package:flutter/material.dart';

class Test extends StatefulWidget {
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  String currentSex = '男';
  @override
  Widget build(BuildContext context) {
    const SEX = ['男', '女', '保密'];
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("下拉框测试"),
      ),
      body: Container(
        padding: const EdgeInsets.only(top: 10, right: 20, left: 20),
        child: Row (
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text("性别"),
            SizedBox(
                width:60.0,
                height: 30.0,
                child: DropdownButtonFormField<String>(
            isExpanded: true,
            iconSize: 20,
            style: TextStyle(fontSize:15, color: Colors.black),
            decoration: const InputDecoration(
                contentPadding: EdgeInsets.only(left: 5, right: 5),
                border: OutlineInputBorder(gapPadding: 1), labelText: ''),
            // 设置默认值
            value: currentSex,
            // 选择回调
            onChanged: (String? newPosition) {
              setState(() {
                currentSex = newPosition!;
                print("currentSex: " + currentSex);
              });
            },
            // 传入可选的数组
            items: SEX.map((String sex) {
              return DropdownMenuItem(value: sex, child: Text(sex));
            }).toList(),
          )),
      ],
        )),
    );
  }
}

运行结果如下所示: 1681180615596.gif

问题总结

,本文主要介绍flutter中实现下拉框的一个方案,基于DropdownButtonFormField来进行实现,该方案实现起来较为简单,有兴趣的同学可以进一步深入研究。

猜你喜欢

转载自blog.csdn.net/weixin_39033300/article/details/130291685