Flutter集合选择器插件collection_picker的使用

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

Flutter集合选择器插件collection_picker的使用

Overview

collection_picker 是一个包含高度自定义的选择列表视图和网格视图的Flutter插件,支持单选、多选和单选按钮类型。它会自动渲染选中的项,并且您可以轻松地自定义选中的项视图。

ListViewPicker

ListViewPicker

GridViewPicker

GridViewPicker

Getting Started

添加依赖

在您的 pubspec.yaml 文件中添加 collection_picker 依赖:

dependencies:
  collection_picker: "^version"

导入插件

在您的 Dart 代码中导入 collection_picker

import 'package:collection_picker/collection_picker.dart';

Usage

我们使用示例数据和模型数据来帮助您更好地理解如何使用 collection_picker

示例模型数据

class CityModel {
  String province;
  String city;

  CityModel(this.province, this.city);
}

示例数据列表

List<CityModel> dataCity = [
  CityModel('Jakarta', 'Menteng'),
  CityModel('Jakarta', 'Tebet'),
  CityModel('Jakarta', 'Gambir'),
  CityModel('Lampung', 'Bandar Lampung'),
  CityModel('Lampung', 'Pringsewu'),
  CityModel('Bandung', 'Setrasari'),
  CityModel('Bandung', 'Gedebage'),
  CityModel('Bandung', 'Cihanjuang'),
  CityModel('Yogyakarta', 'Bantul'),
  CityModel('Yogyakarta', 'Sleman'),
];

ListViewPicker

ListViewPicker<CityModel>(
  type: PickerType.single,
  shrinkWrap: true,
  physics: const NeverScrollableScrollPhysics(),
  separator: const Divider(thickness: 1, height: 16),
  initialValue: dataCity.first,
  data: dataCity,
  itemBuilder: (PickerWrapper<CityModel> item) {
    return SizedBox(
      height: 20,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text('${item.data?.city}'),
          (item.isSelected)
              ? const Icon(Icons.check)
              : const SizedBox.shrink()
        ],
      ),
    );
  },
  onChanged: (context, index, selectedItem, selectedListItem) {
    // 当类型为单选或单选按钮时,应使用此方法
    debugPrint('Selected item = ${selectedItem.city}');

    /// 当类型为多选时,应使用此方法
    debugPrint('All selected item = ${selectedListItem.map((e) => e?.city)}');
  },
)

GridViewPicker

实际上与 ListViewPicker 相同,但以网格形式显示。

GridViewPicker(
  type: PickerType.multiple,
  shrinkWrap: true,
  initialValue: dataCity.first,
  data: dataCity,
  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 200,
    mainAxisExtent: 50,
    crossAxisSpacing: 8,
  ),
  itemBuilder: (PickerWrapper<CityModel> item) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text('${item.data?.city}'),
          (item.isSelected)
              ? const Icon(Icons.check)
              : const SizedBox.shrink()
        ],
      ),
    );
  },
  onChanged: (context, index, selectedItem, selectedListItem) {
    // 当类型为单选或单选按钮时,应使用此方法
    debugPrint('Selected item = ${selectedItem?.city}');

    /// 当类型为多选时,应使用此方法
    debugPrint('All selected item = ${selectedListItem.map((e) => e?.city)}');
  },
)

示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 collection_picker 插件:

import 'package:collection_picker/collection_picker.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: CollectionPickerExample(),
    );
  }
}

