Flutter自动排序包装组件插件auto_sort_wrap_widget的使用

Flutter自动排序包装组件插件auto_sort_wrap_widget的使用

auto_sort_wrap_widget 是一个用于自动排列布局的小部件插件。它能够像俄罗斯方块一样自动调整布局,适合在小屏幕上展示更多的数据。

示例效果

使用默认 Flutter 小部件的结果

final data = ['show me the money', 'asbcdef', '1234567890', 'hi', 'love'];

Wrap(
  runSpacing: 5,
  spacing: 5,
  children: List.generate(data.length, (index) => _getItem(data[index])),
)

默认 Flutter 小部件结果

使用 AutoSortWrapWidget 的结果

final data = ['show me the money', 'asbcdef', '1234567890', 'hi', 'love'];

AutoSortWrapWidget<String>(
  data: data,
  runSpacing: 5,
  spacing: 5,
  itemBuilder: (context, index, data) => _getItem(data)
);

AutoSortWrapWidget 结果

数据类型为 Widget 的结果

final data = ['show me the money', 'asbcdef', '1234567890', 'hi', 'love'];

AutoSortWrapWidget<Widget>(
  data: List.generate(data.length, (index) => _getItem(data[index])),
  runSpacing: 5,
  spacing: 5,
  itemBuilder: (context, index, data) => Container(
    child: data,
    padding: const EdgeInsets.all(5.0),
    color: Colors.blueAccent,
  ),
);

Widget 类型结果

使用说明

初始化项目

首先,在 pubspec.yaml 文件中添加依赖:

dependencies:
  auto_sort_wrap_widget: ^1.0.0

然后运行以下命令安装依赖:

flutter pub get

示例代码

以下是一个完整的示例代码,展示了如何使用 AutoSortWrapWidget 插件。

示例代码

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AutoSortWrapWidget Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'AutoSortWrapWidget Demo'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  final List<String> data = [
    'spent',
    'life',
    'suffocating',
    'Ignoring',
    'villains',
    'living',
    'Will',
    'Under',
    'Will you stay a part of me',
    'You’re killing me from within'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(30.0),
              child: Container(
                color: Colors.amber.withOpacity(0.3),
                child: AutoSortWrapWidget<String>(
                  data: data,
                  runSpacing: 5,
                  spacing: 5,
                  itemBuilder: (context, index, aa) {
                    return Container(
                      padding: EdgeInsets.all(5.0),
                      decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: const BorderRadius.all(
                          Radius.circular(40),
                        ),
                        boxShadow: const [
                          BoxShadow(
                            color: Colors.white10,
                            offset: Offset(4.0, 4.0),
                            blurRadius: 15.0,
                            spreadRadius: 1.0,
                          ),
                          BoxShadow(
                            color: Colors.white,
                            offset: Offset(-4.0, -4.0),
                            blurRadius: 15.0,
                            spreadRadius: 1.0,
                          ),
                        ],
                      ),
                      child: Text(aa,
                        style: TextStyle(fontSize: 15),
                        maxLines: 10,
                        overflow: TextOverflow.ellipsis,
                        softWrap: true,
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

运行效果

运行上述代码后,您将看到一个自动排序的小部件,类似于俄罗斯方块的效果。每个文本块会根据其长度自动调整位置,从而更有效地利用屏幕空间。

注意事项

  • AutoSortWrapWidget 的数据类型可以是 TWidget
  • 如果数据项的大小不同,AutoSortWrapWidget 会自动重新排列以优化布局。
  • 可以通过 runSpacingspacing 参数调整行间距和列间距。

MIT 许可证

Copyright (c) 2018 Simon Leier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

更多关于Flutter自动排序包装组件插件auto_sort_wrap_widget的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自动排序包装组件插件auto_sort_wrap_widget的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


auto_sort_wrap_widget 是一个用于 Flutter 的插件,它可以帮助你自动排序并包装子组件。这个插件非常适合用于需要动态排序和自动换行的场景,比如标签云、动态筛选器等。

安装

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

dependencies:
  auto_sort_wrap_widget: ^0.1.0  # 请使用最新版本

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

基本使用

AutoSortWrapWidget 是一个包装组件,它可以自动根据子组件的大小进行排序和换行。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('AutoSortWrapWidget Example'),
        ),
        body: AutoSortWrapWidget(
          children: List.generate(10, (index) {
            return Chip(
              label: Text('Item $index'),
            );
          }),
        ),
      ),
    );
  }
}

参数说明

AutoSortWrapWidget 提供了多个参数来控制其行为:

  • children: 需要排序和包装的子组件列表。
  • spacing: 子组件之间的水平间距。
  • runSpacing: 行之间的垂直间距。
  • alignment: 子组件的对齐方式。
  • runAlignment: 行的对齐方式。
  • crossAxisAlignment: 交叉轴的对齐方式。
  • direction: 子组件的排列方向,默认为水平方向。
  • textDirection: 文本方向,影响子组件的排列顺序。
  • verticalDirection: 垂直方向,影响子组件的排列顺序。

自定义排序

你可以通过 sortAlgorithm 参数来自定义排序算法。默认情况下,AutoSortWrapWidget 会根据子组件的大小自动排序。以下是一个自定义排序的示例:

AutoSortWrapWidget(
  children: List.generate(10, (index) {
    return Chip(
      label: Text('Item $index'),
    );
  }),
  sortAlgorithm: (List<Widget> children) {
    // 自定义排序逻辑
    children.sort((a, b) {
      // 根据标签文本长度排序
      final aText = (a as Chip).label as Text;
      final bText = (b as Chip).label as Text;
      return aText.data!.length.compareTo(bText.data!.length);
    });
    return children;
  },
);

动态添加和删除子组件

AutoSortWrapWidget 支持动态添加和删除子组件。你可以通过 setState 来更新 children 列表:

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> items = List.generate(5, (index) {
    return Chip(
      label: Text('Item $index'),
    );
  });

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('AutoSortWrapWidget Example'),
        ),
        body: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                setState(() {
                  items.add(Chip(label: Text('Item ${items.length}')));
                });
              },
              child: Text('Add Item'),
            ),
            AutoSortWrapWidget(
              children: items,
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部