flutter_picker 两列的数组方式怎么写
时间: 2023-07-15 07:11:43 浏览: 153
可以使用 `Picker()` 组件,设置 `PickerDataAdapter()` 适配器,示例代码如下:
```dart
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Picker Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Picker Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedFirstIndex = 0;
int _selectedSecondIndex = 0;
List<String> _firstList = [
'Option 1',
'Option 2',
'Option 3',
'Option 4',
'Option 5'
];
List<String> _secondList = [
'Suboption 1',
'Suboption 2',
'Suboption 3',
'Suboption 4',
'Suboption 5'
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: RaisedButton(
onPressed: () {
showPicker();
},
child: Text('Show Picker'),
),
),
);
}
void showPicker() {
Picker(
adapter: PickerDataAdapter<String>(
pickerdata: [
PickerDataItem(
text: _firstList[_selectedFirstIndex],
children: _secondList.map((e) => PickerDataItem(text: e)).toList())
],
),
onConfirm: (Picker picker, List value) {
setState(() {
_selectedFirstIndex = value[0];
_selectedSecondIndex = value[1];
});
},
selecteds: [_selectedFirstIndex, _selectedSecondIndex],
itemExtent: 50,
height: 200,
cancelText: 'Cancel',
confirmText: 'Confirm')
..showModal(context);
}
}
```
在适配器中,我们可以通过 `PickerDataItem()` 来设置每一列的数据,使用 `children` 参数来设置第二列的数据。在 `selecteds` 参数中,我们可以指定每一列的默认选中项。在 `onConfirm` 回调中,我们可以获取到选中的项,并更新 `_selectedFirstIndex` 和 `_selectedSecondIndex` 状态。
阅读全文