Flutter-DropdownButtonFormField实

2022-05-11  本文已影响0人  阿博聊编程
配图来自网络,如侵必删

在日常的开发当中,我们在做选择框的时候,会想做下拉选择框Flutter给我们提供了Material类型的下拉选择框,分享一下我了解到了关于DropdownButtonFormField的知识,并简单实现下来选择框

简单实现下拉选择框

这里是通过DropdownButtonFormField组件来实现下拉选择框的,代码如下:

DropdownButtonFormField<String>(
          isExpanded: true,
          decoration: const InputDecoration(
              border: OutlineInputBorder(), labelText: 'SEX'),
          // 设置默认值
          value: '男',
          // 选择回调
          onChanged: (String? newPosition) {
            setState(() {});
          },
          // 传入可选的数组
          items: SEX.map((String sex) {
            return DropdownMenuItem(value: sex, child: Text(sex));
          }).toList(),
        ),

效果图:


下拉选择框效果图

所有的Dart代码,可以复制到编译器上直接运行:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @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(widget.title),
      ),
      body: Container(
        padding: const EdgeInsets.only(top: 10, right: 10, left: 10),
        child: DropdownButtonFormField<String>(
          isExpanded: true,
          decoration: const InputDecoration(
              border: OutlineInputBorder(), labelText: 'SEX'),
          // 设置默认值
          value: '男',
          // 选择回调
          onChanged: (String? newPosition) {
            setState(() {});
          },
          // 传入可选的数组
          items: SEX.map((String sex) {
            return DropdownMenuItem(value: sex, child: Text(sex));
          }).toList(),
        ),
      ),
    );
  }
}

属性使用

选择回调,这个是非常重要的,要不然点击不会有效果的:

 onChanged: (String? newPosition) {
            setState(() {});
},

设置选择数据,我是定义了一个数组,在使用数组的时候:

items: SEX.map((String sex) {
    return DropdownMenuItem(value: sex, child: Text(sex));
}).toList(),

设置默认值:

value: '男',
上一篇 下一篇

猜你喜欢

热点阅读