探索 Flutter Picker:一个高效、灵活的下拉选择组件
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
class PickerExample extends StatefulWidget {
@override
_PickerExampleState createState() => _PickerExampleState();
}
class _PickerExampleState extends State<PickerExample> {
// 选择器的数据
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
List<String> colors = ['Red', 'Yellow', 'Purple'];
// 选择器当前选中的值
String selectedFruit;
String selectedColor;
// 选择器的显示与隐藏状态
bool isFruitPickerShown = false;
bool isColorPickerShown = false;
void showPicker(List<String> items, String currentValue, bool isShown, ValueChanged<String> onChanged) {
Picker(
adapter: PickerAdapter(pickerData: items),
selecteds: items.indexOf(currentValue),
onConfirm: (Picker picker, List<int> selecteds) {
onChanged(items[selecteds[0]]);
Navigator.of(context).pop(); // 关闭选择器
},
).showModal(context);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Picker Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Selected Fruit: $selectedFruit'),
SizedBox(height: 20.0),
Text('Selected Color: $selectedColor'),
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton(
child: Text('Select Fruit'),
onPressed: () {
showPicker(fruits, selectedFruit ?? fruits.first, isFruitPickerShown, (newValue) {
setState(() {
selectedFruit = newValue;
});
});
},
),
SizedBox(width: 20.0),
FlatButton(
child: Text('Select Color'),
onPressed: () {
showPicker(colors, selectedColor ?? colors.first, isColorPickerShown, (newValue) {
setState(() {
selectedColor = newValue;
});
});
},
),
],
),
],
),
),
);
}
}
这段代码使用了\`f
评论已关闭