Flutter选择器插件flutter_picker的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter选择器插件flutter_picker的使用

flutter_picker

pub package GitHub GitHub stars

flutter_picker 是一个Flutter插件,包含数字选择器(NumberPicker)、日期时间选择器(DateTimePicker)、数组选择器(ArrayPicker)以及默认的联动选择器(linkage Picker)。它提供了灵活的参数以满足各种需求。同时,你可以通过自定义适配器来扩展更多功能。

支持平台

  • Android
  • iOS
  • Windows
  • macOS
  • Linux
  • Web

image

如何使用

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_picker:
    git: git://github.com/yangyxd/flutter_picker.git

2. 导入库

在 Dart 文件中导入 flutter_picker 库:

import 'package:flutter_picker/flutter_picker.dart';

3. 使用示例

3.1 基础使用

void showPicker(BuildContext context) {
  Picker picker = new Picker(
    adapter: PickerDataAdapter<String>(pickerdata: new JsonDecoder().convert(PickerData)),
    changeToFirst: true,
    textAlign: TextAlign.left,
    columnPadding: const EdgeInsets.all(8.0),
    onConfirm: (Picker picker, List value) {
      print(value.toString());
      print(picker.getSelectedValues());
    }
  );
  picker.show(_scaffoldKey.currentState);
}

3.2 模态框使用

void showPickerModal(BuildContext context) {
  new Picker(
    adapter: PickerDataAdapter<String>(pickerdata: new JsonDecoder().convert(PickerData)),
    changeToFirst: true,
    hideHeader: false,
    onConfirm: (Picker picker, List value) {
      print(value.toString());
      print(picker.adapter.text);
    }
  ).showModal(this.context);
}

3.3 图标选择器

void showPickerIcons(BuildContext context) {
  new Picker(
    adapter: PickerDataAdapter(data: [
      new PickerItem(text: Icon(Icons.add), value: Icons.add, children: [
        new PickerItem(text: Icon(Icons.more)),
        new PickerItem(text: Icon(Icons.aspect_ratio)),
        new PickerItem(text: Icon(Icons.android)),
        new PickerItem(text: Icon(Icons.menu)),
      ]),
      new PickerItem(text: Icon(Icons.title), value: Icons.title, children: [
        new PickerItem(text: Icon(Icons.more_vert)),
        new PickerItem(text: Icon(Icons.ac_unit)),
        new PickerItem(text: Icon(Icons.access_alarm)),
        new PickerItem(text: Icon(Icons.account_balance)),
      ]),
      // 其他图标项...
    ]),
    title: new Text("Select Icon"),
    onConfirm: (Picker picker, List value) {
      print(value.toString());
      print(picker.getSelectedValues());
    }
  ).show(_scaffoldKey.currentState);
}

3.4 数字选择器

void showPickerNumber(BuildContext context) {
  new Picker(
    adapter: NumberPickerAdapter(data: [
      NumberPickerColumn(begin: 0, end: 999),
      NumberPickerColumn(begin: 100, end: 200),
    ]),
    delimiter: [
      PickerDelimiter(child: Container(
        width: 30.0,
        alignment: Alignment.center,
        child: Icon(Icons.more_vert),
      ))
    ],
    hideHeader: true,
    title: new Text("Please Select"),
    onConfirm: (Picker picker, List value) {
      print(value.toString());
      print(picker.getSelectedValues());
    }
  ).showDialog(context);
}

3.5 日期选择器

void showPickerDate(BuildContext context) {
  Picker(
    hideHeader: true,
    adapter: DateTimePickerAdapter(),
    title: Text("Select Data"),
    selectedTextStyle: TextStyle(color: Colors.blue),
    onConfirm: (Picker picker, List value) {
      print((picker.adapter as DateTimePickerAdapter).value);
    }
  ).showDialog(context);
}

3.6 日期时间选择器

void showPickerDateTime(BuildContext context) {
  Picker(
    adapter: DateTimePickerAdapter(
      type: PickerDateTimeType.kMDYHM_AP,
      isNumberMonth: true,
      yearSuffix: "年",
      monthSuffix: "月",
      daySuffix: "日",
      hourSuffix: "時",
      minuteSuffix: "分",
      secondSuffix: "秒",
      minValue: DateTime.now(),
      minuteInterval: 30,
    ),
    title: Text("Select DateTime"),
    textAlign: TextAlign.right,
    selectedTextStyle: TextStyle(color: Colors.blue),
    delimiter: [
      PickerDelimiter(
          column: 5,
          child: Container(
            width: 16.0,
            alignment: Alignment.center,
            child: Text(':', style: TextStyle(fontWeight: FontWeight.bold)),
            color: Colors.white,
          ))
    ],
    footer: Container(
      height: 50.0,
      alignment: Alignment.center,
      child: Text('Footer'),
    ),
    onConfirm: (Picker picker, List value) {
      print(picker.adapter.text);
    },
    onSelect: (Picker picker, int index, List selected) {
      setState(() {
        stateText = picker.adapter.toString();
      });
    }
  ).showBottomSheet(context);
}

