Flutter下拉选择插件dropdown_flutter的使用

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

Flutter下拉选择插件dropdown_flutter的使用

Dropdown Flutter

DropdownFlutter 插件旨在增强你的Flutter应用程序,提供高度可定制的下拉菜单,具备高级功能如列表数据搜索、网络搜索和多选等。

特性

  • 提供大量属性用于自定义下拉菜单以满足需求。
  • 可在Form组件中使用以实现必填项验证。
  • 支持多种构造方式:
    • 普通下拉菜单:DropdownFlutter
    • 带搜索字段的下拉菜单:DropdownFlutter.search
    • 带搜索请求字段的下拉菜单:DropdownFlutter.searchRequest
    • 多选下拉菜单:DropdownFlutter.multiSelect
    • 带搜索字段的多选下拉菜单:DropdownFlutter.multiSelectSearch
    • 带搜索请求字段的多选下拉菜单:DropdownFlutter.multiSelectSearchRequest

预览


入门指南

  1. 将最新版本的包添加到你的pubspec.yaml文件(并运行flutter pub get):
dependencies:
  dropdown_flutter: 1.0.1
  1. 导入包并在你的Flutter应用中使用它:
import 'package:dropdown_flutter/custom_dropdown.dart';

示例用法

1. 简单的Dropdown Flutter

import 'package:dropdown_flutter/custom_dropdown.dart';
import 'package:flutter/material.dart';
import 'dart:developer';

const List<String> _list = [
  'Developer',
  'Designer',
  'Consultant',
  'Student',
];

class SimpleDropdown extends StatelessWidget {
  const SimpleDropdown({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DropdownFlutter<String>(
      hintText: 'Select job role',
      items: _list,
      initialItem: _list[0],
      onChanged: (value) {
        log('changing value to: $value');
      },
    );
  }
}

2. 使用自定义类型模型的Dropdown Flutter

首先定义一个自定义类型,并重写toString()方法以显示所需属性:

class Job {
  final String name;
  final IconData icon;
  const Job(this.name, this.icon);

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

const List<Job> _list = [
  Job('Developer', Icons.developer_mode),
  Job('Designer', Icons.design_services),
  Job('Consultant', Icons.account_balance),
  Job('Student', Icons.school),
];

class CustomTypeDropdown extends StatelessWidget {
  const CustomTypeDropdown({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DropdownFlutter<Job>(
      hintText: 'Select job role',
      items: _list,
      onChanged: (value) {
        log('changing value to: $value');
      },
    );
  }
}

3. 多选Dropdown Flutter

class MultiSelectDropDown extends StatelessWidget {
  const MultiSelectDropDown({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DropdownFlutter<Job>.multiSelect(
      items: _list,
      initialItems: _list.take(1).toList(),
      onListChanged: (value) {
        log('changing value to: $value');
      },
    );
  }
}

4. 带搜索功能的Dropdown Flutter

增强Job模型以支持过滤功能:

class Job with DropdownFlutterListFilter {
  final String name;
  final IconData icon;
  const Job(this.name, this.icon);

  @override
  String toString() {
    return name;
  }

  @override
  bool filter(String query) {
    return name.toLowerCase().contains(query.toLowerCase());
  }
}

class SearchDropdown extends StatelessWidget {
  const SearchDropdown({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DropdownFlutter<Job>.search(
      hintText: 'Select job role',
      items: _list,
      excludeSelected: false,
      onChanged: (value) {
        log('changing value to: $value');
      },
    );
  }
}

5. 带搜索请求的Dropdown Flutter

模拟API调用来加载项目:

class Pair {
  final String text;
  final IconData icon;
  const Pair(this.text, this.icon);

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

const List<Pair> _list = [
  Pair('Developer', Icons.developer_board),
  Pair('Designer', Icons.deblur_sharp),
  Pair('Consultant', Icons.money_off),
  Pair('Student', Icons.edit),
];

class SearchRequestDropdown extends StatelessWidget {
  const SearchRequestDropdown({Key? key}) : super(key: key);

