Flutter多选搜索插件multi_select_search的使用

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

Flutter多选搜索插件multi_select_search的使用

Multiselect Search

Easily buildable and customizable multi select widget with search field that can be used anywhere from container to dialog.

ss3 ss2 ss1

Features

  • Can be used in any Flutter widget. Wrap it in Container, dialog, bottom modal sheet etc.
  • User can search from your list of items.
  • Selected item chips list, search field, selectable item list are all visible in one.
  • List items are not hard-coded. You make your own list item widgets.
  • onChanged method returns a list of selected items every time user selects/unselects an item.

Getting Started

To start using the package, add the dependencies in your pubspec.yaml and import.

dependencies:
  multi_select_search: ^1.0.0
import 'package:multi_select_search/multi_select_search.dart';

Usage

Step 1: Create a List of Items

First, you need a list of items from the same class. Your class model MUST have fromJson & toJson methods.

var list = [
  Contact(1, "Joel McHale"),
  Contact(2, "Danny Pudi"),
  Contact(3, "Donald Glover"),
  Contact(4, "Gillian Jacobs"),
  Contact(5, "Alison Brie"),
  Contact(6, "Chevy Chase"),
  Contact(7, "Jim Rush"),
  Contact(8, "Yvette Nicole Brown"),
  Contact(9, "Jeff Winger"),
  Contact(10, "Abed Nadir"),
  Contact(11, "Troy Barnes"),
  Contact(12, "Britta Perry"),
  Contact(13, "Annie Edison"),
];

class Contact {
  final int id;
  final String name;

  Contact(this.id, this.name);

  Contact.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        name = json['name'];

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
    };
  }
}

Step 2: Use the MultiSelectSearch Widget

Now you are ready to use the MultiSelectSearch widget.

Parameters

  • itemBuilder: Build your own list item widgets to select from.
  • chipLabelKey: A field name of your class that should be displayed in selected item chip. In this example, we’re displaying Contact’s name field value in chip when selected. So it’s 'name'.
  • items: The list you created in step 1. Both items and itemBuilder must use the same list.
  • initialValue: Some of your list items to be selected beforehand.
  • onChanged: Returns the selected item list every time a user selects/unselects an item.
  • clearAll: A widget to clear all selected items when clicked. Do not use button widgets.
MultiSelectSearch<Contact>(
  itemBuilder: (Contact item) => ListTile(
    key: ObjectKey(item),
    leading: const Icon(Icons.person),
    title: Text(item.name),
  ),
  chipLabelKey: 'name',
  items: list,
  initialValue: initial,
  onChanged: (List<Contact> items) => setState(() => selectedItems = items),
  decoration: BoxDecoration(
    color: const Color(0xFFF7A072).withOpacity(0.6),
    border: const Border(
      bottom: BorderSide(color: Colors.grey),
    ),
  ),
  clearAll: const Padding(
    padding: EdgeInsets.only(top: 10.0, right: 6.0),
    child: Icon(Icons.clear),
  ),
),

Step 3: Customize Styles

  • maxHeight: Search field & selected items container’s maximum height when it’s expanded.
  • decoration: Search field & selected items container decoration.
  • padding: Search field & selected items container padding.
  • searchFieldDecoration: InputDecoration to change search field’s style, hint text, and more.
  • Selected item chip gets its style from the theme. In order to customize it, change chipThemeData in your AppTheme.
theme: ThemeData(
  primarySwatch: Colors.teal,
  chipTheme: const ChipThemeData(
    deleteIconColor: Color.fromARGB(255, 61, 61, 61),
    backgroundColor: Color(0xFFF9F7F3),
  ),
),

Additional Information

Feel free to create issues for any bugs or requests.

示例代码

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Multiselect Search',
      theme: ThemeData(
        primarySwatch: Colors.teal,
        chipTheme: const ChipThemeData(
          deleteIconColor: Color.fromARGB(255, 61, 61, 61),
          backgroundColor: Color(0xFFF9F7F3),
        ),
      ),
      home: const MyExampleApp(),
    );
  }
}

class MyExampleApp extends StatefulWidget {
  const MyExampleApp({Key? key}) : super(key: key);

  @override
  State<MyExampleApp> createState() => _MyExampleAppState();
}

class _MyExampleAppState extends State<MyExampleApp> {
  List<Contact> selectedItems = [];

