Flutter如何实现三级联动组件

在Flutter中如何实现三级联动选择器?比如省市区三级联动,需要支持数据动态加载和回显功能。目前尝试过使用DropdownButton嵌套,但层级太多导致代码难以维护,有没有更优雅的解决方案?最好能提供可复用的组件示例代码。

2 回复

使用Flutter实现三级联动,可通过以下步骤:

  1. 使用DropdownButton或第三方库如flutter_picker
  2. 创建三个下拉菜单,分别对应三级数据。
  3. 监听第一级选择变化,更新第二级数据;同理更新第三级。
  4. 数据联动通过setState刷新UI。

示例代码可参考官方文档或相关插件文档。

更多关于Flutter如何实现三级联动组件的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现三级联动组件,可以通过以下步骤实现:

核心思路

使用三个DropdownButton组件,通过状态管理实现级联效果。当上级选择改变时,下级选项随之更新。

实现代码

import 'package:flutter/material.dart';

class TriplePicker extends StatefulWidget {
  @override
  _TriplePickerState createState() => _TriplePickerState();
}

class _TriplePickerState extends State<TriplePicker> {
  // 模拟数据(省份-城市-区县)
  final Map<String, Map<String, List<String>>> data = {
    '北京市': {
      '市辖区': ['东城区', '西城区', '朝阳区', '丰台区'],
    },
    '广东省': {
      '广州市': ['天河区', '越秀区', '海珠区'],
      '深圳市': ['福田区', '罗湖区', '南山区'],
    },
  };

  String? selectedProvince;
  String? selectedCity;
  String? selectedDistrict;

  List<String> get provinces => data.keys.toList();
  List<String> get cities => selectedProvince != null 
      ? data[selectedProvince]!.keys.toList() 
      : [];
  List<String> get districts => (selectedProvince != null && selectedCity != null)
      ? data[selectedProvince]![selectedCity]! 
      : [];

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        // 省份选择
        Expanded(
          child: DropdownButton<String>(
            isExpanded: true,
            value: selectedProvince,
            hint: Text('选择省份'),
            items: provinces.map((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
            onChanged: (String? newValue) {
              setState(() {
                selectedProvince = newValue;
                selectedCity = null; // 重置城市
                selectedDistrict = null; // 重置区县
              });
            },
          ),
        ),
        SizedBox(width: 10),
        
        // 城市选择
        Expanded(
          child: DropdownButton<String>(
            isExpanded: true,
            value: selectedCity,
            hint: Text('选择城市'),
            items: cities.map((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
            onChanged: (String? newValue) {
              setState(() {
                selectedCity = newValue;
                selectedDistrict = null; // 重置区县
              });
            },
          ),
        ),
        SizedBox(width: 10),
        
        // 区县选择
        Expanded(
          child: DropdownButton<String>(
            isExpanded: true,
            value: selectedDistrict,
            hint: Text('选择区县'),
            items: districts.map((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
            onChanged: (String? newValue) {
              setState(() {
                selectedDistrict = newValue;
              });
            },
          ),
        ),
      ],
    );
  }
}

使用方式

// 在页面中直接使用
TriplePicker()

关键点说明

  1. 数据管理:使用嵌套Map结构存储三级数据
  2. 状态联动:通过setState实现选择变化时的界面更新
  3. 级联重置:上级选项变化时清空下级选项
  4. 空值处理:使用hint提示用户选择

优化建议

  • 可封装为独立组件,支持数据注入
  • 添加加载状态和空数据提示
  • 支持自定义样式
  • 可改用PopupMenuButton实现更灵活的UI

这个实现方案简洁有效,适合大多数三级联动场景。

回到顶部