Flutter自定义可搜索下拉列表插件custom_searchable_dropdown的使用

Flutter 自定义可搜索下拉列表插件 custom_searchable_dropdown 的使用

custom_searchable_dropdown

允许用户从动态列表中搜索数据。你可以根据需要自定义下拉列表,它还可以被定制为多选或单选。on change 事件返回所选选项的完整列表。

平台

该组件已在 iOS、Android 和 Chrome 上成功测试。

示例

以下示例将帮助你了解其工作原理。

代码
import 'dart:convert';

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Custom Searchable DropDown 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> {

  List listToSearch=[
    {
      'name': 'Amir',
      'class': 12
    },
    {
      'name': 'Raza',
      'class': 11
    },
    {
      'name': 'Praksh',
      'class': 10
    },
    {
      'name': 'Nikhil',
      'class': 9
    },
    {
      'name': 'Sandeep',
      'class': 8
    },
    {
      'name': 'Tazeem',
      'class': 7
    },
    {
      'name': 'Najaf',
      'class': 6
    },
    {
      'name': 'Izhar',
      'class': 5
    },
  ];

  var selected;
  List selectedList;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: <Widget>[
              SizedBox(height: 20,),
              Text('Menu Mode',
                style: TextStyle(
                    fontWeight: FontWeight.bold
                ),),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: CustomSearchableDropDown(
                  dropdownHintText: 'Search For Name Here... ',
                  showLabelInMenu: true,
                  initialValue: [
                    {
                      'parameter': 'name',
                      'value': 'Amir',
                    }
                  ],
                  dropdownItemStyle: TextStyle(
                    color: Colors.red
                  ),
                  primaryColor: Colors.red,
                  menuMode: true,
                  labelStyle: TextStyle(
                    color: Colors.red,
                    fontWeight: FontWeight.bold
                  ),
                  items: listToSearch,
                  label: 'Select Name',
                  prefixIcon:  Icon(Icons.search),
                  dropDownMenuItems: listToSearch?.map((item) {
                    return item['name'];
                  })?.toList() ??
                      [],
                  onChanged: (value){
                    if(value!=null)
                    {
                      selected = value['class'].toString();
                    }
                    else{
                      selected=null;
                    }
                  },
                ),
              ),
              SizedBox(height: 20,),
              Text('Select a value',
              style: TextStyle(
                fontWeight: FontWeight.bold
              ),),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: CustomSearchableDropDown(
                  items: listToSearch,
                  label: 'Select Name',
                  decoration: BoxDecoration(
                      border: Border.all(
                          color: Colors.blue
                      )
                  ),
                  prefixIcon:  Padding(
                    padding: const EdgeInsets.all(0.0),
                    child: Icon(Icons.search),
                  ),
                  dropDownMenuItems: listToSearch?.map((item) {
                    return item['name'];
                  })?.toList() ??
                      [],
                  onChanged: (value){
                    if(value!=null)
                    {
                      selected = value['class'].toString();
                    }
                    else{
                      selected=null;
                    }
                  },
                ),
              ),
              Text('Multi Select',
                style: TextStyle(
                    fontWeight: FontWeight.bold
                ),),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: CustomSearchableDropDown(
                  items: listToSearch,

                  label: 'Select Name',
                  multiSelectTag: 'Names',
                  decoration: BoxDecoration(
                      border: Border.all(
                          color: Colors.blue
                      )
                  ),
                  multiSelect: true,
                  prefixIcon:  Padding(
                    padding: const EdgeInsets.all(0.0),
                    child: Icon(Icons.search),
                  ),
                  dropDownMenuItems: listToSearch?.map((item) {
                    return item['name'];
                  })?.toList() ??
                      [],
                  onChanged: (value){
                    if(value!=null)
                    {
                      selectedList = jsonDecode(value);
                    }
                    else{
                      selectedList.clear();
                    }
                  },
                ),
              ),
              Text('Multi Select as Widget',
                style: TextStyle(
                    fontWeight: FontWeight.bold
                ),),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: CustomSearchableDropDown(
                  initialValue: [
                    {
                      'parameter': 'name',
                      'value': 'Amir',
                    },
                    {
                      'parameter': 'name',
                      'value': 'Tazeem',
                    },
                  ],
                  items: listToSearch,
                  label: 'Select Name',
                  multiSelectTag: 'Names',
                  multiSelectValuesAsWidget: true,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.blue
                    )
                  ),
                  multiSelect: true,
                  prefixIcon:  Padding(
                    padding: const EdgeInsets.all(0.0),
                    child: Icon(Icons.search),
                  ),
                  dropDownMenuItems: listToSearch?.map((item) {
                    return item['name'];
                  })?.toList() ??
                      [],
                  onChanged: (value){
                    print(value.toString());
                    if(value!=null)
                    {
                      selectedList = jsonDecode(value);
                    }
                    else{
                      selectedList.clear();
                    }
                  },
                ),
              ),
            ],
          ),
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

