flutter 选择器
时间: 2023-09-06 15:12:52 浏览: 133
flutter_pickers:flutter选择器库,包括日期和时间选择器(可设置范围),单项选择器(可用于性别,民族,学历,星座,年龄,身高,体重,温度等),城市地址选择器(分省)级,地级及县级),多个选择器等……欢迎Fork&pr贡献您的代码,大家共同学习
5星 · 资源好评率100%
Flutter中的选择器有多种实现方式,以下是其中两种常见的实现方式:
1. CupertinoPicker
CupertinoPicker是一个iOS风格的选择器,可以在Flutter中使用。使用CupertinoPicker需要引入cupertino库,示例代码如下:
```
import 'package:flutter/cupertino.dart';
class MyPicker extends StatefulWidget {
@override
_MyPickerState createState() => _MyPickerState();
}
class _MyPickerState extends State<MyPicker> {
List<String> items = ['item1', 'item2', 'item3'];
int currentIndex = 0;
@override
Widget build(BuildContext context) {
return CupertinoPicker(
itemExtent: 30,
onSelectedItemChanged: (index) {
setState(() {
currentIndex = index;
});
},
children: items.map((item) => Text(item)).toList(),
scrollController: FixedExtentScrollController(initialItem: currentIndex),
);
}
}
```
2. DropdownButton
DropdownButton是一个下拉菜单,也可以用作选择器。示例代码如下:
```
import 'package:flutter/material.dart';
class MyDropdownButton extends StatefulWidget {
@override
_MyDropdownButtonState createState() => _MyDropdownButtonState();
}
class _MyDropdownButtonState extends State<MyDropdownButton> {
List<String> items = ['item1', 'item2', 'item3'];
String currentItem = 'item1';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: currentItem,
onChanged: (value) {
setState(() {
currentItem = value;
});
},
items: items.map((item) {
return DropdownMenuItem<String>(
value: item,
child: Text(item),
);
}).toList(),
);
}
}
```
阅读全文