Flutter折叠面板插件simple_accordion的使用

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

Flutter折叠面板插件simple_accordion的使用

简介

simple_accordion 是一个支持常见折叠面板功能的插件,并且易于使用。你可以在 pub.dev 上查看详细信息。

展示图

如果你喜欢这个项目,可以通过提交 PR 来贡献代码。

添加到你的项目

在你的 pubspec.yaml 文件中添加依赖:

flutter pub add simple_accordion

导入并使用它

在你的 Dart 文件中导入插件:

import 'package:simple_accordion/simple_accordion.dart';

如何使用

SimpleAccordion 是主要的组件,它有一个 children 参数,你可以将 AccordionHeaderItem 数组传递给它,如下所示:

SimpleAccordion(
  children: [
    AccordionHeaderItem(
      title: "Colors",
      children: [
        AccordionItem(title: "Blue"),
        AccordionItem(title: "Red"),
        AccordionItem(title: "Green"),
        AccordionItem(title: "Black"),
      ],
    ),
  ],
)

使用树结构

SimpleAccordion
	-AccordionHeaderItem
		-AccordionItem
		-AccordionItem
		-AccordionItem
	-AccordionHeaderItem
		-AccordionItem
		...

SimpleAccordion 的属性

参数 描述
children AccordionHeaderItem 数组
headerColor 设置所有头部背景颜色
itemColor 设置所有项背景颜色
maxSelectCount 用户可选择的最大数量
headerTextStyle 设置所有头部标题样式
itemTextStyle 设置所有项标题样式
onSelectedChanged 返回所有选中项的变化
selectedItems 默认选中的项

AccordionHeaderItem 的属性

参数 描述
isOpen 头部的初始状态(打开/关闭)
title 头部标题
child 头部子部件
children AccordionItem 数组
headerColor 设置头部背景颜色
itemColor 设置当前头部所有项背景颜色
headerTextStyle 设置头部标题样式
itemTextStyle 设置当前头部所有项标题样式

AccordionItem 的属性

参数 描述
title 头部标题
child 头部子部件
onChange 用于处理复选框模式值
checked 复选框的初始状态
checkColor 设置复选框颜色
itemColor 设置项背景颜色
accrodionItemType 设置项模式(标签、复选框)
itemTextStyle 设置当前项样式

所有自定义选项都可以在 example 文件 中找到。

示例代码

