Flutter多功能工具插件multiutillib的使用
Flutter多功能工具插件multiutillib的使用
multiutillib
是一个用于帮助处理实用工具、动画和一些预构建小部件的 Flutter 包。某些小部件具有默认值以便直接使用,并且可以根据您的需求进行自定义。
此包使用了以下依赖项:
intl
shimmer
device_info
url_launcher
package_info
simple_animations
connectivity_plus
loading_animation_widget
示例代码
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:multiutillib/multiutillib.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const MyHomePage(),
title: 'multiutillib Example',
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
MyHomePageState createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late final AnimationController _animationController;
final TextEditingController _textEditingController = TextEditingController();
String _isValid = '* Email Id is required.';
@override
void initState() {
super.initState();
_animationController = AnimationController(vsync: this, duration: const Duration(seconds: 1));
_animationController.forward();
_textEditingController.addListener(() {
final isEmailValid = emailValidator(_textEditingController.value.text);
if (isEmailValid != _isValid) {
setState(() => _isValid = isEmailValid!);
}
});
// _showProgressDialog();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
appBar: AppBar(title: const Text('Multi Util Lib')),
body: ConnectivityBuilder(
builder: (isOnline) {
return MaterialCard(
borderRadius: 15,
margin: const EdgeInsets.all(15),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
const SizedBox(height: 10),
CustomToggleButton(
textOn: 'On',
textOff: 'Off',
onChanged: (value) => debugPrint(value),
),
const SizedBox(height: 10),
FadeAnimation(
delay: 1.5,
child: Container(height: 100, color: Colors.black12, width: double.infinity),
),
const SizedBox(height: 10),
LoadingAnimationWidget.inkDrop(color: Colors.blue, size: 36),
const SizedBox(height: 10),
Text('Get Current Date: ${getCurrentDate()}'),
const SizedBox(height: 10),
Text(
'${'Get Current Date in $kDateDisplayFormat Format: \n'}${getCurrentDate(newDateTimeFormat: kDateDisplayFormat)}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'${'Get Current Date in $kFullMonthYearFormat Format: \n'}${getCurrentDate(newDateTimeFormat: kFullMonthYearFormat)}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'${'Get Current Date in $kFullDateDisplayFormat Format: \n'}${getCurrentDate(newDateTimeFormat: kFullDateDisplayFormat)}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'Format Date Time in dd-MM-yyyy format: \n${getCurrentDate().formatDateTime(newDateTimeFormat: 'dd-MM-yyyy')}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'Formatting Date Time Object in dd-MM-yyyy format: \n${DateTime.now().formatDateTime(newDateTimeFormat: 'dd-MM-yyyy HH:mm')}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'Convert to Date Time Object: \n${'2021-02-26 14:06:52.55'.toDateTime}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'Convert Time of Day to String: \n${TimeOfDay.now().formatTime()}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'Convert Time of Day String to String: \n${'14:39'.formatTime()}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'Convert Time String to Time of Day: \n${'14:39'.toTimeOfDay}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
'Convert DateTime to Time of Day: \n${DateTime.now().toTimeOfDay}',
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text(
"Convert DateTime to String: \n${DateTime.now().formatDateTime()}",
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
Text('Replace Null With Empty: ${"null".replaceNullWithEmpty}'),
const SizedBox(height: 10),
Text('Replace Null With Zero: ${"null".replaceNullWithZero}'),
const SizedBox(height: 10),
Text('Replace True or False: ${"true".replaceTrueOrFalse}'),
const SizedBox(height: 10),
Text('Replace Null with Double: ${"null".replaceNullWithDouble}'),
const SizedBox(height: 10),
Text('Format Number: ${"1010.869".formatNumber()}'),
const SizedBox(height: 10),
Text('Format Number to Compact: ${'88944444'.formatNumberToCompact}'),
const SizedBox(height: 10),
Text('Is Numeric: ${"1".isNumeric}'),
const SizedBox(height: 10),
Text('To Duration: ${'01:01:01'.toDuration}'),
const SizedBox(height: 10),
Text('From Duration: ${'16:35:34'.toDuration.toTimeString(newTimeString: 'mm:ss')}'),
const SizedBox(height: 10),
Text('To Two Digit: ${"9".toTwoDigits}'),
const SizedBox(height: 10),
Text('To Three Digit: ${"9".toThreeDigits}'),
const SizedBox(height: 10),
Text('To Length of String: ${'9'.toLengthOfString(5)}'),
const SizedBox(height: 10),
// [DecimalInputFormatter] will allow only entered decimal range for the string in text field
TextFormField(
inputFormatters: [DecimalInputFormatter(decimalRange: 2)],
decoration: const InputDecoration(labelText: 'Enter Decimal values'),
),
const SizedBox(height: 10),
TextFormField(
// this method will validate for email id
validator: emailValidator,
controller: _textEditingController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(errorText: _isValid, labelText: 'Enter Email Id'),
),
const SizedBox(height: 10),
FutureBuilder(
future: getDeviceName(),
builder: (context, snapshot) {
var formattedNumber = NumberFormat.compactCurrency(
symbol: '',
locale: 'en_IN',
decimalDigits: 2,
).format(100000);
debugPrint('Formatted Number is $formattedNumber');
debugPrint('snapshot data is: ${snapshot.data}');
if (snapshot.hasData) return Text(snapshot.data!);
return const SizedBox.shrink();
},
),
const SizedBox(height: 10),
FutureBuilder(
future: getDeviceId(),
builder: (context, snapshot) {
debugPrint('snapshot data is: ${snapshot.data}');
if (snapshot.hasData) return Text(snapshot.data!);
return const SizedBox.shrink();
},
),
const SizedBox(height: 10),
const HyperLinkText(url: 'http://www.google.com', text: 'Open Google'),
DefaultButton(
text: 'Show Date Range Picker',
margin: const EdgeInsets.only(top: 10),
onPressed: () {
showCustomDateRangePicker(
context: context,
onCancelClick: () {},
onApplyClick: (startDate, enDate) {},
);
},
),
DefaultButton(
text: 'Show Date Picker',
margin: const EdgeInsets.only(top: 10),
onPressed: () {
showCustomDatePicker(
context: context,
onCancelClick: () {},
onApplyClick: (selectedDate) {},
);
},
),
DefaultButton(
text: 'Show Custom Dialog',
margin: const EdgeInsets.only(top: 10),
onPressed: () {
showCustomDialog(
context,
title: 'Custom Dialog',
btnColor: Colors.green,
dialogAnimationType: DialogAnimationType.fromBottom,
description: 'This is a test to show custom dialog',
);
},
),
DefaultButton(
text: 'Show Confirmation Dialog',
margin: const EdgeInsets.only(top: 10),
onPressed: () {
showConfirmationDialog(
context,
dividerColor: Colors.black,
title: 'Confirmation Dialog',
positiveBtnColor: Colors.green,
negativeBtnColor: Colors.greenAccent,
onPositivePressed: () => Navigator.pop(context),
dialogAnimationType: DialogAnimationType.fromLeft,
description: 'This is a test to show confirmation dialog',
);
},
),
DefaultButton(
text: 'Show Progress Dialog',
margin: const EdgeInsets.only(top: 10),
onPressed: () async {
// calling show progress dialog method
await showProgressDialog(
context, /*progressWidget: const CircularProgressIndicator()*/
);
await Future.delayed(const Duration(seconds: 3));
await hideProgressDialog();
},
),
const SizedBox(height: 10),
const LoadingWidget(itemCount: 1),
OTPTextField(
autoFocus: false,
noOfOtpFields: 6,
onCompleted: (enteredOtp) => debugPrint('entered otp is: $enteredOtp'),
),
const SizedBox(height: 10),
const RichTextWidget(
caption: 'Rich',
description: 'Text',
captionStyle: TextStyle(fontSize: 20, color: Colors.black),
descriptionStyle: TextStyle(fontSize: 24, color: Colors.black),
),
],
),
),
);
},
),
);
}
@override
void dispose() {
_animationController.dispose();
_textEditingController.dispose();
super.dispose();
}
}
功能说明
FadeAnimation
FadeAnimation
将帮助子部件执行淡入淡出动画。
FadeAnimation(
delay: 1,
child: Container(),
),
SlideAnimation
SlideAnimation
将帮助子部件从顶部、左侧、右侧或底部方向执行滑动动画。
SlideAnimation(
child: child,
position: position,
itemCount: itemCount,
slideDirection: SlideDirection.fromRight,
animationController: animationController,
),
OffsetAnimation
OffsetAnimation
将帮助子部件执行偏移动画。
OffsetAnimation(
end: 20, // 可选参数
animationController: _animationController, // 必需参数
widget: YourChildWidget, // 必需参数
),
DateTimeUtils
DateTimeUtils
是一个帮助获取当前日期的实用类。
debugPrint('current date is: ${getCurrentDate()}');
Utils
Utils
是一个帮助获取设备名称、设备ID等信息的实用类。
1. getDeviceName() // 返回字符串Future
2. getDeviceId() // 返回字符串Future
3. getSingleDigitRandomNumber() // 返回单个随机数字
4. getRandomNumber(min: MinValue, max: MaxValue) // 返回在min和max值之间的随机数字
5. getRandomMobileNumber() // 返回随机生成的手机号码
6. getCharFromString(stringToExtract) // 返回传递字符串中的字符
7. getNumbersFromString(stringToExtract) // 返回传递字符串中的数字
8. getAppVersion() // 返回应用的当前版本
Extensions
扩展方法允许将一些实用方法用作扩展。
// 检查字符串、整数或双精度值是否为数字
'123'.isNumeric => 返回true
'String'.isNumeric => 返回false
// 检查字符串是否为空或空
strToCheck.isNullOrEmpty
// 去除字符串最后一个字符
stringToRemoveLastChat.trimLastChar
// 将字符串转换为两位数字
Text('To Two Digit: ${'9'.toTwoDigits}'),
// 将字符串转换为三位数字
Text('To Three Digit: ${'9'.toThreeDigits}'),
// 将字符串转换为固定长度
Text('To Length of String: ${'9'.toLengthOfString(5)}'),
// 格式化数字
Text('Format Number: ' + '1010.869'.formatNumber()),
Text('Format Number to Compact: ' + '88944444'.formatNumberToCompact), // 返回1K, 2k, 2M
Text('Replace Null With Empty: ' + 'null'.replaceNullWithEmpty),
Text('Replace True or False: ' + 'true'.replaceTrueOrFalse.toString()),
Text('Replace Null With Zero: ' + 'null'.replaceNullWithZero.toString()),
Text('Replace Null with Double: ' + 'null'.replaceNullWithDouble.toString()),
Text('Convert Duration to Time String: ' + '16:35:34'.toDuration.toTimeString(newTimeString: 'mm:ss')),
ShowConfirmationDialog
ShowConfirmationDialog
方法会显示一个确认对话框,包含两个按钮以请求确认。
showConfirmationDialog(
BuildContext context,
Widget transitionAnimation,
String negativeBtnText 'No',
String positiveBtnText: 'Yes',
bool barrierDismissible: false,
Color dividerColor: Colors.blue,
Color positiveBtnColor: Colors.blue,
Color negativeBtnColor: Colors.blueAccent,
TextAlign descTextAlign: TextAlign.center,
TextAlign titleTextAlign: TextAlign.center,
Duration transitionDuration: const Duration(milliseconds: 400),
DialogAnimationType dialogAnimationType: DialogAnimationType.grow,
TextStyle descStyle: const TextStyle(fontSize: 16, letterSpacing: 0.27, color: Colors.black),
TextStyle titleStyle: const TextStyle(fontSize: 18, letterSpacing: 0.27, fontWeight: FontWeight.bold),
TextStyle positiveBtnStyle: const TextStyle(fontSize: 18, letterSpacing: 0.27, fontWeight: FontWeight.w400),
TextStyle negativeBtnStyle: const TextStyle(fontSize: 18, letterSpacing: 0.27, fontWeight: FontWeight.w400),
required String title,
required String description,
required VoidCallback onPositivePressed,
);
ShowCustomDialog
ShowCustomDialog
方法会显示一个对话框,包含一个按钮以显示警告或信息。
showCustomDialog(
BuildContext context,
String btnText: 'OK',
Color btnColor: Colors.blue,
bool barrierDismissible: false,
Color dividerColor: Colors.blue,
TextAlign descTextAlign: TextAlign.center,
TextAlign titleTextAlign: TextAlign.center,
Duration transitionDuration: const Duration(milliseconds: 400),
DialogAnimationType dialogAnimationType: DialogAnimationType.grow,
TextStyle descStyle: const TextStyle(fontSize: 16, letterSpacing: 0.27, color: Colors.black),
TextStyle btnStyle: const TextStyle(fontSize: 18, letterSpacing: 0.27, fontWeight: FontWeight.w400),
TextStyle titleStyle: const TextStyle(fontSize: 18, letterSpacing: 0.27, fontWeight: FontWeight.bold),
required String title,
required String description,
);
CustomDateRangePicker
CustomDateRangePicker
类帮助显示自定义日期范围选择对话框。
showCustomDateRangePicker(
required BuildContext context,
required Function onCancelClick,
String applyButtonText: 'Apply',
String cancelButtonText: 'Cancel',
Color leftArrowColor: Colors.blue,
Color rightArrowColor: Colors.blue,
Color applyButtonColor: Colors.blue,
Color cancelButtonColor: Colors.red,
Color weekDaysTextColor: Colors.blue,
Color selectedRangeColor: Colors.blue,
Color monthYearTextColor: Colors.black,
required Function(DateTime startDate, DateTime endDate) onApplyClick,
TextStyle applyButtonTextStyle: const TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
TextStyle cancelButtonTextStyle: const TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
DateTime minimumDate,
DateTime maximumDate,
DateTime initialEndDate,
DateTime initialStartDate,
bool barrierDismissible: false,
);
CustomDatePicker
CustomDatePicker
类帮助显示自定义日期选择对话框。
showCustomDatePicker(
required BuildContext context,
required Function onCancelClick,
String applyButtonText: 'Apply',
String cancelButtonText: 'Cancel',
Color leftArrowColor: Colors.blue,
Color rightArrowColor: Colors.blue,
Color applyButtonColor: Colors.blue,
Color cancelButtonColor: Colors.red,
Color weekDaysTextColor: Colors.blue,
Color selectedDateColor: Colors.blue,
Color monthYearTextColor: Colors.black,
required Function(DateTime dateTime) onApplyClick,
TextStyle applyButtonTextStyle: const TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
TextStyle cancelButtonTextStyle: const TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
DateTime minimumDate,
DateTime maximumDate,
DateTime initialStartDate,
bool barrierDismissible: false,
);
ProgressDialog
ProgressDialog
类帮助显示和隐藏带有自定义加载小部件的进度对话框。
// 显示进度对话框
await showProgressDialog(context);
// 隐藏进度对话框
await hideProgressDialog();
ConnectivityBuilder
ConnectivityBuilder
是一个显示连接状态消息的小部件。
ConnectivityBuilder(
Key? key,
required builder,
gradient,
offlineWidget,
bgColor: Colors.red,
position: Position.bottom,
disableInteraction: false,
alignment: Alignment.center,
message: kInternetNotAvailable,
textStyle: const TextStyle(fontSize: 14, color: Colors.white),
),
DefaultButton
DefaultButton
是一个按钮小部件。
DefaultButton(
isEnabled: true,
isUpperCase: true,
margin: const EdgeInsets.only(top: 20),
required String text,
required Function onPressed,
),
HyperLinkText
HyperLinkText
是一个显示文本并点击时打开 URL 的小部件。
HyperLinkText(url: 'http://www.google.com', text: 'Open Google'),
LoadingWidget
LoadingWidget
会显示一个加载闪烁效果。
LoadingWidget(
itemCount: 6,
borderRadius: 12,
highlightColor: Colors.white,
baseColor: const Color(0xFFE0E0E0),
),
MaterialCard
MaterialCard
是一个有用的卡片视图小部件,可以直接使用或根据需要进行自定义。
MaterialCard(
required Widget child,
onTap,
borderRadius,
elevation: 4,
borderRadiusGeometry,
color: Colors.white,
padding: const EdgeInsets.all(12),
margin: const EdgeInsets.only(top: 12),
),
OTPTextField
OTPTextField
是一个用于输入 OTP 的小部件。
OTPTextField(
required int noOfOtpFields,
required ValueChanged<String> onCompleted,
borderWidth: 2,
isEnabled: true,
autoFocus: true,
autoCorrect: false,
borderColor: Colors.blue,
cursorColor: Colors.blue,
textAlign: TextAlign.center,
margin: const EdgeInsets.only(top: 20, left: 20, right: 20),
textStyle: const TextStyle(fontSize: 16, letterSpacing: 0.27, color: Colors.black),
),
RichTextWidget
RichTextWidget
是一个帮助显示标题和描述值的小部件。
RichTextWidget(
required String caption,
required String description,
isDescNewLine: false,
captionStyle: const TextStyle(fontSize: 14, color: Colors.black, fontWeight: FontWeight.normal),
descriptionStyle: const TextStyle(fontSize: 14, color: Colors.black, fontWeight: FontWeight.normal),
),
CustomToggleButton
CustomToggleButton
会显示带有文本的切换开关。
CustomToggleButton({
textOn,
textOff,
onChanged,
width: 200,
height: 45,
borderRadius: 50,
transitionTime: 300,
activeTextColor: Colors.black,
activeSwitchColor: Colors.white,
inactiveTextColor: Colors.white,
inactiveSwitchColor: Colors.blue,
});
DecimalInputFormatter
DecimalInputFormatter
是一个用于允许输入指定小数范围的 TextInputFormatter
。
TextFormField(
inputFormatters: [DecimalInputFormatter(decimalRange: 2)],
decoration: InputDecoration(labelText: 'Enter Decimal values'),
),
Validators
Validators
类包含用于验证字符串的方法。
TextFormField(
// 此方法将验证电子邮件地址
validator: emailValidator,
decoration: InputDecoration(labelText: 'Enter Email Id'),
),
更多关于Flutter多功能工具插件multiutillib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter多功能工具插件multiutillib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,我可以为你提供一个关于如何使用Flutter多功能工具插件 multi_utillib
的代码示例。首先,确保你已经在 pubspec.yaml
文件中添加了该依赖:
dependencies:
flutter:
sdk: flutter
multi_utillib: ^最新版本号 # 替换为实际最新版本号
然后,运行 flutter pub get
来获取依赖。
以下是一个简单的示例,展示了如何使用 multi_utillib
插件中的一些功能。假设 multi_utillib
提供了字符串处理、日期处理和加密解密等功能,以下代码分别展示了这些功能的用法:
import 'package:flutter/material.dart';
import 'package:multi_utillib/multi_utillib.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MultiUtilLib Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MultiUtilLibDemo(),
);
}
}
class MultiUtilLibDemo extends StatefulWidget {
@override
_MultiUtilLibDemoState createState() => _MultiUtilLibDemoState();
}
class _MultiUtilLibDemoState extends State<MultiUtilLibDemo> {
String? encryptedText;
String? decryptedText;
String formattedDate = '';
String reversedString = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('MultiUtilLib Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 字符串处理示例:反转字符串
TextField(
decoration: InputDecoration(labelText: 'Enter text to reverse'),
onChanged: (value) {
setState(() {
reversedString = value.split('').reversed.join('');
});
},
),
SizedBox(height: 16),
Text('Reversed Text: $reversedString'),
// 日期处理示例:格式化当前日期
SizedBox(height: 16),
Text('Formatted Date: ${formatDate(DateTime.now())}'),
// 加密解密示例
SizedBox(height: 16),
TextField(
decoration: InputDecoration(labelText: 'Enter text to encrypt'),
onEditingComplete: () {
setState(() {
encryptedText = encryptText(reversedString ?? '');
});
},
),
SizedBox(height: 16),
Text('Encrypted Text: $encryptedText'),
SizedBox(height: 16),
TextField(
decoration: InputDecoration(labelText: 'Enter encrypted text to decrypt'),
onEditingComplete: () {
setState(() {
decryptedText = decryptText(encryptedText ?? '');
});
},
),
SizedBox(height: 16),
Text('Decrypted Text: $decryptedText'),
],
),
),
);
}
// 假设multi_utillib提供了这些函数,实际使用时请参考文档
String formatDate(DateTime date) {
// 示例:格式化日期为 YYYY-MM-DD
return date.toIso8601String().split('T').first;
}
String encryptText(String text) {
// 示例:简单的Base64加密(实际应使用更安全的加密方法)
return base64Encode(utf8.encode(text));
}
String decryptText(String encryptedText) {
// 示例:简单的Base64解密
return utf8.decode(base64Decode(encryptedText));
}
}
注意:
- 上述代码中的
formatDate
,encryptText
, 和decryptText
函数是假设multi_utillib
提供了这些功能。实际使用中,你需要根据multi_utillib
的文档来调用相应的函数。 - Base64 加密并不是一种安全的加密方法,仅用于示例。实际应用中应使用更安全的加密方法。
- 确保你已经正确导入了
multi_utillib
插件,并且根据该插件的实际API进行了调用。
如果你需要更详细的功能实现,请参考 multi_utillib
的官方文档或示例代码。