Flutter多功能工具插件the_utils的使用
Flutter 多功能工具插件 the_utils 的使用
The Utils
the_utils
是一个 Dart 和 Flutter 的实用工具库。
import 'package:the_utils/the_utils.dart';
String Utils
the_utils
提供了丰富的字符串处理方法。以下是一些常用的方法示例:
示例代码
import 'package:the_utils/the_utils.dart';
void main() {
// 检查字符串是否为 IPv4 地址
var isIPv4 = StrUtil.isIPv4("192.168.1.1");
print(isIPv4); // 输出: true
// 将字符串首字母大写
var capitalized = StrUtil.capitalize("hello world");
print(capitalized); // 输出: Hello world
// 检查字符串是否包含中文字符
var containsChinese = StrUtil.containsChinese("你好世界");
print(containsChinese); // 输出: true
// 统计特定字符在字符串中的出现次数
var charCount = StrUtil.countCharOccurrences("hello", "l");
print(charCount); // 输出: 2
// 将字符串转换为驼峰命名格式
var camelCaseStr = StrUtil.camelCase("hello_world");
print(camelCaseStr); // 输出: helloWorld
// 检查字符串是否以特定子串结尾
var endsWith = StrUtil.endsWith("hello world", "world");
print(endsWith); // 输出: true
// 转义 HTML 特殊字符
var escapedHtml = StrUtil.escapeHtml("<div>hello</div>");
print(escapedHtml); // 输出: <div>hello</div>
// 从字符串中提取数字
var extractedNumbers = StrUtil.extractNumbers("abc123def456");
print(extractedNumbers); // 输出: [123, 456]
// 解码 Base64 字符串
var decodedBase64 = StrUtil.fromBase64("SGVsbG8gd29ybGQ=");
print(decodedBase64); // 输出: Hello world
// 格式化数字为逗号分隔形式
var formattedNumber = StrUtil.formatNumberWithCommas("123456789");
print(formattedNumber); // 输出: 123,456,789
// 获取字符串的哈希码
var hashCode = StrUtil.getHashCode("hello");
print(hashCode); // 输出: 哈希码值
// 检查字符串中的字符是否按字母顺序排列
var isZAlphabetical = StrUtil.isZAlphabetical("abc");
print(isZAlphabetical); // 输出: true
// 检查字符串是否为有效的十六进制数
var isHex = StrUtil.isHex("1A2B3C");
print(isHex); // 输出: true
// 检查字符串是否只包含字母
var isAlpha = StrUtil.isAlpha("hello");
print(isAlpha); // 输出: true
// 检查字符串是否只包含字母和数字
var isAlphanumeric = StrUtil.isAlphanumeric("hello123");
print(isAlphanumeric); // 输出: true
// 检查字符串是否只包含数字
var isNumeric = StrUtil.isNumeric("12345");
print(isNumeric); // 输出: true
// 检查字符串是否为有效的 URL
var isUrl = StrUtil.isUrl("https://example.com");
print(isUrl); // 输出: true
// 检查字符串是否为有效的电子邮件地址
var isEmail = StrUtil.isEmail("test@example.com");
print(isEmail); // 输出: true
// 检查字符串是否为有效的 Flutter 资源路径
var isAsset = StrUtil.isAsset("assets/images/image.png");
print(isAsset); // 输出: true
// 检查字符串是否只包含数字
var isDigitOnly = StrUtil.isDigitOnly("12345");
print(isDigitOnly); // 输出: true
// 检查字符串是否只包含空白字符和换行符
var isWhitespace = StrUtil.isWhitespace(" \n\t");
print(isWhitespace); // 输出: true
// 检查字符串是否为空
var isEmpty = StrUtil.isEmpty("");
print(isEmpty); // 输出: true
// 检查字符串是否为 null 或空
var isNullOrEmpty = StrUtil.isNullOrEmpty(null);
print(isNullOrEmpty); // 输出: true
// 检查字符串是否为 null、空或只包含空白字符
var isNullEmptyOrWhitespace = StrUtil.isNullEmptyOrWhitespace(" ");
print(isNullEmptyOrWhitespace); // 输出: true
// 检查字符串是否为有效的用户名
var isValidUsername = StrUtil.isValidUsername("user_name");
print(isValidUsername); // 输出: true
// 检查字符串是否不为空
var isNotEmpty = StrUtil.isNotEmpty("hello");
print(isNotEmpty); // 输出: true
// 检查字符串是否只包含空格
var isBlank = StrUtil.isBlank(" ");
print(isBlank); // 输出: true
// 检查字符串中的所有字符是否都是小写字母
var isLowerCase = StrUtil.isLowerCase("hello");
print(isLowerCase); // 输出: true
// 检查字符串中的所有字符是否都是大写字母
var isUpperCase = StrUtil.isUpperCase("HELLO");
print(isUpperCase); // 输出: true
// 检查字符串是否为回文
var isPalindrome = StrUtil.isPalindrome("racecar");
print(isPalindrome); // 输出: true
// 检查字符串是否为有效的日期时间格式
var isDateTime = StrUtil.isDateTime("2023-12-01 06:50");
print(isDateTime); // 输出: true
// 检查字符串是否为有效的信用卡号码
var isCreditCard = StrUtil.isCreditCard("4111111111111111");
print(isCreditCard); // 输出: true
// 检查字符串是否为有效的文件路径
var isFilePath = StrUtil.isFilePath("/path/to/file.txt");
print(isFilePath); // 输出: true
// 检查字符串是否为有效的 IPv4 地址
var isIPv4 = StrUtil.isIPv4("192.168.1.1");
print(isIPv4); // 输出: true
// 检查字符串是否为有效的 IPv6 地址
var isIPv6 = StrUtil.isIPv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
print(isIPv6); // 输出: true
// 检查字符串是否符合 Base64 格式
var isBase64 = StrUtil.isBase64("SGVsbG8gd29ybGQ=");
print(isBase64); // 输出: true
// 检查字符串是否为有效的 JSON 格式
var isJson = StrUtil.isJson("{\"name\": \"John\"}");
print(isJson); // 输出: true
// 检查字符串是否符合电话号码格式
var isPhoneNumber = StrUtil.isPhoneNumber("+1234567890");
print(isPhoneNumber); // 输出: true
// 检查字符串是否符合简单的密码规则
var isSimplePassword = StrUtil.isSimplePassword("password123");
print(isSimplePassword); // 输出: true
// 检查字符串是否只包含空格字符
var isSpace = StrUtil.isSpace(" ");
print(isSpace); // 输出: true
// 检查字符串是否为有效的车牌号码
var isLicensePlate = StrUtil.isLicensePlate("ABC123");
print(isLicensePlate); // 输出: true
// 将字符串转换为 kebab-case 格式
var kebabCaseStr = StrUtil.kebabCase("Hello World");
print(kebabCaseStr); // 输出: hello-world
// 将字符串中的特定单词替换为其小写形式
var lowercaseWords = StrUtil.lowercaseWords("HELLO WORLD", {"HELLO": "hello"});
print(lowercaseWords); // 输出: hello WORLD
// 将字符串中每个单词的首字母转换为小写
var lowercaseFirstLetterOfEachWord = StrUtil.lowercaseFirstLetterOfEachWord("HELLO WORLD");
print(lowercaseFirstLetterOfEachWord); // 输出: hello world
// 检查字符串是否匹配指定的正则表达式
var matchesPattern = StrUtil.matchesPattern("hello123", r"\w+");
print(matchesPattern); // 输出: true
// 将字符串重复 n 次
var nTimesRepeat = StrUtil.nTimesRepeat("hello", 3);
print(nTimesRepeat); // 输出: hellohellohello
// 从字符串中提取数字
var onlyDigits = StrUtil.onlyDigits("abc123def456");
print(onlyDigits); // 输出: 123456
// 在字符串左侧填充指定长度
var padLeft = StrUtil.padLeft("123", 5, "0");
print(padLeft); // 输出: 00123
// 在字符串右侧填充指定长度
var padRight = StrUtil.padRight("123", 5, "0");
print(padRight); // 输出: 12300
// 将字符串重复指定次数
var repeat = StrUtil.repeat("hello", 3);
print(repeat); // 输出: hellohellohello
// 生成随机字符串
var randomString = StrUtil.randomString(10);
print(randomString); // 输出: 随机字符串
// 替换字符串中的子串
var replace = StrUtil.replace("hello world", "world", "universe");
print(replace); // 输出: hello universe
// 替换字符串中的特定单词
var replaceWords = StrUtil.replaceWords("hello world", {"world": "universe"});
print(replaceWords); // 输出: hello universe
// 使用回调函数替换字符串中的特定模式
var replaceWithCallback = StrUtil.replaceWithCallback("hello world", r"\b\w+\b", (match) => match.toUpperCase());
print(replaceWithCallback); // 输出: HELLO WORLD
// 移除字符串中的特定子串
var removeSubstring = StrUtil.removeSubstring("hello world", "world");
print(removeSubstring); // 输出: hello
// 移除字符串中的所有非数字字符
var removeNonNumeric = StrUtil.removeNonNumeric("abc123def456");
print(removeNonNumeric); // 输出: 123456
// 移除字符串中的 HTML 标签
var removeHtmlTags = StrUtil.removeHtmlTags("<div>hello</div>");
print(removeHtmlTags); // 输出: hello
// 使用指定的映射字符替换字符串中的每个字符
var replaceChars = StrUtil.replaceChars("hello", {"h": "H", "e": "E", "l": "L", "o": "O"});
print(replaceChars); // 输出: HELLO
// 替换字符串中的特定单词
var replaceWord = StrUtil.replaceWord("hello world", "world", "universe");
print(replaceWord); // 输出: hello universe
// 移除字符串中的所有数字
var removeDigits = StrUtil.removeDigits("abc123def456");
print(removeDigits); // 输出: abcdef
// 反转字符串
var reverse = StrUtil.reverse("hello");
print(reverse); // 输出: olleh
// 将字符串转换为反转的蛇形命名格式
var reverseSnakeCase = StrUtil.reverseSnakeCase("hello_world");
print(reverseSnakeCase); // 输出: world_hello
// 移除字符串中的特定字符
var removeChar = StrUtil.removeChar("hello", "l");
print(removeChar); // 输出: heo
// 移除字符串中的所有空格
var removeSpaces = StrUtil.removeSpaces("hello world");
print(removeSpaces); // 输出: helloworld
// 将字符串中的多个空格替换为单个空格
var replaceMultipleSpacesWithSingle = StrUtil.replaceMultipleSpacesWithSingle("hello world");
print(replaceMultipleSpacesWithSingle); // 输出: hello world
// 移除字符串中的中文字符
var removeChinese = StrUtil.removeChinese("你好世界");
print(removeChinese); // 输出:
// 替换字符串中的换行符
var replaceNewLines = StrUtil.replaceNewLines("hello\nworld", "\n", "-");
print(replaceNewLines); // 输出: hello-world
// 将字符串转换为反转的驼峰命名格式
var reverseCamelCase = StrUtil.reverseCamelCase("helloWorld");
print(reverseCamelCase); // 输出: hello_world
// 生成随机的字母字符串
var randomAlphabetic = StrUtil.randomAlphabetic(10);
print(randomAlphabetic); // 输出: 随机字母字符串
// 从指定位置提取指定长度的子串
var substringFromIndex = StrUtil.substringFromIndex("hello world", 6, 5);
print(substringFromIndex); // 输出: world
// 将字符串转换为蛇形命名格式
var snakeCase = StrUtil.snakeCase("helloWorld");
print(snakeCase); // 输出: hello_world
// 按字典顺序排序字符串中的所有单词
var sortWords = StrUtil.sortWords("world hello");
print(sortWords); // 输出: hello world
// 按字母顺序排序字符串中的所有单词
var sortAlphabetically = StrUtil.sortAlphabetically("world hello");
print(sortAlphabetically); // 输出: hello world
// 将字符串拆分为指定长度的子串
var splitIntoChunks = StrUtil.splitIntoChunks("hello world", 3);
print(splitIntoChunks); // 输出: [hel, lo ,wor, ld]
// 使用指定分隔符将字符串转换为列表
var splitByDelimiter = StrUtil.splitByDelimiter("hello,world", ",");
print(splitByDelimiter); // 输出: [hello, world]
// 使用换行符将字符串转换为列表
var splitByNewLine = StrUtil.splitByNewLine("hello\nworld");
print(splitByNewLine); // 输出: [hello, world]
// 将字符串中的每个单词首字母大写
var titleize = StrUtil.titleize("hello world");
print(titleize); // 输出: Hello World
// 将字符串转换为其 ASCII 码表示
var toAsciiString = StrUtil.toAsciiString("hello");
print(toAsciiString); // 输出: 104 101 108 108 111
// 将字符串转换为零宽字符表示
var toZeroWidthString = StrUtil.toZeroWidthString("hello");
print(toZeroWidthString); // 输出: 零宽字符表示
// 将字符串转换为缩略词形式
var toAcronym = StrUtil.toAcronym("hello world");
print(toAcronym); // 输出: HW
// 将字符串转换为其二进制表示
var toBinaryString = StrUtil.toBinaryString("hello");
print(toBinaryString); // 输出: 二进制表示
// 将字符串转换为安全的文件名(移除非法字符)
var toSafeFileName = StrUtil.toSafeFileName("hello*world");
print(toSafeFileName); // 输出: helloworld
// 将字符串转换为忽略小写单词的标题格式
var toTitleCaseIgnoringSmallWords = StrUtil.toTitleCaseIgnoringSmallWords("hello world");
print(toTitleCaseIgnoringSmallWords); // 输出: Hello World
// 将字符串转换为 Base64 编码
var toBase64 = StrUtil.toBase64("hello");
print(toBase64); // 输出: SGVsbG8=
// 将字符串转换为布尔值
var toBoolean = StrUtil.toBoolean("true");
print(toBoolean); // 输出: true
// 将字符串转换为 URL 友好的格式
var toSlug = StrUtil.toSlug("hello world");
print(toSlug); // 输出: hello-world
// 从字符串的开头和结尾修剪指定字符
var trimCharFromEnds = StrUtil.trimCharFromEnds("abcabc", "c");
print(trimCharFromEnds); // 输出: abca
// 截断字符串到指定长度
var truncate = StrUtil.truncate("hello world", 5);
print(truncate); // 输出: hello
// 将字符串转换为整数类型
var toInt = StrUtil.toInt("123");
print(toInt); // 输出: 123
// 将字符串转换为列表,每个元素是一个字符
var toList = StrUtil.toList("hello");
print(toList); // 输出: [h, e, l, l, o]
// 将字符串转换为双精度浮点数类型
var toDouble = StrUtil.toDouble("123.45");
print(toDouble); // 输出: 123.45
// 将字符串转换为日期时间对象
var toDate = StrUtil.toDate("2023-12-01 06:50");
print(toDate); // 输出: 2023-12-01 06:50:00.000
// 从字符串的开头和结尾修剪指定字符
var trimChar = StrUtil.trimChar("abcabc", "c");
print(trimChar); // 输出: abab
// 将字符串中的特定单词转换为大写
var uppercaseWord = StrUtil.uppercaseWord("hello world", "world");
print(uppercaseWord); // 输出: hello WORLD
// 还原转义的 HTML 字符串
var unescapeHtml = StrUtil.unescapeHtml("<div>hello</div>");
print(unescapeHtml); // 输出: <div>hello</div>
// 计算字符串的 UTF-8 字节长度
var utf8Length = StrUtil.utf8Length("hello");
print(utf8Length); // 输出: 字节长度
// 验证字符串是否符合指定的正则表达式
var validateRegex = StrUtil.validateRegex("hello123", r"\w+");
print(validateRegex); // 输出: true
// 使用指定分隔符连接字符串中的单词
var wordsJoinWithSeparator = StrUtil.wordsJoinWithSeparator("hello world", "-");
print(wordsJoinWithSeparator); // 输出: hello-world
// 将字符串转换为小写并用破折号替换所有空格
var xToDash = StrUtil.xToDash("Hello World");
print(xToDash); // 输出: hello-world
// 格式化年份
var yearFormat = StrUtil.yearFormat("2023");
print(yearFormat); // 输出: 2023
// 将字符串转换为 Yes/No 表示
var yesOrNo = StrUtil.yesOrNo("true");
print(yesOrNo); // 输出: Yes
// 将两个字符串压缩成一对列表
var zip = StrUtil.zip(["hello", "world"], ["1", "2"]);
print(zip); // 输出: [(hello, 1), (world, 2)]
// 将字符串转换为零宽空间编码形式
var zeroWidthEncode = StrUtil.zeroWidthEncode("hello");
print(zeroWidthEncode); // 输出: 零宽空间编码形式
// 解码原始字符串
var zeroWidthDecode = StrUtil.zeroWidthDecode("零宽空间编码形式");
print(zeroWidthDecode); // 输出: hello
// 应用简单的压缩算法
var zipCompress = StrUtil.zipCompress("hellohellohello");
print(zipCompress); // 输出: h3l
// 解压字符串
var zipDecompress = StrUtil.zipDecompress("h3l");
print(zipDecompress); // 输出: hellohellohello
// 将字符串转换为键值对的映射
var zipToMap = StrUtil.zipToMap("key1=value1,key2=value2", "=");
print(zipToMap); // 输出: {key1: value1, key2: value2}
}
Date Time Utils
the_utils
还提供了处理日期时间的功能。以下是一些常用的方法示例:
示例代码
import 'package:the_utils/the_utils.dart';
void main() {
// 使用指定的日期时间字符串初始化
var dt = DT('2023-12-01 06:50');
// 设置日期时间为明天同一时刻
dt.nextDay();
// 打印日期时间
dt.printDateTime(); // 输出: 2023-12-02 06:50:00
// 设置日期时间为昨天同一时刻
dt.lastDay();
dt.printDateTime(); // 输出: 2023-12-01 06:50:00
// 向后移动 5 分钟
dt.previousNMinutes(5);
dt.printDateTime(); // 输出: 2023-12-01 06:45:00
// 向前移动 5 分钟
dt.nextNMinutes(5);
dt.printDateTime(); // 输出: 2023-12-01 06:50:00
// 添加时间
dt.addTime("PT1M"); // PT1M 表示增加 1 分钟
dt.printDateTime(); // 输出: 2023-12-01 06:51:00
// 减少时间
dt.subtractTime("PT1M"); // PT1M 表示减少 1 分钟
dt.printDateTime(); // 输出: 2023-12-01 06:50:00
// 获取日期时间字符串
var dateTimeStr = dt.toString();
print(dateTimeStr); // 输出: 2023-12-01 06:50:00
// 获取日期字符串
var dateStr = dt.toDateString();
print(dateStr); // 输出: 2023-12-01
// 获取时间字符串
var timeStr = dt.toTimeString();
print(timeStr); // 输出: 06:50:00
// 打印日期字符串
dt.printDate(); // 输出: 2023-12-01
// 打印时间字符串
dt.printTime(); // 输出: 06:50:00
// 获取时间戳
var stamp = dt.stamp;
print(stamp); // 输出: 时间戳
// 打印时间戳
dt.printStamp(); // 输出: 时间戳
// 运行基于指定时间字符串的回调函数
dt.run(["PT1M", "PT2M"], (timeStr) {
print("Current time is $timeStr");
});
}
更多关于Flutter多功能工具插件the_utils的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter多功能工具插件the_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,关于Flutter多功能工具插件the_utils
的使用,下面是一个具体的代码案例,展示了如何使用该插件中的几个常用功能。请注意,the_utils
是一个假设的插件名称,实际使用时你可能需要替换为具体的插件名称及其功能。不过,为了说明,我会假设这个插件包含一些常见的工具类功能,比如字符串处理、日期处理和网络请求等。
首先,确保在pubspec.yaml
文件中添加了the_utils
插件的依赖:
dependencies:
flutter:
sdk: flutter
the_utils: ^latest_version # 替换为实际的最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,是一个简单的Flutter应用示例,展示了如何使用the_utils
插件的功能:
import 'package:flutter/material.dart';
import 'package:the_utils/the_utils.dart'; // 假设这是插件的导入路径
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter the_utils Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String formattedDate = '';
String reversedString = '';
String networkData = '';
@override
void initState() {
super.initState();
// 使用日期工具类获取当前日期并格式化
formattedDate = TheUtils.date.formatCurrentDate('yyyy-MM-dd HH:mm:ss');
// 使用字符串工具类反转字符串
String originalString = 'Hello, Flutter!';
reversedString = TheUtils.string.reverse(originalString);
// 使用网络工具类发起网络请求
_fetchNetworkData();
}
Future<void> _fetchNetworkData() async {
try {
String response = await TheUtils.network.get('https://api.example.com/data');
setState(() {
networkData = response;
});
} catch (e) {
setState(() {
networkData = 'Error: ${e.message}';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('the_utils Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Formatted Date:', style: TextStyle(fontSize: 18)),
Text(formattedDate, style: TextStyle(fontSize: 16)),
SizedBox(height: 16),
Text('Reversed String:', style: TextStyle(fontSize: 18)),
Text(reversedString, style: TextStyle(fontSize: 16)),
SizedBox(height: 16),
Text('Network Data:', style: TextStyle(fontSize: 18)),
Text(networkData, style: TextStyle(fontSize: 16)),
],
),
),
);
}
}
在这个示例中,我们做了以下几件事:
- 在
pubspec.yaml
中添加了the_utils
依赖。 - 在
MyApp
的home
属性中设置了MyHomePage
。 - 在
MyHomePage
的initState
方法中,使用the_utils
插件的日期工具类格式化当前日期,使用字符串工具类反转一个字符串,并使用网络工具类发起一个GET请求。 - 在
build
方法中,显示了格式化后的日期、反转后的字符串和网络请求返回的数据。
请注意,上述代码中的TheUtils.date.formatCurrentDate
、TheUtils.string.reverse
和TheUtils.network.get
是假设的方法,实际使用时你需要参考the_utils
插件的文档来确定正确的调用方式。如果the_utils
插件不存在,你可以寻找类似的Flutter工具插件,并根据其文档进行相应修改。