在这篇文章中,我们将学习如何使用 DropDownButton,并探索它在 Flutter 中的各种属性。我们将使用 Flutter DropDownButton 组件在我们的应用程序中显示一个下拉列表。那么,首先让我们来看看什么是 DropDownButton。
Flutter 中的 DropDownButton 组件
在 Flutter 中,DropDownButton 是一个符合 Material Design 设计规范的下拉按钮。DropDownButton 是一个组件,我们可以用它来从一组值中选择一个唯一的值。它让用户从多个项目中选中一个值。默认情况下,它显示当前选中的值。我们甚至可以在列表中包含一个向下箭头的图标。点击 DropDownButton 时,它会打开一个项目列表,用户可以从中选择所需的选项。
DropDownButton 的构造函数
DropdownButton DropdownButton({
Key? key,
required List<DropdownMenuItem>? items,
List Function(BuildContext)? selectedItemBuilder,
String? value,
Widget? hint,
Widget? disabledHint,
required void Function(String?)? onChanged,
void Function()? onTap,
int elevation = 8,
TextStyle? style,
Widget? underline,
Widget? icon,
Color? iconDisabledColor,
Color? iconEnabledColor,
double iconSize = 24.0,
bool isDense = false,
bool isExpanded = false,
double? itemHeight = kMinInteractiveDimension,
double? menuWidth,
Color? focusColor,
FocusNode? focusNode,
bool autofocus = false,
Color? dropdownColor,
double? menuMaxHeight,
bool? enableFeedback,
AlignmentGeometry alignment = AlignmentDirectional.centerStart,
BorderRadius? borderRadius,
EdgeInsetsGeometry? padding,
})
DropDownButton 的属性:
描述
—
我们使用此属性来定义下拉菜单/列表中要定义的各种项目。它是用户可以选择的项目列表。
Value 代表当前选中的项目。
我们使用 style 属性来设置下拉菜单/列表中文本的样式,例如颜色、字体大小、字体粗细等。
Alignment 定义了提示或选中项目如何在按钮内定位。
我们使用 elevation 属性来提升下拉菜单/列表的高度(即阴影效果)。
此属性用于在下拉按钮上显示一个图标。
此属性用于定义图标的大小。
此属性用于设置当下拉按钮被禁用时的图标颜色。
此属性用于设置当下拉按钮启用时的图标颜色。
此属性用于设置下拉菜单的背景颜色。
此属性用于减小按钮的高度。
此属性用于将下拉按钮扩展为全宽。
当用户从下拉列表中选择一个选项时,它会在按钮上显示该选项。如果我们想在按钮上显示除所选选项之外的其他文本,我们将使用 selectedItemBuilder。
我们可以在按钮上显示下拉列表中的某个选项,或者可以使用 hint 默认设置我们想要的文本。
此属性用于在下拉按钮被禁用时显示所需的文本。### Flutter DropDownButton 代码示例:
main.dart:
main.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 DropDownButton‘,
theme: ThemeData(primarySwatch: Colors.green),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
// Initial Selected Value
String dropdownvalue = ‘Item 1‘;
// List of items in our dropdown menu
var items = [
‘Item 1‘,
‘Item 2‘,
‘Item 3‘,
‘Item 4‘,
‘Item 5‘
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("示例 DropDownButton"),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
body: Center(
child: DropdownButton(
// Initial Value
value: dropdownvalue,
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),
// Array list of items
items:
items.map((String items) {
return DropdownMenuItem(value: items, child: Text(items));
}).toList(),
// After selecting the desired option,it will
// change