Flutter快速下拉菜单插件quick_dropdown的使用

Flutter快速下拉菜单插件quick_dropdown的使用

概述

Quick Dropdown 是一个高度可定制的 Flutter 包,它提供了一个灵活且功能丰富的下拉菜单小部件。

安装

要在您的 Flutter 项目中使用 Quick Dropdown,请在 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  quick_dropdown: ^0.0.1

然后运行 flutter pub get 来安装该包。

使用

首先,在 Dart 代码中导入 quick_dropdown 包:

import 'package:quick_dropdown/quick_dropdown.dart';

接下来,使用 QuickDropdown 小部件在您的用户界面中添加下拉菜单:

QuickDropdown(
  items: [...], // 提供您的项目列表
  selectedValue: 'Select',
  onChanged: (String? value) {
    // 处理选中的值
    print('Selected value: $value');
  },
  onSearch: (String searchQuery) async {
    // 实现您的搜索逻辑
    return Future.value([]);
  },
)

根据您的需求自定义小部件的参数。

示例

以下是完整的示例代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Quick Dropdown',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Quick Dropdown'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String searchQuery = '';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: QuickDropdown(
                items: List.generate(10, (index) => 'Item $index'),
                selectedValue: 'Select',
                onChanged: (String? value) {
                  debugPrint('Selected value: $value');
                },
                onSearch: (String searchQuery) {
                  debugPrint('Search query: $searchQuery');
                  return Future.value([]);
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

class QuickDropdown extends StatefulWidget {
  final List<String> items;
  final String? selectedValue;
  final ValueChanged<String?> onChanged;
  final Future<void> Function(String searchQuery) onSearch;
  final TextStyle? textStyle;
  final IconData? dropdownIcon;
  final BorderRadius? borderRadius;
  final Color? backgroundColor;
  final Color? borderColor;
  final Color? dividerColor;
  final Color? textColor;
  final Color? hintColor;
  final Color? searchIconColor;
  final Color? searchHintColor;
  final Color? errorTextColor;
  final double? fontSize;
  final double? itemHeight;

  const QuickDropdown({
    required this.items,
    required this.selectedValue,
    required this.onChanged,
    required this.onSearch,
    this.textStyle,
    this.dropdownIcon,
    this.borderRadius,
    this.backgroundColor,
    this.borderColor,
    this.dividerColor,
    this.textColor,
    this.hintColor,
    this.searchIconColor,
    this.searchHintColor,
    this.errorTextColor,
    this.fontSize,
    this.itemHeight,
    Key? key,
  }) : super(key: key);

  [@override](/user/override)
  _QuickDropdownState createState() => _QuickDropdownState();
}

class _QuickDropdownState extends State<QuickDropdown> {
  bool isDropdownOpen = false;
  String? selectedValue;
  String? errorText;
  bool isLoading = false;

  [@override](/user/override)
  void initState() {
    super.initState();
    selectedValue = widget.selectedValue;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    bool isdarkmode = Theme.of(context).brightness == Brightness.light;

    return Container(
      decoration: BoxDecoration(
        borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
        color: widget.backgroundColor ?? Colors.transparent,
        border: Border.all(
          color: widget.borderColor ??
              (isdarkmode ? const Color(0xffA3A3A3) : const Color(0xffDCDCDC)),
          width: 1.0,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          InkWell(
            onTap: () {
              setState(() {
                isDropdownOpen = !isDropdownOpen;
              });
            },
            child: Container(
              padding: EdgeInsets.symmetric(
                horizontal: size.width * 0.03,
                vertical: size.height * 0.02,
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      selectedValue ?? "Select",
                      style: widget.textStyle ??
                          TextStyle(
                            fontSize: widget.fontSize ?? 16,
                            color: widget.textColor ??
                                (isdarkmode
                                    ? const Color(0xffA3A3A3)
                                    : const Color(0xffDCDCDC)),
                          ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const Spacer(),
                  Icon(
                    widget.dropdownIcon ??
                        (isDropdownOpen
                            ? Icons.keyboard_arrow_up
                            : Icons.keyboard_arrow_down),
                    color: widget.textColor ??
                        (isdarkmode
                            ? const Color(0xffA3A3A3)
                            : const Color(0xffDCDCDC)),
                  ),
                ],
              ),
            ),
          ),
          if (isDropdownOpen)
            Column(
              children: [
                TextField(
                  onChanged: ((value) {
                    setState(() {
                      selectedValue = value;
                    });
                    widget.onSearch(value);

                    setState(() {
                      errorText = null;
                    });

                    widget.onSearch(value).catchError((error) {
                      setState(() {
                        errorText = "Search failed: $error";
                      });
                    });
                  }),
                  decoration: InputDecoration(
                    hintText: "Search",
                    hintStyle: TextStyle(
                      fontSize: widget.fontSize ?? 16,
                      color: widget.searchHintColor ??
                          (isdarkmode
                              ? const Color(0xffA3A3A3)
                              : const Color(0xffDCDCDC)),
                    ),
                    prefixIcon: Icon(
                      Icons.search,
                      color: widget.searchIconColor ??
                          (isdarkmode
                              ? const Color(0xffA3A3A3)
                              : const Color(0xffDCDCDC)),
                    ),
                    border: InputBorder.none,
                  ),
                ),
                if (isLoading) const Center(child: CircularProgressIndicator()),
                if (errorText != null)
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      errorText!,
                      style:
                          TextStyle(color: widget.errorTextColor ?? Colors.red),
                    ),
                  ),
                if (!isLoading && widget.items.isEmpty)
                  const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text('No items found.'),
                  ),
                if (!isLoading && widget.items.isNotEmpty)
                  SizedBox(
                    height: widget.itemHeight ?? 150,
                    child: ListView.separated(
                      separatorBuilder: (context, index) => Divider(
                        height: 2,
                        thickness: 1.5,
                        color: widget.dividerColor ??
                            (isdarkmode
                                ? const Color(0xffA3A3A3)
                                : const Color(0xffDCDCDC)),
                      ),
                      itemCount: widget.items.length,
                      itemBuilder: (context, index) {
                        final item = widget.items[index];
                        return InkWell(
                          onTap: () {
                            setState(() {
                              selectedValue = item;
                              isDropdownOpen = false;
                              widget.onChanged(item);
                            });
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: size.width * 0.03,
                              vertical: size.height * 0.02,
                            ),
                            child: Text(
                              item,
                              style: TextStyle(
                                fontSize: widget.fontSize ?? 16,
                                color: widget.textColor ??
                                    (isdarkmode
                                        ? const Color(0xffA3A3A3)
                                        : const Color(0xffDCDCDC)),
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
              ],
            ),
        ],
      ),
    );
  }
}

更多关于Flutter快速下拉菜单插件quick_dropdown的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter快速下拉菜单插件quick_dropdown的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用quick_dropdown插件的一个示例代码案例。quick_dropdown是一个用于快速创建下拉菜单的Flutter插件。

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

dependencies:
  flutter:
    sdk: flutter
  quick_dropdown: ^最新版本号  # 请替换为实际可用的最新版本号

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

接下来,你可以在Flutter应用中使用QuickDropdown组件。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Quick Dropdown Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Quick Dropdown Demo'),
        ),
        body: Center(
          child: QuickDropdown<String>(
            items: ['Option 1', 'Option 2', 'Option 3'],
            onValueChanged: (value) {
              print('Selected value: $value');
            },
            hint: Text('Select an option'),
            dialogBoxDecoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            itemBuilder: (context, value) {
              return ListTile(
                title: Text(value),
              );
            },
          ),
        ),
      ),
    );
  }
}

在这个示例中:

  1. 依赖导入:导入了flutter/material.dartquick_dropdown/quick_dropdown.dart
  2. QuickDropdown组件
    • items:下拉菜单中的选项列表。
    • onValueChanged:当用户选择一个选项时触发的回调,返回选中的值。
    • hint:下拉菜单未选中时显示的提示文本。
    • dialogBoxDecoration:下拉菜单对话框的装饰,这里设置了背景颜色和边框圆角。
    • itemBuilder:自定义每个选项的UI,这里使用了ListTile

这个示例展示了如何使用quick_dropdown插件创建一个简单的下拉菜单,并且当用户选择一个选项时,会在控制台打印选中的值。你可以根据需要进一步自定义和扩展这个示例。

回到顶部