Flutter工具集插件arcane_helper_utils的使用

Flutter工具集插件arcane_helper_utils的使用

概述

Arcane Helper Utils 是一个用于增强 Dart 开发的 Dart 包,提供了简化常见任务的实用函数和扩展。

style: arcane analysis

特性

  • Ticker Utility:一个帮助类,可以用于基于时间的操作,非常适合动画或任何与时间相关的操作。
  • JSON Converter:简化将 JSON 数据转换为 Dart 对象的过程。
  • DateTime Extensions:向 DateTime 类添加了额外的功能,使日期格式化和计算更加容易。
  • String Extensions:通过添加新的方法来增强 String 类,包括 JWT 解析。
  • List Extensions:为 List 添加了一个新的 unique 操作符来过滤列表项。

入门指南

要在您的 Dart 项目中使用此包,请将其添加到项目的 pubspec.yaml 文件中:

dependencies:
  arcane_helper_utils: any

然后在需要的地方导入它:

import 'package:arcane_helper_utils/arcane_helper_utils.dart';

使用示例

Ticker

Ticker 可以用作倒计时或间隔定时器。

final Stream<int> ticker = const Ticker().tick(
  timeout: Duration(seconds: 30),
  interval: Duration(seconds: 5)
);

await for (final int ticksRemaining in ticker) {
  if (ticksRemaining == 0) print("Time's up!");
  print('Tick! $ticksRemaining');
}

JSON 转换

这些辅助方法与 Freezed 包一起使用,用于注解需要从一种数据类型转换为另一种的数据字段。可用的转换包括:

  • String?int?
  • String?double?

假设有以下 JSON 输出:

{
  "valueIsMaybeNull": "",
  "valueIsDouble": "123.456",
  "valueIsInt": "123"
}

valueIsMaybeNull 字段将被转换为空字符串到 nullvalueIsDouble 字段将被转换为 double?valueIsInt 字段将被转换为 int?

@freezed
class MyFreezedClass with _$MyFreezedClass {
  const factory MyFreezedClass({
    @DecimalConverter() double? valueIsMaybeNull,
    @DecimalConverter() double? valueIsDouble,
    @IntegerConverter() int? valueIsInt,
  }) = _MyFreezedClass;

  factory MyFreezedClass.fromJson(Map<String, dynamic> json) => _$MyFreezedClassFromJson(json);

  const MyFreezedClass._();
}

DateTime 扩展

这些扩展为 DateTime 类添加了有用的辅助方法,使得处理常见的日期和时间操作(如格式化、比较和计算)变得更加简单。

起始和结束时间的计算

以下操作现在可以在 DateTime 对象上使用:

final DateTime dateTime = DateTime(2019, 1, 1, 13, 45);
print(dateTime); // 2019-01-01T13:45:00.0
print(dateTime.startOfHour); // 2019-01-01T13:00:00.0
final DateTime dateTime = DateTime(2019, 1, 1, 13, 45);
print(dateTime); // 2019-01-01T13:45:00.0
print(dateTime.endOfHour); // 2019-01-01T13:59:59.999
final DateTime dateTime = DateTime(2019, 1, 1, 13, 45);
print(dateTime); // 2019-01-01T13:45:00.0
print(dateTime.startOfDay); // 2019-01-01T00:00:00.0
final DateTime dateTime = DateTime(2019, 1, 1, 13, 45);
print(dateTime); // 2019-01-01T13:45:00.0
print(dateTime.endOfDay); // 2019-01-01T23:59:59.9
final DateTime dateTime = DateTime(2023, 9, 10);
print(dateTime); // 2023-09-10
print(dateTime.startOfWeek); // 2023-09-04
final DateTime dateTime = DateTime(2023, 9, 10);
print(dateTime); // 2023-09-10
print(dateTime.endOfWeek); // 2023-09-17T23:59:59.999999
final DateTime dateTime = DateTime(2023, 9, 10);
print(dateTime); // 2023-09-10
print(dateTime.startOfMonth); // 2023-09-01T00:00:00.0
final DateTime dateTime = DateTime(2023, 9, 10);
print(dateTime); // 2023-09-10
print(dateTime.endOfMonth); // 2023-09-30T23:59:59.999999
final DateTime dateTime = DateTime(2023, 9, 10);
print(dateTime); // 2023-09-10
print(dateTime.startOfYear); // 2023-01-01T00:00:00.0
final DateTime dateTime = DateTime(2023, 9, 10);
print(dateTime); // 2023-09-10
print(dateTime.endOfYear); // 2023-12-31T23:59:59.999999

比较操作

final DateTime today = DateTime(2024, 9, 10);
final bool notToday = DateTime(2001, 12, 31).isToday; // false
final DateTime first = DateTime(2001, 1, 1);
final DateTime second = DateTime(2001, 1, 2);
final DateTime third = DateTime(2001, 1, 1);

final bool firstAndSecond = first.isSameDayAs(second); // false
final bool firstAndThird = first.isSameDayAs(third); // true

周期信息操作

final int daysInMonth = DateTime(2024, 9).daysInMonth; // 30
final DateTime today = DateTime(2024, 9, 10); // Tuesday
final DateTime sunday = today.firstDayOfWeek; // Sunday

昨天和明天的获取

final DateTime now = DateTime.now(); // 2024-10-07 13:37:48.274
final DateTime yesterday = DateTime(0).yesterday; // 2024-10-06 00:00:00.000
final DateTime now = DateTime.now(); // 2024-10-07 13:37:48.274
final DateTime tomorrow = DateTime(0).tomorrow; // 2024-10-08 00:00:00.000