  @override
  Widget build(BuildContext context) {
    var list = [
      Contact(1, "Joel McHale"),
      Contact(2, "Danny Pudi"),
      Contact(3, "Donald Glover"),
      Contact(4, "Gillian Jacobs"),
      Contact(5, "Alison Brie"),
      Contact(6, "Chevy Chase"),
      Contact(7, "Jim Rush"),
      Contact(8, "Yvette Nicole Brown"),
      Contact(9, "Jeff Winger"),
      Contact(10, "Abed Nadir"),
      Contact(11, "Troy Barnes"),
      Contact(12, "Britta Perry"),
      Contact(13, "Annie Edison"),
    ];

    List<Contact> initial = [
      list.first,
      list[1],
      list.last,
    ];

    return Scaffold(
      appBar: AppBar(
        title: const Text("Multi Select Search Menu"),
      ),
      body: Column(
        children: [
          Expanded(
            child: MultiSelectSearch<Contact>(
              itemBuilder: (Contact item) => ListTile(
                key: ObjectKey(item),
                leading: const Icon(Icons.person),
                title: Text(item.name),
              ),
              chipLabelKey: 'name',
              items: list,
              initialValue: initial,
              onChanged: (List<Contact> items) => setState(() => selectedItems = items),
              decoration: BoxDecoration(
                color: const Color(0xFFF7A072).withOpacity(0.6),
                border: const Border(
                  bottom: BorderSide(color: Colors.grey),
                ),
              ),
              clearAll: const Padding(
                padding: EdgeInsets.only(top: 10.0, right: 6.0),
                child: Icon(Icons.clear),
              ),
            ),
          ),
          Wrap(
            children: [
              for (var i = 0; i < selectedItems.length; i++)
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8.0),
                  child: Text(selectedItems[i].name),
                )
            ],
          )
        ],
      ),
    );
  }
}

class Contact {
  final int id;
  final String name;

  Contact(this.id, this.name);

  Contact.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        name = json['name'];

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
    };
  }
}

希望这个示例能帮助你更好地理解和使用 multi_select_search 插件。如果有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,以下是如何在Flutter项目中使用multi_select_search插件的示例代码。这个插件允许用户在一个多选搜索框中搜索和选择多个选项。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  multi_select_search: ^latest_version  # 替换为最新版本号

2. 导入包

在你的Dart文件中导入multi_select_search包:

import 'package:multi_select_search/multi_select_search.dart';

3. 准备数据

假设你有一个简单的数据列表,包含名称和ID:

class MyItem {
  String id;
  String name;

  MyItem({required this.id, required this.name});

  @override
  String toString() {
    return name;
  }
}

List<MyItem> items = [
  MyItem(id: '1', name: 'Apple'),
  MyItem(id: '2', name: 'Banana'),
  MyItem(id: '3', name: 'Cherry'),
  // 更多项目...
];

4. 使用MultiSelectSearch

在你的UI中使用MultiSelectSearch组件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MultiSelectSearch Example'),
        ),
        body: MultiSelectSearch<MyItem>(
          // 配置MultiSelectSearch
          initialSelectedItems: [],  // 初始选中的项目
          searchInputDecoration: InputDecoration(
            labelText: 'Search...',
            hintText: 'Search for items',
            prefixIcon: Icon(Icons.search),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.0),
            ),
          ),
          chipDecoration: BoxDecoration(
            color: Colors.blue.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12.0),
          ),
          onSearch: (query) async {
            // 模拟异步搜索
            await Future.delayed(Duration(seconds: 1));
            if (query.isEmpty) {
              return items;
            } else {
              return items
                  .where((item) => item.name.toLowerCase().contains(query.toLowerCase()))
                  .toList();
            }
          },
          onItemSelected: (item) {
            // 处理选中项
            print('Selected: ${item.name}');
          },
          onItemDeselected: (item) {
            // 处理取消选中项
            print('Deselected: ${item.name}');
          },
          selectedItems: [],  // 绑定的选中项目列表
          labelField: 'name',  // 用于显示的字段
          searchField: 'name',  // 用于搜索的字段
          buildItem: (context, item) {
            return ListTile(
              title: Text(item.name),
            );
          },
        ),
      ),
    );
  }
}

5. 运行应用

现在你可以运行你的Flutter应用,并看到一个多选搜索框。你可以在其中搜索并选择多个项目。

注意事项

  • 确保你已经在pubspec.yaml中添加了最新版本的multi_select_search依赖,并运行flutter pub get
  • 你可以根据需要自定义MultiSelectSearch组件的其他属性,如chipDecorationitemComparator等。
  • 异步搜索操作是模拟的,你可以替换为实际的网络请求或其他数据源。

这个示例代码展示了如何使用multi_select_search插件在Flutter应用中实现一个多选搜索框。希望这对你有所帮助!

回到顶部