📊 选择器组件详解
Flutter 提供了多种选择器组件,用于日期、时间、颜色、文件等选择的场景。
📅 DatePicker
DatePicker 是日期选择器,用于选择日期。
渲染预览
基本用法
ElevatedButton(
onPressed: () async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
locale: Locale('zh', 'CN'),
helpText: '选择日期',
cancelText: '取消',
confirmText: '确定',
);
if (picked != null) {
print('选择的日期: $picked');
}
},
child: Text('选择日期'),
)
常用属性
| 属性 | 类型 | 说明 |
|---|---|---|
| initialDate | DateTime | 初始日期 |
| firstDate | DateTime | 最早可选日期 |
| lastDate | DateTime | 最晚可选日期 |
| locale | Locale | 本地化 |
| helpText | String | 帮助文本 |
💡 提示:需要引入 flutter_localizations 包以支持中文。
⏰ TimePicker
TimePicker 是时间选择器,用于选择时间。
渲染预览
基本用法
ElevatedButton(
onPressed: () async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
helpText: '选择时间',
cancelText: '取消',
confirmText: '确定',
);
if (picked != null) {
print('选择的时间: ${picked.format(context)}');
}
},
child: Text('选择时间'),
)
常用属性
| 属性 | 类型 | 说明 |
|---|---|---|
| initialTime | TimeOfDay | 初始时间 |
| builder | WidgetBuilder | 自定义构建器 |
| helpText | String | 帮助文本 |
| cancelText | String | 取消文本 |
| confirmText | String | 确认文本 |
💡 提示:TimeOfDay 提供了 format() 方法来格式化时间显示。
🎨 ColorPicker
ColorPicker 是颜色选择器,用于选择颜色。Flutter 没有内置的颜色选择器,需要使用第三方包。
渲染预览
使用 flutter_colorpicker 包
// 1. 添加依赖
// dependencies:
// flutter_colorpicker: ^1.0.3
// 2. 使用示例
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
Color _currentColor = Colors.blue;
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('选择颜色'),
content: SingleChildScrollView(
child: ColorPicker(
pickerColor: _currentColor,
onColorChanged: (color) {
setState(() {
_currentColor = color;
});
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('确定'),
),
],
),
);
},
child: Text('选择颜色'),
)
💡 提示:flutter_colorpicker 是一个流行的颜色选择器包,提供了丰富的颜色选择功能。
📁 FilePicker
FilePicker 是文件选择器,用于选择文件。需要使用 file_picker 第三方包。
渲染预览
使用 file_picker 包
// 1. 添加依赖
// dependencies:
// file_picker: ^6.0.0
// 2. 使用示例
import 'package:file_picker/file_picker.dart';
ElevatedButton(
onPressed: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'pdf'],
);
if (result != null) {
PlatformFile file = result.files.first;
print('文件名: ${file.name}');
print('文件大小: ${file.size}');
print('文件路径: ${file.path}');
}
},
child: Text('选择文件'),
)
// 选择多个文件
ElevatedButton(
onPressed: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
allowMultiple: true,
);
if (result != null) {
print('选择了 ${result.files.length} 个文件');
}
},
child: Text('选择多个文件'),
)
常用方法
- pickFiles():选择文件
- pickDirectory():选择目录
- clearTemporaryFiles():清除临时文件
💡 提示:file_picker 支持选择单个或多个文件,可以限制文件类型。