Flutter嵌套选择模态框插件nested_selection_modal的使用

Flutter嵌套选择模态框插件nested_selection_modal的使用

nested_selection_modal 是一个简单的 Flutter 小部件,用于从树结构的选择中进行选择。

使用示例

以下是一个完整的示例代码,展示了如何在 Flutter 应用程序中使用 nested_selection_modal 插件。

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int? selection = null;
  List<int> selections = []; // [2010,3,4];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
                onPressed: () async {
                  var r = await showNestedSelectionsModal<String>(
                    context,
                    initialSelections: [],
                    items: _createItems()!,
                    selectorWidth: 130
                    //itemHeight: 100,
                    //selectorHeight: 100
                  );
                  print(r?.toString());
                },
                child: Text('显示嵌套选择模态框')),
            SizedBox(
              height: 30,
            ),
            // NestedSelectionView<int>(
            //     selections: selections,
            //     onSelectionChanged: (s) {
            //       selections = s;
            //       setState(() {});
            //     },
            //     items: List.generate(30, (index) => index + 2000)
            //         .map((e) => SelectionItemModel(
            //             label: '$e',
            //             value: e,
            //             children: List.generate(
            //                 12,
            //                 (index) => SelectionItemModel(
            //                     label: (index + 1).toString(),
            //                     value: (index + 1),
            //                     children: List.generate(30,
            //                         (index) => SelectionItemModel(label: (index + 1).toString(), value: index + 1))))))
            //         .toList())
          ],
        ),
      ),
    );
  }

  List<SelectionItemModel<String>>? _createItems({String? parent = null, int level = 0}) {
    if (level == 4) return null;
    if (level == 0) {
      return ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
          .map((e) => SelectionItemModel(label: e, value: e, children: _createItems(parent: e, level: level + 1)))
          .toList();
    }
    //
    return List.generate(
      10,
      (index) => SelectionItemModel(
          label: '$parent-${index + 1}',
          value: '$parent-${index + 1}',
          children: _createItems(parent: '$parent-${index + 1}', level: level + 1)),
    );
  }
}

代码说明

  • MyApp: 主应用类,设置了主题和初始页面。
  • MyHomePage: 主页面类,包含一个按钮,点击按钮会弹出嵌套选择模态框。
  • _MyHomePageState: 页面状态类,负责构建页面并处理按钮点击事件。
    • selections: 存储用户选择的结果。
    • _createItems: 创建树形结构的数据项。

按钮点击事件

onPressed: () async {
  var r = await showNestedSelectionsModal<String>(
    context,
    initialSelections: [],
    items: _createItems()!,
    selectorWidth: 130
    //itemHeight: 100,
    //selectorHeight: 100
  );
  print(r?.toString());
},

更多关于Flutter嵌套选择模态框插件nested_selection_modal的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter嵌套选择模态框插件nested_selection_modal的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


nested_selection_modal 是一个 Flutter 插件,用于创建嵌套的选择模态框。它允许用户在模态框中进行多层次的选择,通常用于需要从多个类别或层次结构中选择数据的场景。

安装插件

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

dependencies:
  flutter:
    sdk: flutter
  nested_selection_modal: ^1.0.0  # 请根据实际情况替换为最新版本

然后运行 flutter pub get 来安装插件。

基本用法

以下是一个简单的示例,展示如何使用 nested_selection_modal 插件创建一个嵌套选择模态框。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  final List<NestedSelectionItem> items = [
    NestedSelectionItem(
      title: 'Category 1',
      children: [
        NestedSelectionItem(title: 'Item 1.1'),
        NestedSelectionItem(title: 'Item 1.2'),
      ],
    ),
    NestedSelectionItem(
      title: 'Category 2',
      children: [
        NestedSelectionItem(title: 'Item 2.1'),
        NestedSelectionItem(title: 'Item 2.2'),
      ],
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Nested Selection Modal Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            showNestedSelectionModal(
              context: context,
              items: items,
              onSelectionComplete: (selectedItems) {
                print('Selected Items: $selectedItems');
              },
            );
          },
          child: Text('Open Modal'),
        ),
      ),
    );
  }
}

参数说明

  • items: 一个 NestedSelectionItem 列表,表示模态框中的选择项。每个 NestedSelectionItem 可以包含子项,形成嵌套结构。
  • onSelectionComplete: 当用户完成选择时触发的回调函数,返回用户选择的项列表。
  • context: 必须传递的 BuildContext,用于显示模态框。

NestedSelectionItem

NestedSelectionItem 类用于定义每个选择项的属性和子项。它包含以下属性:

  • title: 选择项的标题。
  • children: 子项列表(可选)。
  • isSelected: 表示该项是否被选中(可选)。

自定义样式

你可以通过传递 modalConfig 参数来自定义模态框的样式和行为。modalConfig 是一个 NestedSelectionModalConfig 对象,允许你设置模态框的标题、按钮文本、颜色等。

showNestedSelectionModal(
  context: context,
  items: items,
  modalConfig: NestedSelectionModalConfig(
    title: 'Select Items',
    confirmButtonText: 'Done',
    cancelButtonText: 'Cancel',
    backgroundColor: Colors.white,
    textStyle: TextStyle(color: Colors.black),
  ),
  onSelectionComplete: (selectedItems) {
    print('Selected Items: $selectedItems');
  },
);

处理选择结果

onSelectionComplete 回调函数会返回一个包含用户选择的 NestedSelectionItem 列表。你可以在回调函数中处理这些选择结果,例如更新 UI 或执行其他操作。

onSelectionComplete: (selectedItems) {
  setState(() {
    // 更新 UI 或其他操作
  });
},
回到顶部