Flutter实用工具插件flutter_easy_utility的使用
Flutter实用工具插件flutter_easy_utility的使用
本项目是一个用于Flutter插件包的起点。它提供了一组方法/扩展,使使用框架变得更加容易和干净,并增加了额外的功能,提供了构建项目所需的各种工具和部分。
功能
动态类型转换
可以轻松地将动态类型转换为字符串、整数或浮点数,并带有错误处理。
字符串操作与验证
验证手机号码和电子邮件地址,修剪字符串,格式化字符串为价格等。
TextEditingController 扩展
从 TextEditingController 获取修剪后的文本并检查其是否为空。
GapSizer
通过 SizedBox 简化添加水平和垂直间距。
文件工具
获取文件大小(以兆字节为单位)。
日志工具
记录消息和异常以便调试。
十六进制颜色
在十六进制字符串和 Color 对象之间进行转换。
安装
要使用此软件包,在 pubspec.yaml
文件中添加 flutter_easy_utility
作为依赖项。
dependencies:
flutter_easy_utility: ^1.0.0
然后运行 flutter pub get
来安装它。
使用
1. convertToString
- 将任何动态类型转换为字符串。
- 修剪字符串并返回。
- 如果发生错误,则记录错误并返回空字符串。
String strValue = " Abc ";
Text("Converted String to String: ${convertToString(strValue)}"),
Text("Converted String to Int: ${convertToInt(strValue)}"),
Text("Converted String to Double: ${convertToDouble(strValue)}"),
2. convertToInt
- 将任何动态类型转换为整数。
- 如果动态类型是字符串,则先将其解析为双精度浮点数,然后转换为整数并四舍五入。
- 如果发生错误,则记录错误并返回 0。
int iValue = 56;
Text("Converted Int to Int: ${convertToInt(iValue)}"),
Text("Converted Int to String: ${convertToString(iValue)}"),
Text("Converted Int to Double: ${convertToDouble(iValue)}"),
3. convertToDouble
- 将任何动态类型转换为双精度浮点数。
- 替换字符串表示形式中的逗号。
- 如果发生错误,则记录错误并返回 0.00。
double dValue = 9925.56;
Text("Converted Double to Double: ${convertToDouble(dValue)}"),
Text("Converted Double to String: ${convertToString(dValue)}"),
Text("Converted Double to Int: ${convertToInt(dValue)}"),
4. isValidMobileNumber
- 检查字符串是否包含有效的手机号码。
- 移除非数字字符并检查长度是否在 5 到 15 位之间且只包含数字。
final TextEditingController _mobileController = TextEditingController();
String _validationMessageForNumber = "";
TextField(
keyboardType: TextInputType.number,
controller: _mobileController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
labelText: "Enter mobile number",
),
),
ElevatedButton(
onPressed: () {
setState(() {
_validationMessageForNumber = _mobileController.text.isValidMobileNumber()
? "Valid mobile number"
: "Invalid mobile number";
});
},
child: const Text("Validate Mobile Number"),
),
Text("Mobile number validation: $_validationMessageForNumber"),// 输出: 验证手机号码的消息
5. isEmptyOrNull
- 检查字符串是否为空或在修剪空白后为 null。
String strValue = " Abc ";
Text("Check the message emptyOrNull: ${strValue.isEmptyOrNull()}"),
6. isNotEmptyAndNotNull
- 检查字符串是否既不为空也不为 null。
String strValue = " Abc ";
Text("Check the message isNotEmptyAndNotNull: ${strValue.isNotEmptyAndNotNull()}"),
7. trimString
- 从字符串中修剪空白。
- 如果原始字符串为 null 或字符串 “null”,则返回空字符串。
String strValue = " Abc ";
Text("Trim the String: ${strValue.trimString()}"),
8. convertToLowerCase
- 从字符串中修剪空白并将其转换为小写。
String strValue = " Abc ";
Text("Convert the message to lowerCase: ${strValue.convertToLowerCase()}"),
9. convertToPrice
- 从字符串中修剪空白并将其格式化为指定货币符号的价格。
String price = "2500";
Text("Convert to price: ${price.convertToPrice("₹")}"),
10. isValidEmail
- 使用正则表达式检查字符串是否为有效的电子邮件地址。
final TextEditingController _emailController = TextEditingController();
String _validationMessageForEmail = "";
TextField(
controller: _emailController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
labelText: "Enter email-id",
),
),
ElevatedButton(
onPressed: () {
setState(() {
_validationMessageForEmail = _emailController.text.isValidEmail()
? "Valid email-id"
: "Invalid email-id";
});
},
child: const Text("Validate Email-id"),
),
Text("Email-id validation: $_validationMessageForEmail"),// 输出: 验证电子邮件地址的消息
11. printLog
- 如果消息不为空,则将其记录到控制台。
printLog("This is a log message");
12. printExceptionLog
- 如果异常不为 null,则将其记录到控制台。
try {
throw Exception("An error occurred");
} catch (ex) {
printExceptionLog(ex);
}
13. getFileSize
- 计算文件大小(以兆字节为单位)。
- 读取文件字节,转换为千字节,然后转换为兆字节。
- 如果发生异常,则记录错误并返回 0。
File file = File('path/to/your/file.txt');
double fileSize = Utility().getFileSize(file);
print(fileSize); // 输出: 文件大小(MB)
14. GapSizer
heightGap
:- 创建一个高度等于数值的 SizedBox。
- 适用于在小部件之间添加垂直空间。
widthGap
:- 创建一个宽度等于数值的 SizedBox。
- 适用于在小部件之间添加水平空间。
Column(
children: [
Text("Hello Users"),
5.heightGap,
Row(
children: [
Text("Simple text1"),
5.widthGap,
Text("Simple text2"),
],
),
],
),
15. HexColor
fromHex
:- 从十六进制字符串创建一个 Color 对象。
- 字符串可以是 “aabbcc” 或 “ffaabbcc” 格式,可选前缀 “#”。
- 如果字符串为 6 个字符长,则假定完全不透明(ff)。
toHex
:- 将 Color 对象转换为十六进制字符串。
- 字符串将以 “#aabbcc” 或 “aabbcc” 的格式输出。
- 如果
leadingHashSign
参数设置为 true(默认值),则会在开头添加一个井号。
Container(
padding: const EdgeInsets.all(8),
color: HexColor.fromHex("#00ff00"),
child: const Text("Hex color"),
),
示例代码
以下是一个完整的示例代码,展示了如何使用 flutter_easy_utility
插件。
import "package:flutter/material.dart";
import "package:flutter_easy_utility/flutter_easy_utility.dart";
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: "Flutter Easy Utility Example",
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _mobileController = TextEditingController();
String strValue = " Abc ";
int iValue = 56;
double dValue = 9925.56;
String price = "2500";
String _validationMessageForNumber = "";
String _validationMessageForEmail = "";
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: const Text("Flutter Easy Utility Example"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
children: [
10.heightGap,
// 字符串值
Text("Converted String to String: ${convertToString(strValue)}"),
Text("Converted String to Int: ${convertToInt(strValue)}"),
Text("Converted String to Double: ${convertToDouble(strValue)}"),
20.heightGap,
// 整数值
Text("Converted Int to Int: ${convertToInt(iValue)}"),
Text("Converted Int to String: ${convertToString(iValue)}"),
Text("Converted Int to Double: ${convertToDouble(iValue)}"),
20.heightGap,
// 双精度浮点数值
Text("Converted Double to Double: ${convertToDouble(dValue)}"),
Text("Converted Double to String: ${convertToString(dValue)}"),
Text("Converted Double to Int: ${convertToInt(dValue)}"),
20.heightGap,
Text("Check the message emptyOrNull: ${strValue.isEmptyOrNull()}"),
Text("Check the message isNotEmptyAndNotNull: ${strValue.isNotEmptyAndNotNull()}"),
Text("Trim the String: ${strValue.trimString()}"),
Text("Convert the message to lowerCase: ${strValue.convertToLowerCase()}"),
Text("Convert to price: ${price.convertToPrice("₹")}"),
20.heightGap,
TextField(
controller: _emailController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
labelText: "Enter email-id",
),
),
5.heightGap,
ElevatedButton(
onPressed: () {
setState(() {
_validationMessageForEmail = _emailController.text.isValidEmail()
? "Valid email-id"
: "Invalid email-id";
});
},
child: const Text("Validate Email-id"),
),
5.heightGap,
Text("Email-id validation: $_validationMessageForEmail"),
20.heightGap,
TextField(
keyboardType: TextInputType.number,
controller: _mobileController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
labelText: "Enter mobile number",
),
),
5.heightGap,
ElevatedButton(
onPressed: () {
setState(() {
_validationMessageForNumber = _mobileController.text.isValidMobileNumber()
? "Valid mobile number"
: "Invalid mobile number";
});
},
child: const Text("Validate Mobile Number"),
),
5.heightGap,
Text("Mobile number validation: $_validationMessageForNumber"),
20.heightGap,
Container(
padding: const EdgeInsets.all(8),
color: HexColor.fromHex("#00ff00"),
child: const Text("Hex color"),
),
10.heightGap,
],
),
),
),
);
}
}
更多关于Flutter实用工具插件flutter_easy_utility的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter实用工具插件flutter_easy_utility的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_easy_utility
是一个实用的 Flutter 插件,旨在简化开发者在 Flutter 应用中的常见任务。它提供了一系列工具和功能,帮助开发者更高效地完成各种任务,如字符串处理、日期格式化、网络请求、设备信息获取等。
安装
首先,你需要在 pubspec.yaml
文件中添加 flutter_easy_utility
依赖:
dependencies:
flutter:
sdk: flutter
flutter_easy_utility: ^版本号
然后运行 flutter pub get
来安装依赖。
使用示例
以下是一些 flutter_easy_utility
插件的常见使用场景和示例:
1. 字符串处理
import 'package:flutter_easy_utility/flutter_easy_utility.dart';
void main() {
String str = "Hello, World!";
// 判断字符串是否为空
bool isEmpty = EasyString.isEmpty(str);
print(isEmpty); // false
// 字符串反转
String reversedStr = EasyString.reverse(str);
print(reversedStr); // "!dlroW ,olleH"
// 字符串截取
String subStr = EasyString.substring(str, start: 0, end: 5);
print(subStr); // "Hello"
}
2. 日期格式化
import 'package:flutter_easy_utility/flutter_easy_utility.dart';
void main() {
DateTime now = DateTime.now();
// 格式化日期
String formattedDate = EasyDate.format(now, pattern: "yyyy-MM-dd");
print(formattedDate); // "2023-10-05"
// 获取当前时间戳
int timestamp = EasyDate.timestamp();
print(timestamp); // 1696521600000
// 日期加减
DateTime futureDate = EasyDate.addDays(now, 10);
print(futureDate); // 2023-10-15
}
3. 网络请求
import 'package:flutter_easy_utility/flutter_easy_utility.dart';
void main() async {
// GET 请求
var response = await EasyHttp.get("https://jsonplaceholder.typicode.com/posts/1");
print(response.body);
// POST 请求
var postResponse = await EasyHttp.post(
"https://jsonplaceholder.typicode.com/posts",
body: {
"title": "foo",
"body": "bar",
"userId": 1,
},
);
print(postResponse.body);
}
4. 设备信息获取
import 'package:flutter_easy_utility/flutter_easy_utility.dart';
void main() async {
// 获取设备ID
String deviceId = await EasyDevice.getDeviceId();
print(deviceId);
// 获取设备型号
String deviceModel = await EasyDevice.getDeviceModel();
print(deviceModel);
// 获取系统版本
String osVersion = await EasyDevice.getOsVersion();
print(osVersion);
}
5. 其他实用工具
import 'package:flutter_easy_utility/flutter_easy_utility.dart';
void main() {
// 生成随机数
int randomNumber = EasyRandom.nextInt(min: 1, max: 100);
print(randomNumber);
// 生成随机字符串
String randomString = EasyRandom.nextString(length: 10);
print(randomString);
// 判断网络是否连接
bool isConnected = await EasyNetwork.isConnected();
print(isConnected);
}