JWT 解析

这些扩展增强了 String 类的 JWT 特定功能,使得直接作为 String 对象处理 JSON Web Token 更加容易。

String jwt = "your.jwt.token";
final String? email = jwt.jwtEmail(); // 返回 JWT 中的电子邮件地址
String jwt = "your.jwt.token";
final DateTime? expiryTime = jwt.jwtExpiryTime(); // 返回 JWT 的过期时间
String jwt = "your.jwt.token";
final String? userId = jwt.jwtUserId(); // 返回 JWT 中的用户 ID

字符串实用程序

以下实用程序用于增强 String 对象的工作:

const String? nullString = null;
const String? emptyString = " ";
const String? nonEmptyString = "Hello World!";

print(nullString.isNullOrEmpty) // true
print(emptyString.isNullOrEmpty) // true
print(nonEmptyString.isNullOrEmpty) // false
const String? nullString = null;
const String? emptyString = " ";
const String? nonEmptyString = "Hello World!";

print(nullString.isNotNullOrEmpty) // false
print(emptyString.isNotNullOrEmpty) // false
print(nonEmptyString.isNotNullOrEmpty) // true
const String text = "DartLang";
final List<String> result = text.splitByLength(3); // ["Dar", "tLa", "ng"]
const String text = "hello";
final String capitalized = text.capitalize; // "Hello"
String text = "hello world";
String capitalizedWords = text.capitalizeWords; // "Hello World"
String text = "ArcaneHelperUtils";
String spaced = text.spacePascalCase; // "Arcane Helper Utils"

列表扩展

以下扩展已添加到 List 对象:

final list = [1, 2, 2, 3, 4, 4];
final uniqueList = list.unique();
print(uniqueList); // 输出: [1, 2, 3, 4]
final people = [
  Person(id: 1, name: 'Alice'),
  Person(id: 2, name: 'Bob'),
  Person(id: 1, name: 'Alice Duplicate'),
];

final uniquePeople = people.unique((person) => person.id);
print(uniquePeople.map((p) => p.name)); // 输出: ['Alice', 'Bob']
final List<Person> people = [
  const Person(id: 1, name: "Alice"),
  const Person(id: 2, name: "Bob"),
  const Person(id: 1, name: "Alice Duplicate"),
];

final List<Person> uniquePeople = people.unique((person) => person.id, false);
print(people.map((p) => p.name)); // 输出: ['Alice', 'Bob', 'Alice Duplicate']
print(uniquePeople.map((p) => p.name)); // 输出: ['Alice', 'Bob']
final String alice = const Person(id: 0, name: "Alice").printValue<Person>().name;
print(alice); // 输出: 'Alice'
final String bob = const Person(id: 1, name: "Bob").printValue<Person>("Person").name;
print(bob); // 输出: 'Bob'
class Person {
  final int id;
  final String name;

  const Person({required this.id, required this.name});
}

更多关于Flutter工具集插件arcane_helper_utils的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter工具集插件arcane_helper_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中集成和使用arcane_helper_utils插件的示例代码。请注意,arcane_helper_utils是一个假设的插件名称,实际使用时请替换为真实存在的插件名称及其功能。假设这个插件提供了一些常用的工具函数,比如字符串处理、日期格式化等。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  arcane_helper_utils: ^x.y.z  # 替换为实际的版本号

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

2. 导入插件

在你需要使用该插件的Dart文件中导入它。

import 'package:arcane_helper_utils/arcane_helper_utils.dart';

3. 使用插件的功能

假设arcane_helper_utils插件提供了以下功能:

  • capitalizeFirstLetter(String input): 将输入字符串的首字母大写。
  • formatDate(DateTime date, String format): 格式化日期。

下面是如何使用这些功能的示例代码:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Arcane Helper Utils Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Capitalized String: ${capitalizeFirstLetter("hello world")}',
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(height: 20),
              Text(
                'Formatted Date: ${formatDate(DateTime.now(), "yyyy-MM-dd HH:mm:ss")}',
                style: TextStyle(fontSize: 20),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 假设插件中的函数实现如下(实际使用时请忽略这部分,因为这部分是插件内部的实现)
// 以下是示例代码,仅用于说明如何使用这些功能,并非真实插件代码
extension ArcaneHelperUtils on String {
  String capitalizeFirstLetter() {
    if (isEmpty) return this;
    return "${this[0].toUpperCase()}${substring(1)}";
  }
}

String formatDate(DateTime date, String format) {
  // 这里使用简单的日期格式化作为示例,实际插件可能会使用更复杂的库
  var dateFormat = {
    "yyyy": date.year.toString(),
    "MM": (date.month + 1).toString().padStart(2, '0'),
    "dd": date.day.toString().padStart(2, '0'),
    "HH": date.hour.toString().padStart(2, '0'),
    "mm": date.minute.toString().padStart(2, '0'),
    "ss": date.second.toString().padStart(2, '0'),
  };
  
  return format.replaceAll(RegExp(r'\b(\w{2,4})\b'), (match) {
    return dateFormat[match.group(0)!] ?? match.group(0)!;
  });
}

注意事项

  1. 实际插件的API:上面的capitalizeFirstLetterformatDate函数是假设的,实际使用时请参考arcane_helper_utils插件的官方文档来了解其提供的API。
  2. 插件版本:确保你使用的是最新版本的插件,以避免已知的bug和兼容性问题。
  3. 错误处理:在实际应用中,添加适当的错误处理逻辑,比如处理空值、异常等。

希望这个示例代码能帮助你在Flutter项目中集成和使用arcane_helper_utils插件!

回到顶部