class CollectionPickerExample extends StatelessWidget {
  const CollectionPickerExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Collection Picker Example'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            ListViewPicker<CityModel>(
              type: PickerType.single,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              separator: (BuildContext context, int index) =>
                  const Divider(thickness: 1, height: 16),
              initialValue: dataCity.first,
              data: dataCity,
              unavailableDataIndex: [3, 5],
              itemBuilder: (BuildContext context, int index,
                  PickerWrapper<CityModel> item) {
                return SizedBox(
                  height: 20,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(item.data.city),
                      (!item.isAvailable)
                          ? const Text('Unavailable')
                          : (item.isSelected)
                              ? const Icon(Icons.check)
                              : const SizedBox.shrink()
                    ],
                  ),
                );
              },
              onChanged: (context, index, selectedItem, selectedListItem) {
                // 当类型为单选或单选按钮时,应使用此方法
                debugPrint('Selected item = $selectedItem');

                /// 当类型为多选时,应使用此方法
                debugPrint('All selected item = $selectedListItem');
              },
            ),
            GridViewPicker(
              type: PickerType.multiple,
              shrinkWrap: true,
              initialValue: dataCity.first,
              data: dataCity,
              gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 200,
                mainAxisExtent: 50,
                crossAxisSpacing: 8,
              ),
              itemBuilder: (BuildContext context, int index,
                  PickerWrapper<CityModel> item) {
                return Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.grey.shade300),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(item.data.city),
                      if (item.isSelected) const Icon(Icons.check),
                    ],
                  ),
                );
              },
              onChanged: (context, index, selectedItem, selectedListItem) {
                // 当类型为单选或单选按钮时,应使用此方法
                debugPrint('Selected item = ${selectedItem?.city}');

                /// 当类型为多选时,应使用此方法
                debugPrint(
                    'All selected item = ${selectedListItem.map((e) => e.city)}');
              },
            ),
          ],
        ),
      ),
    );
  }
}

class CityModel {
  String province;
  String city;

  CityModel(this.province, this.city);
}

List<CityModel> dataCity = [
  CityModel('Jakarta', 'Menteng'),
  CityModel('Jakarta', 'Tebet'),
  CityModel('Jakarta', 'Gambir'),
  CityModel('Lampung', 'Bandar Lampung'),
  CityModel('Lampung', 'Pringsewu'),
  CityModel('Bandung', 'Setrasari'),
  CityModel('Bandung', 'Gedebage'),
  CityModel('Bandung', 'Cihanjuang'),
  CityModel('Yogyakarta', 'Bantul'),
  CityModel('Yogyakarta', 'Sleman'),
];

Additional Information

感谢使用 collection_picker 插件。希望这个插件能对您有所帮助。祝您编码愉快!


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

1 回复

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


当然,下面是一个关于如何在Flutter中使用collection_picker插件的示例代码。这个插件允许你以优雅的方式在集合中进行选择,通常用于选择单个或多个项目。

首先,你需要在你的pubspec.yaml文件中添加collection_picker依赖:

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

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

接下来是一个简单的例子,展示如何使用collection_picker来选择单个项目:

import 'package:flutter/material.dart';
import 'package:collection_picker/collection_picker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? selectedItem;

  final List<String> items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];

  void _onItemSelected(String item) {
    setState(() {
      selectedItem = item;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Collection Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              selectedItem ?? 'No item selected',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                showPicker(
                  context: context,
                  collection: items,
                  initialSelected: selectedItem,
                  onSelected: _onItemSelected,
                  builder: (context, options) {
                    return CollectionPicker(
                      options: options,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(items[index]),
                        );
                      },
                    );
                  },
                );
              },
              child: Text('Select Item'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个例子中,我们创建了一个包含四个字符串项目的列表。当用户点击按钮时,会显示一个选择器,允许用户从列表中选择一个项目。选择后,将更新UI以显示所选项目。

如果你需要选择多个项目,可以使用MultiSelectionPicker。以下是修改后的代码示例:

import 'package:flutter/material.dart';
import 'package:collection_picker/collection_picker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Set<String>? selectedItems;

  final List<String> items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];

  void _onItemsSelected(Set<String> items) {
    setState(() {
      selectedItems = items;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Multi Collection Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              selectedItems?.join(', ') ?? 'No items selected',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                showPicker(
                  context: context,
                  collection: items,
                  initialSelected: selectedItems?.toList() ?? [],
                  allowMultiSelect: true,
                  onSelected: _onItemsSelected,
                  builder: (context, options) {
                    return MultiSelectionPicker(
                      options: options,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(items[index]),
                        );
                      },
                    );
                  },
                );
              },
              child: Text('Select Items'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个多选例子中,我们使用MultiSelectionPicker来允许用户选择多个项目,并在选择后更新UI以显示所选项目的列表。

这两个例子展示了如何在Flutter中使用collection_picker插件进行单个和多个项目的选择。希望这些代码对你有帮助!

回到顶部