  Future<List<Pair>> _getFakeRequestData(String query) async {
    return await Future.delayed(const Duration(seconds: 1), () {
      return _list.where((e) {
        return e.text.toLowerCase().contains(query.toLowerCase());
      }).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return DropdownFlutter<Pair>.searchRequest(
      futureRequest: _getFakeRequestData,
      hintText: 'Search job role',
      items: _list,
      onChanged: (value) {
        log('changing value to: $value');
      },
    );
  }
}

6. 带验证的Dropdown Flutter

单选验证

class ValidationDropdown extends StatelessWidget {
  ValidationDropdown({Key? key}) : super(key: key);

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          DropdownFlutter<String>(
            hintText: 'Select job role',
            items: _list,
            onChanged: (value) {
              log('changing value to: $value');
            },
            validateOnChange: true,
            validator: (value) => value == null ? "Must not be null" : null,
          ),
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                if (!_formKey.currentState!.validate()) return;
              },
              child: const Text(
                'Submit',
                style: TextStyle(fontWeight: FontWeight.w600),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

多选验证

class MultiSelectValidationDropdown extends StatelessWidget {
  MultiSelectValidationDropdown({Key? key}) : super(key: key);

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          DropdownFlutter<String>.multiSelect(
            hintText: 'Select job role',
            items: _list,
            onListChanged: (value) {
              log('changing value to: $value');
            },
            listValidator: (value) => value.isEmpty ? "Must not be null" : null,
          ),
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                if (!_formKey.currentState!.validate()) return;
              },
              child: const Text(
                'Submit',
                style: TextStyle(fontWeight: FontWeight.w600),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

完整示例Demo

import 'package:dropdown_flutter/custom_dropdown.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 MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Dropdown Flutter App',
      home: const Home(),
      theme: ThemeData(
        brightness: Brightness.light,
        colorScheme: ColorScheme.fromSeed(
          brightness: Brightness.light,
          seedColor: Colors.blue,
          primary: Colors.grey[200],
        ),
      ),
    );
  }
}

class Home extends StatefulWidget {
  const Home({super.key});
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: Theme.of(context).colorScheme.primary,
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.primary,
          title: const Text(
            'Custom Dropdown Example',
            style: TextStyle(color: Colors.white),
          ),
          bottom: const TabBar(
            labelColor: Colors.white,
            unselectedLabelColor: Colors.white70,
            labelStyle: TextStyle(fontSize: 18),
            unselectedLabelStyle: TextStyle(fontSize: 18),
            padding: EdgeInsets.all(2),
            tabs: [
              Padding(
                padding: EdgeInsets.only(bottom: 8.0),
                child: Text(
                  'Single selection',
                ),
              ),
              Padding(
                padding: EdgeInsets.only(bottom: 8.0),
                child: Text('Multi selection'),
              ),
            ],
          ),
        ),
        body: TabBarView(
          children: [
            ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                const SimpleDropdown(),
                const SizedBox(height: 16),
                const SearchDropdown(),
                const SizedBox(height: 16),
                const SearchRequestDropdown(),
                const SizedBox(height: 16),
                // Add more widgets here...
              ],
            ),
            ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                const MultiSelectDropdown(),
                const SizedBox(height: 16),
                const MultiSelectSearchDropdown(),
                const SizedBox(height: 16),
                const MultiSelectSearchRequestDropdown(),
                const SizedBox(height: 16),
                // Add more widgets here...
              ],
            ),
          ],
        ),
      ),
    );
  }
}

以上是dropdown_flutter插件的详细使用说明和完整示例代码。你可以根据需要调整和扩展这些代码片段。如果你有任何问题或反馈,请随时提交issue。


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

1 回复

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


当然,下面是一个关于如何在Flutter中使用dropdown_flutter插件(注意:通常我们使用的是更广泛认可的dropdown_menu或官方的DropdownButton,但我会按照你的要求假设dropdown_flutter是一个有效的包名或者类似功能的插件)的示例代码。如果dropdown_flutter不是一个实际存在的包,你可以参考官方的DropdownButton实现方式,逻辑是类似的。

首先,确保你已经在pubspec.yaml文件中添加了dropdown_flutter(或相应的插件)依赖:

dependencies:
  flutter:
    sdk: flutter
  dropdown_flutter: ^x.y.z  # 替换为实际的版本号

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

以下是一个使用dropdown_flutter(或类似功能插件)的基本示例:

import 'package:flutter/material.dart';
import 'package:dropdown_flutter/dropdown_flutter.dart'; // 假设这是插件的导入路径

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

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

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

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

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

  void handleDropdownChange(String? newValue) {
    setState(() {
      selectedValue = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dropdown Flutter Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DropdownFlutter( // 假设这是插件提供的组件名
              items: dropdownItems.map((String item) {
                return DropdownMenuItem<String>(
                  value: item,
                  child: Text(item),
                );
              }).toList(),
              hint: Text('Select an item'),
              value: selectedValue,
              onChanged: handleDropdownChange,
            ),
            SizedBox(height: 20),
            Text('Selected Value: ${selectedValue ?? 'None'}'),
          ],
        ),
      ),
    );
  }
}

注意

  1. DropdownFlutter组件可能是假设的,实际使用时请替换为正确的组件名。
  2. 如果dropdown_flutter不是一个有效的包名,你可能需要使用Flutter社区更常用的dropdown_menu或官方的DropdownButton
  3. 对于官方的DropdownButton,使用方法类似,但组件名和API可能有所不同。以下是使用官方DropdownButton的示例:
// 使用官方的 DropdownButton
import 'package:flutter/material.dart';

// ...

DropdownButton<String>(
  hint: Text('Select an item'),
  value: selectedValue,
  icon: Icon(Icons.arrow_downward),
  iconSize: 24,
  elevation: 16,
  style: TextStyle(color: Colors.deepPurple),
  underline: Container(
    height: 2,
    color: Colors.deepPurpleAccent,
  ),
  onChanged: handleDropdownChange,
  items: dropdownItems.map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
)

希望这能帮助你开始在Flutter中使用下拉选择插件!

回到顶部