Flutter多级联动下拉选择插件vega_multi_dropdown的使用

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

Flutter多级联动下拉选择插件vega_multi_dropdown的使用

示例代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:multi_dropdown/multi_dropdown.dart';

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

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

  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Multiselect dropdown demo',
      debugShowCheckedModeBanner: false,
      themeMode: ThemeMode.dark,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      routerConfig: GoRouter(routes: [
        GoRoute(
          path: '/',
          builder: (context, state) {
            return const MyHomePage();
          },
        ),
      ]),
    );
  }
}

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

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

class User {
  final String name;
  final int id;

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

  [@override](/user/override)
  String toString() {
    return 'User(name: $name, id: $id)';
  }
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();

  final controller = MultiSelectController<User>();

  [@override](/user/override)
  Widget build(BuildContext context) {
    var items = [
      DropdownItem(id: '1', label: 'Nepal', value: User(name: 'Nepal', id: 1)),
      DropdownItem(id: '6', label: 'Australia', value: User(name: 'Australia', id: 6)),
      DropdownItem(id: '2', label: 'India', value: User(name: 'India', id: 2)),
      DropdownItem(id: '3', label: 'China', value: User(name: 'China', id: 3)),
      DropdownItem(id: '4', label: 'USA', value: User(name: 'USA', id: 4)),
      DropdownItem(id: '5', label: 'UK', value: User(name: 'UK', id: 5)),
      DropdownItem(id: '7', label: 'Germany', value: User(name: 'Germany', id: 7)),
      DropdownItem(id: '8', label: 'France', value: User(name: 'France', id: 8)),
    ];
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            child: SizedBox(
              width: double.infinity,
              height: MediaQuery.of(context).size.height,
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    const SizedBox(height: 4),
                    MultiDropdown&lt;User&gt;(
                      items: items,
                      controller: controller,
                      enabled: true,
                      searchEnabled: true,
                      chipDecoration: const ChipDecoration(
                        backgroundColor: Colors.yellow,
                        wrap: true,
                        runSpacing: 2,
                        spacing: 10,
                      ),
                      fieldDecoration: FieldDecoration(
                        hintText: 'Countries',
                        hintStyle: const TextStyle(color: Colors.black87),
                        prefixIcon: const Icon(CupertinoIcons.flag),
                        showClearIcon: false,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: const BorderSide(color: Colors.grey),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: const BorderSide(
                            color: Colors.black87,
                          ),
                        ),
                      ),
                      dropdownDecoration: const DropdownDecoration(
                        marginTop: 2,
                        maxHeight: 500,
                        header: Padding(
                          padding: EdgeInsets.all(8),
                          child: Text(
                            'Select countries from the list',
                            textAlign: TextAlign.start,
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                      dropdownItemDecoration: DropdownItemDecoration(
                        selectedIcon: const Icon(Icons.check_box, color: Colors.green),
                        disabledIcon: Icon(Icons.lock, color: Colors.grey.shade300),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please select a country';
                        }
                        return null;
                      },
                      onSelectionChange: (selectedItems) {
                        debugPrint("OnSelectionChange: $selectedItems");
                      },
                    ),
                    const SizedBox(height: 12),
                    Wrap(
                      spacing: 8,
                      children: [
                        ElevatedButton(
                          onPressed: () {
                            if (_formKey.currentState?.validate() ?? false) {
                              final selectedItems = controller.selectedItems;

                              debugPrint(selectedItems.toString());
                            }
                          },
                          child: const Text('Submit'),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            controller.selectAll();
                          },
                          child: const Text('Select All'),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            controller.clearAll();
                          },
                          child: const Text('Unselect All'),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            controller.addItems([
                              DropdownItem(id: '8', label: 'France', value: User(name: 'France', id: 8)),
                            ]);
                          },
                          child: const Text('Add Items'),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            controller.selectWhere((element) =&gt; element.value.id == 1 || element.value.id == 2 || element.value.id == 3);
                          },
                          child: const Text('Select Where'),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            controller.selectAtIndex(0);
                          },
                          child: const Text('Select At Index'),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            controller.openDropdown();
                          },
                          child: const Text('Open/Close dropdown'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个使用Flutter多级联动下拉选择插件vega_multi_dropdown的示例代码案例。这个插件允许你创建多级下拉菜单,其中每个菜单的选项依赖于前一个菜单的选择。

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

dependencies:
  flutter:
    sdk: flutter
  vega_multi_dropdown: ^最新版本号  # 请替换为当前最新版本号

然后,你可以在你的Flutter项目中按照以下方式使用它:

import 'package:flutter/material.dart';
import 'package:vega_multi_dropdown/vega_multi_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: MultiDropdownDemo(),
    );
  }
}