PickerData 示例

数组

const PickerData2 = '''
[
    [
        1,
        2,
        3,
        4
    ],
    [
        11,
        22,
        33,
        44
    ],
    [
        "aaa",
        "bbb",
        "ccc"
    ]
]
''';

联动

const PickerData = '''
[
    {
        "a": [
            {
                "a1": [
                    1,
                    2,
                    3,
                    4
                ]
            },
            {
                "a2": [
                    5,
                    6,
                    7,
                    8
                ]
            },
            {
                "a3": [
                    9,
                    10,
                    11,
                    12
                ]
            }
        ]
    },
    {
        "b": [
            {
                "b1": [
                    11,
                    22,
                    33,
                    44
                ]
            },
            {
                "b2": [
                    55,
                    66,
                    77,
                    88
                ]
            },
            {
                "b3": [
                    99,
                    1010,
                    1111,
                    1212
                ]
            }
        ]
    },
    {
        "c": [
            {
                "c1": [
                    "a",
                    "b",
                    "c"
                ]
            },
            {
                "c2": [
                    "aa",
                    "bb",
                    "cc"
                ]
            },
            {
                "c3": [
                    "aaa",
                    "bbb",
                    "ccc"
                ]
            }
        ]
    }
]
''';

更多关于Flutter选择器插件flutter_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter选择器插件flutter_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用flutter_picker插件的示例代码。这个插件通常用于在Flutter应用中实现选择器功能,比如日期选择器、时间选择器、多列选择器等。

首先,确保你已经在pubspec.yaml文件中添加了flutter_picker依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_picker: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

接下来是一个完整的示例代码,展示了如何使用flutter_picker插件:

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 Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PickerExample(),
    );
  }
}

class PickerExample extends StatefulWidget {
  @override
  _PickerExampleState createState() => _PickerExampleState();
}

class _PickerExampleState extends State<PickerExample> {
  List<Picker> _pickerData = [];
  Picker _picker;
  List<Object> _pickerResult = [];

  @override
  void initState() {
    super.initState();

    // 初始化Picker数据
    _pickerData = [
      Picker.create({
        "columns": [
          {"values": ["Option 1", "Option 2", "Option 3"]},
          {"values": ["A", "B", "C", "D"]},
          {"values": [1, 2, 3, 4, 5]}
        ],
        "mode": "multiSelector", // 多列选择器模式
        "title": "Multi Selector",
      }),
      Picker.create({
        "columns": [
          {"values": ["2023", "2024", "2025"]},
          {"values": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]},
          {"values": List.generate(31, (index) => index + 1)},
        ],
        "mode": "cascade", // 级联选择器模式
        "title": "Date Picker",
        "cascade": true,
        "toolbarHeight": 110,
        "onConfirm": (Picker picker, List<Object> values) {
          // 选择器确认回调
          setState(() {
            _pickerResult = values;
          });
        },
      }),
    ];

    // 初始化Picker实例
    _picker = Picker(
      adapter: PickerDataAdapter(_pickerData),
      onConfirm: (Picker picker, List<Object> values) {
        // 处理选择结果
        setState(() {
          _pickerResult = values;
        });
      },
      onCancel: () {
        // 取消选择回调
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Picker Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Selected Values:', style: TextStyle(fontSize: 18)),
            SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: List.generate(_pickerResult.length, (index) {
                return Chip(
                  label: Text(_pickerResult[index].toString()),
                );
              }),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: () {
                _picker.showDialog(context);
              },
              child: Text('Show Picker'),
            ),
          ],
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖导入:在pubspec.yaml文件中添加flutter_picker依赖。

  2. Picker数据初始化:在initState方法中,我们创建了两个Picker,一个是多列选择器(multiSelector),另一个是级联选择器(cascade)用于日期选择。

  3. Picker实例:我们创建了一个Picker实例,并设置了adapteronConfirmonCancel回调。

  4. UI展示:在UI中,我们展示了一个按钮来触发Picker对话框,以及一个区域来显示用户选择的结果。

运行这个示例应用,点击“Show Picker”按钮后,会弹出一个选择器对话框,用户可以选择数据并确认或取消。选择的结果会显示在UI上。

希望这个示例对你有帮助!如果有其他问题,请随时询问。

回到顶部