以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:simple_accordion/model/SimpleAccordionState.dart';
import 'package:simple_accordion/simple_accordion.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: DefaultTabController(
        length: 2,
        child: Scaffold(
            appBar: AppBar(
              title: const Text('Simple Accordion'),
              bottom: const TabBar(
                tabs: [
                  Tab(
                    text: "Simple",
                  ),
                  Tab(
                    text: "Custom",
                  )
                ],
              ),
            ),
            body: const TabBarView(children: [
              SimpleMode(),
              CustomMode(),
            ])),
      ),
    );
  }
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8),
      child: SimpleAccordion(children: [
        AccordionHeaderItem(
          title: "List of actions",
          children: [
            AccordionItem(
              title: "First Item Of List",
            ),
            AccordionItem(
              title: "Second Item Of List",
            ),
            AccordionItem(
              title: "Third Item Of List",
            )
          ],
        ),
        AccordionHeaderItem(
          title: "List of colors",
          children: [
            AccordionItem(
              title: "First Color Is Red",
            ),
            AccordionItem(
              title: "Second Color Is Blue",
            ),
          ],
        ),
        AccordionHeaderItem(
          title: "List of Cars",
          children: [
            AccordionItem(
              title: "First Car Is BMW",
            ),
          ],
        ),
        AccordionHeaderItem(
          title: "List of languages",
          children: [
            AccordionItem(
              title: "C-Sharp",
            ),
            AccordionItem(
              title: "Rust",
            ),
            AccordionItem(
              title: "JavaScript",
            ),
            AccordionItem(
              title: "Dart-Flutter",
            ),
          ],
        )
      ]),
    );
  }
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: SimpleAccordion(
        onSelectedChanged: (data) {
          print(data.map((e) => e.title).join('-'));
        },
        itemTextStyle: TextStyle(color: Colors.red),
        maxSelectCount: 2,
        selectedItems: [AccordionData(title: "Blue")],
        children: [
          AccordionHeaderItem(
            title: "Colors",
            children: [
              AccordionItem(
                title: "Blue",
                itemTextStyle: TextStyle(color: Colors.blue),
                accrodionItemType: AccrodionItemType.CheckBox,
              ),
              AccordionItem(
                  title: "Red", accrodionItemType: AccrodionItemType.CheckBox),
              AccordionItem(
                title: "Green",
                onTap: () {},
              ),
              AccordionItem(title: "Black"),
            ],
          ),
          AccordionHeaderItem(
            title: "Header 2",
            children: const [],
          ),
          AccordionHeaderItem(
            title: "Header 3",
            children: const [],
          ),
          AccordionHeaderItem(
            title: "Customized items",
            children: [
              AccordionItem(title: "Label Item (tapable)"),
              AccordionItem(
                  title: "Checkbox Item",
                  accrodionItemType: AccrodionItemType.CheckBox),
              AccordionItem(
                  title: "Checkbox Item (red check)",
                  checkColor: Colors.red,
                  accrodionItemType: AccrodionItemType.CheckBox),
              AccordionItem(
                title: "Backgrounded Item",
                itemColor: Colors.orange,
              ),
            ],
          ),
          AccordionHeaderItem(
            title: "Colored Header 1 and items",
            headerColor: Colors.lightBlue,
            itemColor: Colors.greenAccent,
            children: [
              AccordionItem(
                title: "Item 1",
              ),
              AccordionItem(
                title: "Item 2",
              ),
              AccordionItem(
                child: Container(
                  width: double.infinity,
                  margin: const EdgeInsets.only(bottom: 10),
                  padding: const EdgeInsets.all(5),
                  decoration: const BoxDecoration(
                      border: Border(bottom: BorderSide(width: 1))),
                  child: const Text(
                    "Custom Item",
                    style: TextStyle(
                        color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              AccordionItem(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    const Icon(Icons.star),
                    OutlinedButton(
                        onPressed: () {}, child: const Text("Button")),
                    const SizedBox(width: 100, height: 40, child: TextField())
                  ],
                ),
              )
            ],
          ),
          AccordionHeaderItem(
            children: [
              AccordionItem(
                child: Container(
                  padding: const EdgeInsets.all(10),
                  child: const Text(
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate, quam molestie finibus interdum, mauris tortor pretium eros, eget dignissim neque leo et mi. Etiam rutrum dapibus malesuada. Ut sem metus, tristique quis semper id, tincidunt quis elit. Aenean vel ipsum nec enim sollicitudin sollicitudin id et nibh. Donec ut ligula eros. Integer quis libero eu eros malesuada faucibus. Nullam viverra blandit placerat. Duis suscipit sagittis orci et iaculis. Sed at justo tincidunt dolor aliquam maximus. Proin condimentum mi ipsum, ut blandit purus ornare quis. Donec dignissim ut ligula non iaculis. Vestibulum consequat, enim eu egestas sodales, nunc est varius nulla, eget ullamcorper quam velit at est. Curabitur nec ex enim. In sit amet tellus ex.",
                    textAlign: TextAlign.justify,
                  ),
                ),
              )
            ],
            child: Row(
              children: const [
                Icon(Icons.arrow_forward_ios_sharp),
                SizedBox(
                  width: 5,
                ),
                Text("Custom header with custom body")
              ],
            ),
          )
        ],
      ),
    );
  }
}

更多关于Flutter折叠面板插件simple_accordion的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter折叠面板插件simple_accordion的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用simple_accordion插件来实现折叠面板效果的代码案例。首先,确保你已经在你的pubspec.yaml文件中添加了simple_accordion依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_accordion: ^latest_version  # 请替换为实际的最新版本号

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

以下是一个完整的示例,展示了如何使用simple_accordion插件:

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  // 创建一个列表来存储面板的展开状态
  final List<bool> isPanelOpen = List.filled(3, false);

  // 面板内容
  final List<String> panelContents = [
    "这是第一个面板的内容。",
    "这是第二个面板的内容。",
    "这是第三个面板的内容。",
  ];

  // 处理面板展开和折叠的函数
  void togglePanel(int index) {
    setState(() {
      isPanelOpen[index] = !isPanelOpen[index];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Simple Accordion Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: List.generate(panelContents.length, (index) {
            return AccordionPanel(
              header: Text("面板 ${index + 1}"),
              isExpanded: isPanelOpen[index],
              onHeaderClicked: () => togglePanel(index),
              body: Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: Text(panelContents[index]),
              ),
            );
          }),
        ),
      ),
    );
  }
}

代码说明

  1. 依赖导入: 在pubspec.yaml中添加simple_accordion依赖,并运行flutter pub get

  2. 创建应用: 使用MaterialApp创建一个Flutter应用,并设置主页为MyHomePage

  3. 状态管理: 在MyHomePage_MyHomePageState中,创建一个List<bool>来管理每个面板的展开状态。

  4. 面板内容: 创建一个List<String>来存储每个面板的内容。

  5. 处理展开/折叠: 定义一个togglePanel函数,该函数通过setState来更新面板的展开状态。

  6. 构建UI: 使用Column布局来排列多个AccordionPanel。每个AccordionPanel都有一个标题(header),一个展开状态(isExpanded),一个点击事件处理函数(onHeaderClicked),以及面板的内容(body)。

这样,你就完成了一个简单的Flutter应用,它使用simple_accordion插件来创建可折叠的面板。你可以根据需要调整面板的内容和样式。

回到顶部