问题背景 客户端日常开发和学习过程,下拉框是一个很常见的组件,本文主要介绍Flutter中实现下拉框的一个方案,基于DropdownButtonFORMField来进行实现。 问题分析 DropdownButtonFormF
客户端日常开发和学习过程,下拉框是一个很常见的组件,本文主要介绍Flutter中实现下拉框的一个方案,基于DropdownButtonFORMField来进行实现。
DropdownButtonFormField 是一个组合控件,将[DropdownButton]包装在[FormField]中,用法如下:
var _value='语文';@overrideWidget 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 { 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( 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(), )), ], )), ); }}
运行结果如下所示:
,本文主要介绍flutter中实现下拉框的一个方案,基于DropdownButtonFormField来进行实现,该方案实现起来较为简单,有兴趣的同学可以进一步深入研究。
来源地址:https://blog.csdn.net/weixin_39033300/article/details/130291685
--结束END--
本文标题: flutter实现下拉框功能——基于DropdownButtonFormField
本文链接: https://www.lsjlt.com/news/394864.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0