class MultiDropdownDemo extends StatefulWidget {
  @override
  _MultiDropdownDemoState createState() => _MultiDropdownDemoState();
}

class _MultiDropdownDemoState extends State<MultiDropdownDemo> {
  // 初始数据
  List<Map<String, dynamic>>? countries;
  List<Map<String, dynamic>>? states;
  List<Map<String, dynamic>>? cities;
  String? selectedCountry;
  String? selectedState;
  String? selectedCity;

  @override
  void initState() {
    super.initState();
    // 加载初始数据
    loadData();
  }

  void loadData() async {
    // 模拟从服务器获取数据
    countries = [
      {"id": "1", "name": "USA"},
      {"id": "2", "name": "India"},
    ];

    states = [
      {"id": "1_1", "parentId": "1", "name": "California"},
      {"id": "1_2", "parentId": "1", "name": "Texas"},
      {"id": "2_1", "parentId": "2", "name": "Delhi"},
      {"id": "2_2", "parentId": "2", "name": "Mumbai"},
    ];

    cities = [
      {"id": "1_1_1", "parentId": "1_1", "name": "Los Angeles"},
      {"id": "1_1_2", "parentId": "1_1", "name": "San Francisco"},
      {"id": "1_2_1", "parentId": "1_2", "name": "Austin"},
      {"id": "1_2_2", "parentId": "1_2", "name": "Houston"},
      {"id": "2_1_1", "parentId": "2_1", "name": "New Delhi"},
      {"id": "2_2_1", "parentId": "2_2", "name": "Mumbai City"},
    ];

    setState(() {});
  }

  void onCountryChanged(String? value) {
    setState(() {
      selectedCountry = value;
      selectedState = null;
      selectedCity = null;
      // 根据选中的国家过滤州
      states = states!.where((state) => state["parentId"] == "${selectedCountry!}").toList();
    });
  }

  void onStateChanged(String? value) {
    setState(() {
      selectedState = value;
      selectedCity = null;
      // 根据选中的州过滤城市
      cities = cities!.where((city) => city["parentId"] == "${selectedState!}").toList();
    });
  }

  void onCityChanged(String? value) {
    setState(() {
      selectedCity = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("多级联动下拉菜单示例"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text("选择国家:", style: TextStyle(fontSize: 16)),
            VegaMultiDropdown(
              data: countries,
              displayField: "name",
              valueField: "id",
              onChanged: onCountryChanged,
              value: selectedCountry,
              hintText: "请选择国家",
            ),
            SizedBox(height: 16),
            Text("选择州:", style: TextStyle(fontSize: 16)),
            VegaMultiDropdown(
              data: states,
              displayField: "name",
              valueField: "id",
              onChanged: onStateChanged,
              value: selectedState,
              hintText: "请选择州",
              isDependent: true, // 表示这个下拉框是依赖的
            ),
            SizedBox(height: 16),
            Text("选择城市:", style: TextStyle(fontSize: 16)),
            VegaMultiDropdown(
              data: cities,
              displayField: "name",
              valueField: "id",
              onChanged: onCityChanged,
              value: selectedCity,
              hintText: "请选择城市",
              isDependent: true, // 表示这个下拉框是依赖的
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. VegaMultiDropdown用于创建多级下拉菜单。
  2. loadData方法模拟从服务器加载数据。
  3. onCountryChangedonStateChangedonCityChanged方法用于处理每个下拉菜单的变化,并根据前一个下拉菜单的选择来更新下一个下拉菜单的选项。
  4. isDependent: true表示该下拉框是依赖的,这意味着它的选项将基于前一个下拉框的选择来更新。

这个示例展示了如何使用vega_multi_dropdown插件来创建一个简单的三级联动下拉菜单。你可以根据需要进一步自定义和扩展这个示例。

回到顶部