Flutter数据多条件排序插件multi_sort的使用

multi_sort #

一个快速且强大的Flutter包,可以帮助你一次性根据一个或多个属性对对象列表进行排序。


为什么选择multi_sort?#

假设你有一个手机列表,并希望根据其规格(如RAM、存储、价格、摄像头等)同时进行排序,类似于Microsoft Excel中的排序功能。

例如,假设我有以下手机列表:

List<Phone> items = [
    Phone("real me 6", 6, 18999, 128),
    Phone("real me 6", 8, 19999, 128),
    Phone("real Note 8", 7, 16999, 128),
    Phone("oppo a9", 4, 13999, 128),
    Phone("real me 6 pro", 6, 17999, 64),
    Phone("Oppo 5as", 2, 8999, 32),
    Phone("Real me 5i", 4, 10999, 64),
    Phone("Poco x2", 6, 18500, 128),
];

在按RAM优先排序,然后按存储排序后,结果将是:

[
    Phone("real me 6", 8, 19999, 128),
    Phone("real Note 8", 7, 16999, 128),
    Phone("real me 6", 6, 18999, 128),
    Phone("Poco x2", 6, 18500, 128),
    Phone("real me 6 pro", 6, 17999, 64),
    Phone("oppo a9", 4, 13999, 128),
    Phone("Oppo 5as", 2, 8999, 32),
    Phone("Real me 5i", 4, 10999, 64),
]

通过这个Flutter插件,你可以非常方便地实现这种偏好排序/多重排序/多级排序。


安装 #

1. 添加依赖项

在你的pubspec.yaml文件中添加以下内容:

dependencies:
  multi_sort: ^3.0.0

2. 安装依赖项

从命令行安装依赖项:

使用Flutter命令:

$ flutter pub get

或者,如果你的编辑器支持,可以直接通过IDE安装。

3. 导入插件

在Dart代码中导入插件:

import 'package:multi_sort/multi_sort.dart';

使用说明 #

初始化

List<dynamic> list; // 要排序的列表
List<bool> criteria; // 排序规则(true为升序,false为降序)
List<String> preference; // 排序优先级列表

排序列表

list.multisort(criteria, preference);

示例代码 #

以下是完整的示例代码:

import 'package:flutter/material.dart';
import "package:multi_sort/multi_sort.dart";

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

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

class ExampleApp extends StatefulWidget {
  ExampleApp({Key key}) : super(key: key);

  @override
  _ExampleAppState createState() => _ExampleAppState();
}

/// 定义一个Item类
class Items {
  String name;
  int ram;
  int price;
  int storage;
  Items(this.name, this.ram, this.price, this.storage);

  /// 将对象映射为Map
  Map<String, dynamic> _toMap() {
    return {'name': name, 'price': price, 'ram': ram, 'storage': storage};
  }

  /// 获取对象的属性值
  dynamic get(String propertyName) {
    var _mapRep = _toMap();
    if (_mapRep.containsKey(propertyName)) {
      return _mapRep[propertyName];
    }
    throw ArgumentError('属性未找到');
  }
}

class _ExampleAppState extends State<ExampleApp> {
  // 定义一个Items列表
  List<Items> items = [
    Items("real me 6", 6, 18999, 128),
    Items("real me 6", 8, 19999, 128),
    Items("real Note 8", 7, 16999, 128),
    Items("oppo a9", 4, 13999, 128),
    Items("real me 6 pro", 6, 17999, 64),
    Items("Oppo 5as", 2, 8999, 32),
    Items("Real me 5i", 4, 10999, 64),
    Items("Poco x2", 6, 18500, 128),
  ];

  // 临时列表用于排序
  List<Items> sortingList = [];

  // 排序规则列表
  List<bool> criteria = [false, false];

  // 排序优先级列表
  List<String> preference = ['ram', 'storage'];

  @override
  void initState() {
    super.initState();
    setState(() {
      sortingList = items;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("排序示例"),
      ),
      body: Column(
        children: [
          _buttons(), // 排序按钮
          ListView.builder(
            shrinkWrap: true,
            itemCount: sortingList.length,
            itemBuilder: (BuildContext context, int i) {
              return Card(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(sortingList[i].name), // 名称
                    Text(sortingList[i].price.toString()), // 价格
                    Text(sortingList[i].ram.toString()), // RAM
                    Text(sortingList[i].storage.toString()), // 存储
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buttons() {
    return ElevatedButton(
      onPressed: () {
        setState(() {
          /// 使用MultiSort进行排序
          sortingList.multisort(criteria, preference);
        });
      },
      child: Text('按优先级排序'),
    );
  }
}

许可证 #

multi_sort 的许可证为 MIT 许可证

MIT License

Copyright (c) 2020 Deependra Chansoliya

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数据多条件排序插件multi_sort的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据多条件排序插件multi_sort的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,multi_sort 是一个用于多条件排序的插件,它允许你根据多个条件对数据进行排序。这个插件非常适用于需要对复杂数据结构进行排序的场景。

安装 multi_sort 插件

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

dependencies:
  flutter:
    sdk: flutter
  multi_sort: ^1.0.0  # 请检查最新版本

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

使用 multi_sort 插件

假设你有一个包含多个字段的数据列表,并且你想根据多个条件对其进行排序。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Multi-Sort Example'),
        ),
        body: MultiSortExample(),
      ),
    );
  }
}

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

class _MultiSortExampleState extends State<MultiSortExample> {
  List<Map<String, dynamic>> data = [
    {'name': 'Alice', 'age': 25, 'score': 90},
    {'name': 'Bob', 'age': 30, 'score': 85},
    {'name': 'Charlie', 'age': 25, 'score': 95},
    {'name': 'David', 'age': 30, 'score': 80},
  ];

  void sortData() {
    setState(() {
      data = multiSort(data, [
        (a, b) => a['age'].compareTo(b['age']), // 先按年龄升序排序
        (a, b) => b['score'].compareTo(a['score']), // 再按分数降序排序
      ]);
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Column(
      children: [
        ElevatedButton(
          onPressed: sortData,
          child: Text('Sort Data'),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: data.length,
            itemBuilder: (context, index) {
              final item = data[index];
              return ListTile(
                title: Text(item['name']),
                subtitle: Text('Age: ${item['age']}, Score: ${item['score']}'),
              );
            },
          ),
        ),
      ],
    );
  }
}
回到顶部