示例说明

  1. 导入依赖pubspec.yaml 文件的 dependencies 部分添加:

    dependencies:
      custom_searchable_dropdown:
    

    然后运行命令获取依赖包:

    flutter packages get
    
  2. 导入包 在 Dart 文件中导入 custom_searchable_dropdown 包:

    import 'package:custom_searchable_dropdown/custom_searchable_dropdown.dart';
    
  3. 示例代码

    • 菜单模式

      CustomSearchableDropDown(
        dropdownHintText: 'Search For Name Here... ',
        showLabelInMenu: true,
        primaryColor: Colors.red,
        menuMode: true,
        labelStyle: TextStyle(
          color: Colors.red,
          fontWeight: FontWeight.bold
        ),
        items: listToSearch,
        label: 'Select Name',
        prefixIcon: Icon(Icons.search),
        dropDownMenuItems: listToSearch?.map((item) {
          return item['name'];
        })?.toList() ?? [],
        onChanged: (value){
          if(value!=null)
          {
            selected = value['class'].toString();
          }
          else{
            selected=null;
          }
        },
      ),
      
    • 单选模式

      CustomSearchableDropDown(
        items: listToSearch,
        label: 'Select Name',
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.blue
          )
        ),
        prefixIcon: Padding(
          padding: const EdgeInsets.all(0.0),
          child: Icon(Icons.search),
        ),
        dropDownMenuItems: listToSearch?.map((item) {
          return item['name'];
        })?.toList() ?? [],
        onChanged: (value){
          if(value!=null)
          {
            selected = value['class'].toString();
          }
          else{
            selected=null;
          }
        },
      ),
      
    • 多选模式

      CustomSearchableDropDown(
        items: listToSearch,
        label: 'Select Name',
        multiSelectTag: 'Names',
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.blue
          )
        ),
        multiSelect: true,
        prefixIcon: Padding(
          padding: const EdgeInsets.all(0.0),
          child: Icon(Icons.search),
        ),
        dropDownMenuItems: listToSearch?.map((item) {
          return item['name'];
        })?.toList() ?? [],
        onChanged: (value){
          if(value!=null)
          {
            selectedList = jsonDecode(value);
          }
          else{
            selectedList.clear();
          }
        },
      ),
      
    • 多选作为 Widget

      CustomSearchableDropDown(
        initialValue: [
          {
            'parameter': 'name',
            'value': 'Amir',
          },
          {
            'parameter': 'name',
            'value': 'Tazeem',
          },
        ],
        items: listToSearch,
        label: 'Select Name',
        multiSelectTag: 'Names',
        multiSelectValuesAsWidget: true,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.blue
          )
        ),
        multiSelect: true,
        prefixIcon: Padding(
          padding: const EdgeInsets.all(0.0),
          child: Icon(Icons.search),
        ),
        dropDownMenuItems: listToSearch?.map((item) {
          return item['name'];
        })?.toList() ?? [],
        onChanged: (value){
          print(value.toString());
          if(value!=null)
          {
            selectedList = jsonDecode(value);
          }
          else{
            selectedList.clear();
          }
        },
      ),
      

更多关于Flutter自定义可搜索下拉列表插件custom_searchable_dropdown的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义可搜索下拉列表插件custom_searchable_dropdown的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用custom_searchable_dropdown插件来创建一个自定义可搜索下拉列表的示例代码。首先,确保你已经在pubspec.yaml文件中添加了custom_searchable_dropdown依赖:

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

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

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

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  // 模拟数据列表
  List<String> items = [
    'Apple',
    'Banana',
    'Cherry',
    'Date',
    'Elderberry',
    'Fig',
    'Grape',
  ];

  String? selectedValue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Searchable Dropdown Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              'Selected Item:',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Text(
              selectedValue ?? 'None',
              style: TextStyle(fontSize: 16),
            ),
            SizedBox(height: 20),
            CustomSearchableDropDown<String>(
              items: items,
              value: selectedValue,
              onChanged: (newValue) {
                setState(() {
                  selectedValue = newValue;
                });
              },
              searchHint: 'Search...',
              itemBuilder: (context, item) {
                return ListTile(
                  title: Text(item),
                );
              },
              isCaseSensitiveSearch: false,
            ),
          ],
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖导入

    • 确保在pubspec.yaml中添加了custom_searchable_dropdown依赖。
  2. 数据准备

    • _MyHomePageState类中,定义了一个List<String>类型的items列表,作为下拉列表的数据源。
  3. UI构建

    • 使用Scaffold作为主布局,包含一个AppBar和一个Column
    • Column中包含了显示选中项的Text组件,以及一个CustomSearchableDropDown组件。
  4. CustomSearchableDropDown配置

    • items:指定下拉列表的数据源。
    • value:当前选中的值,初始化为null
    • onChanged:当选中项改变时的回调函数,更新selectedValue状态。
    • searchHint:搜索框的提示文本。
    • itemBuilder:自定义每个列表项的构建方式,这里使用了ListTile
    • isCaseSensitiveSearch:是否区分大小写搜索,这里设置为false

通过这个示例,你可以看到如何使用custom_searchable_dropdown插件来创建一个自定义的可搜索下拉列表,并处理用户的选择。你可以根据自己的需求进一步自定义和扩展这个示例。

回到顶部