flutter_helper_kit 1.0.4
flutter_helper_kit: ^1.0.4 copied to clipboard
flutter_helper_kit helps to improve less code extensions and widgets.
Installation #
Add this package to pubspec.yaml
as follows:
$ flutter pub add flutter_helper_kit
copied to clipboard
Import package
import 'package:flutter_helper_kit/flutter_helper_kit.dart';
copied to clipboard
Contents #
Useful methods or extensions you will ever need #
/// Toast
AppButton(
onTap: () {
//The `FlutterToast` widget allows you to display customizable toast messages in your Flutter application.
FlutterToast.show('Flutter Helper Kit', context, position: FlutterToastPosition.bottom, duration: 500.milliseconds);
},
text: 'click'
),
copied to clipboard
Widgets #
///FlutterTag is a highly customizable widget designed for tags, close icons, and notifications.
///You can easily integrate it into your app with various options for styling, positioning, and animation.
FlutterTag(
tagContent: Icon(Icons.ac_unit),
tagStyle: FlutterTagStyle(
tagColor: Colors.blue,
borderRadius: 0.circularSharpBorderRadius,
shape: FlutterTagShape.circle,
),
tagAnimation: FlutterTagAnimation.fade(
animationDuration: Duration(milliseconds: 1500),
colorChangeAnimationCurve: Curves.decelerate,
curve: Curves.ease,
toAnimate: true,
),
position: FlutterTagPosition.topEnd(),
showTag: true,
child: Icon(Icons.add_shopping_cart, size: 40),
onTap: () {},
)
copied to clipboard
///SharpRectangleBorder provides a way to create sharp, defined corners on your Flutter widgets.
///This is particularly useful for achieving a more modern or geometric design style where precise corner sharpness is desired.
/// Example 1
SharpClipRect(
radius: SharpBorderRadius(
cornerRadius: 10,
sharpRatio: 1,
),
child: Container(
color: Colors.red,
width: 100,
height: 100,
alignment: Alignment.center,
),
)
/// Example 2
Container(
height: 100,
width: 100,
alignment: Alignment.center,
decoration: ShapeDecoration(
color: Colors.red,
shape: SharpRectangleBorder(
borderRadius: SharpBorderRadius(
cornerRadius: 10,
sharpRatio: 1,
),
),
),
)
copied to clipboard
///TapSafeGesture is a StatefulWidget that manages rapid, repeated taps on a widget, ensuring only a single tap is processed at a time with an optional cooldown period.
///This is perfect for preventing multiple executions of asynchronous operations triggered by button presses.
TapSafeGesture(
builder: (context, onTap) {
return ElevatedButton(
onPressed: onTap,
child: Text('Tap Me'),
);
},
waitBuilder: (context, child) {
return Stack(
alignment: Alignment.center,
children: [
child,
CircularProgressIndicator(),
],
);
},
onTap: () async {
// Perform your async operation here
await Future.delayed(Duration(seconds: 2));
},
cooldown: Duration(seconds: 2),
)
copied to clipboard
/// Add a Google Logo
/// Add size parameter for custom size - Default is 24
GoogleLogoWidget()
copied to clipboard
///without using Expanded or ListView, and ensuring compatibility with the code structure you provided, you can utilize SingleChildScrollView along with Column or Row based on the scrollDirection.
/// This widget is designed to provide a customizable list view with optional item separators,
/// allowing developers to build lists in both horizontal and vertical directions.
FlutterListView(
items: myItems,
itemBuilder: (context, item) {
return ListTile(title: Text(item.title));
},
separatorBuilder: (context, index) {
return Divider();
},
padding: EdgeInsets.all(16.0),
scrollDirection: FlutterScrollDirection.vertical,
)
copied to clipboard
AvatarGlow(
glowColor: Colors.cyan,
glowCount: 5,
startDelay: 2.seconds,
glowRadiusFactor: 2,
child: GoogleLogoWidget(),
),
copied to clipboard
OutlineAvatarGlow(
glowColor: Colors.cyan,
glowCount: 5,
startDelay: 2.seconds,
glowRadiusFactor: 2,
child: GoogleLogoWidget(),
),
copied to clipboard
AvatarGlowMultiColor (
glowColors: [Colors.red,Colors.blue,Colors.red,Colors.green,Colors.yellow,],
startDelay: 2.seconds,
glowRadiusFactor: 2,
child: GoogleLogoWidget(),
),
copied to clipboard
OutlineAvatarGlowMultiColor (
glowColors: [Colors.red,Colors.blue,Colors.red,Colors.green,Colors.yellow,],
startDelay: 2.seconds,
glowRadiusFactor: 2,
child: GoogleLogoWidget(),
),
copied to clipboard
/// add a 'Space' inside a 'Column' or a 'Row' with the specified extent.
/// The 'MaxSpace' widget will try to fill the available space in a 'Column' or a Row 'with' the specified size. If the available space is lesser than the specified size, the MaxSpace widget will only take the available space.
Column(
children: <Widget>[
Container(color: Colors.red, height: 20),
const Gap(20), // Adds an empty space of 20 pixels.
Container(color: Colors.red, height: 20),
],
);
/// There is also a Sliver version of the `Space` widget:
CustomScrollView(
slivers: <Widget>[
const SliverGap(20), // Adds an empty space of 20 pixels.
],
);
copied to clipboard
AppButton(
onTap: () {},
text: 'Flutter Helper Kit',
shapeBorder: RoundedRectangleBorder(borderRadius: 16.circularBorderRadius),
color: Colors.blue,
textStyle: TextStyle(fontSize: 28),enabled: false,
)
copied to clipboard
CustomIndicator(
isActive: true, //A boolean value that determines whether the overlay indicator is shown. If set to true, the overlay indicator is displayed.
opacity: 0.6, //The value should be between 0.0 and 1.0, where 0.0 is fully transparent and 1.0 is fully opaque. In the example above, it is set to 0.6.
bgColor: Colors.grey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Screen1')
],
),
)
copied to clipboard
The DashDivider
widget creates a dashed line divider in your Flutter application. It is customizable, allowing you to set the color, thickness, dash length, and gap length.
DashDivider()
copied to clipboard
DoublePressBackWidget(
message: 'Press back again to exit', // Optional
onWillPop: () {
print('Double press confirmed');
},
child: AnyWidget
),
copied to clipboard
//The `UnFocusable` widget is a simple utility that helps to unfocus text fields or other focusable widgets when a user taps outside of them. This is particularly useful for dismissing the keyboard when a user taps outside a `TextField`.
UnFocusable(
child: Scaffold(),
),
copied to clipboard
// The `Marquee` widget allows you to display its child in a scrolling manner, either horizontally or vertically. This widget is useful for creating scrolling text effects, such as news tickers or any other scrolling content.
// - Scrolls its child widget horizontally or vertically.
// - Supports continuous scrolling in one or two directions.
// - Customizable animation durations and pause durations.
// - Handles text direction for internationalization.
Marquee(
child: Text(
'Flutter Helper Kit example using the Marquee widget.',
style: TextStyle(fontSize: 24),
),
direction: Axis.horizontal,
textDirection: TextDirection.ltr,
animationDuration: Duration(milliseconds: 3000),
backDuration: Duration(milliseconds: 2000),
pauseDuration: Duration(milliseconds: 1000),
directionMarguee: DirectionMarguee.twoDirection,
)
copied to clipboard
//The `RatingBarWidget` is a customizable rating bar widget for Flutter. It allows users to select a rating by tapping on icons. The widget supports half ratings, customizable icons, colors, and spacing between icons.
RatingBarWidget(
rating: 3.5,
onRatingChanged: (newRating) {
print('Rating changed: $newRating');
},
activeColor: Colors.yellow,
inActiveColor: Colors.grey,
size: 40,
allowHalfRating: true,
filledIconData: Icons.star,
halfFilledIconData: Icons.star_half,
defaultIconData: Icons.star_border,
spacing: 4.0,
disable: false,
)
copied to clipboard
//The `ReadMoreText` widget allows you to display a portion of a long text and provide a "read more" link to expand the text. You can also collapse the text back with a "read less" link.
ReadMoreText(
'This is a very long text that needs to be trimmed.\nClick on the "read more" link to see the full text.\nClick on the "read less" link to collapse the text.',
trimLines: 2,
trimMode: TrimMode.line,
trimCollapsedText: '...read more',
trimExpandedText: ' read less',
style: TextStyle(color: Colors.black),
colorClickableText: Colors.blue,
textAlign: TextAlign.start,
),
copied to clipboard
RoundedCheckBox(
isChecked: true,
borderColor: Colors.grey,
onTap: (isChecked) {
print('Checkbox is now: $isChecked');
},
text: 'Accept Terms',
),
copied to clipboard
// To use the `SeparatedColumn` widget, simply wrap your children widgets with `SeparatedColumn` and provide a `separatorBuilder` to create the separators between the children.
SeparatedColumn(
separatorBuilder: (BuildContext context, int index) => Container(height: 1, color: Colors.grey),
children: const [
Text('Item 1'),
Text('Item 2'),
Text('Item 3'),
],
)
copied to clipboard
//To use the `TextAvatar` widget, simply create an instance of it and provide the required parameters.
TextAvatar(
text: 'Flutter Helper Kit',
)
copied to clipboard
TextIcon(
text: 'Hello World',
textStyle: TextStyle(color: Colors.blue, fontSize: 18),
prefix: Icon(Icons.star, color: Colors.yellow),
suffix: Icon(Icons.arrow_forward, color: Colors.red),
spacing: 8,
maxLine: 1,
onTap: () {
print('TextIcon tapped!');
},
edgeInsets: EdgeInsets.all(10),
expandedText: true,
useMarquee: false,
boxDecoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8),
),
)
copied to clipboard
// The `TimerBuilder` widget in Flutter allows you to rebuild your widget tree on specific and/or periodic timer events. It's highly customizable and can be used to create widgets that update at certain intervals or on a schedule.
//The example below shows how to use `TimerBuilder.periodic` to rebuild a widget every 5 seconds:
TimerBuilder.periodic(
Duration(seconds: 5),
builder: (context) {
return Text(
'Current Time: ${DateTime.now()}',
style: TextStyle(fontSize: 20),
);
},
)
//The example below shows how to use TimerBuilder.scheduled to rebuild a widget at specific times:
TimerBuilder.scheduled(
[
DateTime.now().add(Duration(seconds: 10)),
DateTime.now().add(Duration(seconds: 20)),
DateTime.now().add(Duration(seconds: 30)),
],
builder: (context) {
return Text(
'Current Time: ${DateTime.now()}',
style: TextStyle(fontSize: 20),
);
},
),
copied to clipboard
//A new list of widgets where the divider is inserted between each pair of adjacent widgets in the input list.
List<Widget> interspersedItems = WidgetHelper.intersperse(
items,
Divider(color: Colors.black),
leading: true,
trailing: true,
);
//A new list of widgets where each object in the input list is mapped to a list of widgets using the provided mapping function.
List<Widget> mappedWidgets = WidgetHelper.widgetMap(
items, (item) => [
Text(item),
SizedBox(height: 10)
],
);
copied to clipboard
Extensions #
String Extensions #
bool get isNotEmptyOrNull
num? get toNumber
bool get isDateTime
DateTime? get toDateTime
bool get isDouble
double? get toDouble
int get toLength
bool get validatePhone
bool get validatePhoneWithCountryCode
bool get isValidateEmail
bool get isContainsAlphabetLetter
bool get isAlphabetOnly
String get removeAllWhiteSpace
String get reversed
bool get validateURL
String get capitalizeFirstCharacter
String get capitalizeEachWordFirstCharacter
bool get isJsonDecodable
int get countWords
String validate([String value = ""])
bool startsWithCharacters(String characters,{bool matchCase = false})
String lastChars(int n)
String toWordsFirstCharacters({int? numberOfCharacters, String splitBy = "\\s+"})
String take(int numberOfCharacters)
bool isPasswordValidator({int minLength = 6,int uppercaseCharCount = 0,int lowercaseCharCount = 0,int numericCharCount = 0,int specialCharCount = 0})
copied to clipboard
Bool Extensions #
bool validate({bool value = false})
bool get isTrue
bool get isFalse
bool get isNotTrue
bool get isNotFalse
int get toInt
bool get toggle
copied to clipboard
Color Extensions #
String toHex({bool leadingHashSign = true, bool includeAlpha = false})
MaterialColor createMaterialColor()
Color lighten([double amount = .1])
Color darken([double amount = .1])
bool get isDark
bool get isLight
double get getBrightness
double get getLuminance
copied to clipboard
Build Context Extensions #
void requestFocus(FocusNode focus)
void unFocus(FocusNode focus)
void unFocusKeyboard()
void pop<T extends Object>([T? result])
void openDrawer()
void openEndDrawer()
void hideCurrentSnackBar()
void removeCurrentSnackBar()
void clearSnackBars()
void showSnackBar()
Size get size
double get width
double get height
double get pixelRatio
double get minScreenSize
double get maxScreenSize
Brightness get platformBrightness
double get statusBarHeight
double get navigationBarHeight
ThemeData get theme
TextTheme get textTheme
DefaultTextStyle get defaultTextStyle
FormState? get formState
ScaffoldState get scaffoldState
OverlayState? get overlayState
Color get primaryColor
Color get secondaryColor
Color get accentColor
Color get scaffoldBackgroundColor
Color get cardColor
Color get dividerColor
Color get iconColor
dynamic get getArguments
Orientation get orientation
bool get isLandscape
bool get isPortrait
bool get canPop
TargetPlatform get platform
bool get isAndroid
bool get isIOS
bool get isMacOS
bool get isWindows
bool get isFuchsia
bool get isLinux
copied to clipboard
DateTime Extensions - Utils #
/// You can use .timeAgo on a DateTime object like this
String result = DateTime.now().timeAgo;
/// Returns the current timestamp in seconds.
int get currentTimeStamp
/// Returns the number between the current DateTime instance and [differenceDateTime].
int countSeconds(DateTime? differenceDateTime)
int countMinutes(DateTime? differenceDateTime)
int countHours(DateTime? differenceDateTime)
int countDays(DateTime? differenceDateTime)
int countWeeks(DateTime? differenceDateTime)
int countMonths(DateTime? differenceDateTime)
int countYears(DateTime? differenceDateTime)
bool get isToday
bool get isYesterday
bool get isTomorrow
String? get toTimeAmPm
DateTime? toIndiaTimeZone()
/// Returns a DateTime object in UTC timezone.
DateTime? get asUtc
String? weekdayName({bool isHalfName = false})
String? monthName({bool isHalfName = false})
copied to clipboard
/// 📅 DateTime Format Extension
/// Format `DateTime` easily using custom patterns.
void printTest() {
DateTime now = DateTime.now();
print(now.format(pattern: 'd MMMM, yyyy at h:mm a')); // Output: "7 February, 2025 at 5:54 PM"
print(now.format('yyyy-MM-dd')); // Output: 2024-02-07
print(now.format('dd MMM yyyy')); // Output: 07 Feb 2024
print(now.format('EEEE, MMM d, y')); // Output: Wednesday, Feb 7, 2024
print(now.format('hh:mm a')); // Output: 10:30 AM
print(now.format('HH:mm:ss')); // Output: 10:30:45
print(now.format('hh:mm:ss a')); // Output: 10:30:45 AM
print(now.format('yyyy-MM-dd HH:mm:ss')); // Output: 2024-02-07 10:30:45
print(now.format('EEE, d MMM yyyy hh:mm a')); // Output: Wed, 7 Feb 2024 10:30 AM
print(now.format('MMMM d, y')); // Output: February 7, 2024
print(now.format('MM/dd/yyyy')); // Output: 02/07/2024
print(now.format('dd-MM-yyyy HH:mm')); // Output: 07-02-2024 10:30
DateTime pastDate = now.subtract(Duration(days: 3));
print(pastDate.format('EEE, d MMM y')); // Output: Sun, 4 Feb 2024
DateTime futureDate = now.add(Duration(days: 7));
print(futureDate.format('EEE, d MMM y')); // Output: Wed, 14 Feb 2024
}
copied to clipboard
Double Extensions #
double validate({double value = 0.0})
bool isBetween(num first, num second)
SizedBox get squareSizeBox
Size get squareSize
/// Returns a [BorderRadius] with circular radius.
BorderRadius get circularRadius
copied to clipboard
Duration Extensions #
/// await Duration(seconds: 1).delay();
Future<void> get delay
copied to clipboard
int Extensions #
bool get isEmptyOrNull
Widget get height
Widget get width
Widget get space
Widget get maxSpace
Widget get spaceExpand
Duration get microseconds
Duration get milliseconds
Duration get seconds
Duration get minutes
Duration get hours
Duration get days
Duration get weeks
Duration get month
Duration get years
Size get size
BorderRadius get circularBorderRadius
String? get addZeroPrefix
bool toBool([int value = 1])
int validate({int value = 0})
int lastDigits(int n)
/// returns month name from the given int value between [1-12]
String toMonthName({bool isHalfName = false})
/// returns WeekDay from the given int value [1-7]
String toWeekDay({bool isHalfName = false})
copied to clipboard
List Extensions #
T? get firstOrNull
List<T> get removeFirstElement
List<T> get removeLastElement
int? get lastIndex
T? tryGet(int index)
T? firstWhereOrNull(bool Function(T element) test)
T? lastWhereOrNull(bool Function(T element) test)
int countWhere(bool Function(T element) predicate)
T? elementAtOrNull(int index)
Iterable<T> filterOrNewList(bool Function(T e) fun)
Iterable<T> filterNot(bool Function(T element) fun)
List<Widget> toWidgetList(Widget Function(T value) mapFunc)
int countWhere(bool Function(T) test)
void forEachIndexed(void Function( int index,T element) f)
T? random({int? seed})
List<T> separatorEvery(T separator,{bool start= false,bool end=false})
List<List<T>> divideListByFunction(bool Function(T) condition)
List<List<T>>? divideListByRange(int rangeSize)
copied to clipboard
num Extensions #
bool get isNullOrEmpty
num validate({num value = 0})
bool between(int min, int max)
bool isInRange(num min, num max)
List<num> randomList({int min = 0, int max = 100})
String toNumeral({bool international = true, int digitAfterDecimal = 0})
///SharpBorderRadius
SharpBorderRadius get circularSharpBorderRadius
SharpBorderRadius get topLeftSharpBorderRadius
SharpBorderRadius get topRightSharpBorderRadius
SharpBorderRadius get bottomLeftSharpBorderRadius
SharpBorderRadius get bottomRightSharpRadius
SharpRadius get sharpRadius
copied to clipboard
ScopeFunction Extensions #
int number = 5;
String result = number.let((it) => 'Number is $it');
print(result); // Output: Number is 5
var person = Person('John').also((it) => it.name = 'Doe');
print(person.name); // Output: Doe
var result = 'Hello'.run(() => 'Hello World');
print(result); // Output: Hello World
var list = [1, 2, 3].apply(() => print('List has ${list.length} elements')); // Output: List has 3 elements
int? number = 5.takeIf((it) => it > 3);
print(number); // Output: 5
number = 5.takeIf((it) => it > 6);
print(number); // Output: null
int? number = 5.takeUnless((it) => it > 6);
print(number); // Output: 5
number = 5.takeUnless((it) => it > 3);
print(number); // Output: null
copied to clipboard
Systems Methods #
/// Change status bar Color and Brightness
setStatusBarColor(Colors.blue);
setDarkStatusBar();
setLightStatusBar();
/// Show Status Bar
showStatusBar();
/// Hide Status Bar
hideStatusBar();
/// Set orientation to portrait
setOrientationPortrait();
/// Set orientation to landscape
setOrientationLandscape();
copied to clipboard
Utils #
///Display a customizable dialog with a close icon in your Flutter app.
///This example shows how to create an upload dialog with a slide animation for the close button, custom styling, and sharp rounded corners.
showDialogWithCloseIcon(
context: context,
title: const Icon(Icons.image, size: 40),
content: Column(children: [
const Text('Upload your profile Picture.'),
20.height,
OutlinedButton(onPressed: () {}, child: const Text('Upload'))]),
closeButtonPosition: FlutterTagPosition.topEnd(),
closeButtonAnimation: const FlutterTagAnimation.slide(),
closeButtonStyle: FlutterTagStyle(borderRadius: 1000.circularSharpBorderRadius, shape: FlutterTagShape.circle),
shape: SharpRectangleBorder(borderRadius: 16.circularSharpBorderRadius),
closeIcon: const Icon(Icons.clear,color: Colors.white),
dialogColor: Colors.white,
);
copied to clipboard
showDialogWithCloseIcon
void printTest(){
DateTime pastDate = DateTime.now().subtract(Duration(hours: 2, minutes: 30));
print('English: ${timeAgoCalculated(pastDate)}'); //output: 3 hours ago
print('Hindi: ${timeAgoCalculated(pastDate, inHindi: true)}'); //output: Hindi: 3 घंटे पूर्व
}
copied to clipboard
hasMatch(testString, pattern)
copied to clipboard
String randomString({int? length, bool includeNumeric = true})
copied to clipboard
Numeral #
//The Numeral class provides methods to format numbers based on the chosen numeral system.
Numeral numeral = Numeral(1234567.89);
String indianFormatted = numeral.indian; // Output: 12.34 L
String internationalFormatted = numeral.international; // Output: 1.23 M
copied to clipboard
Validator #
Validator.hasMinimumLength(String password, int minLength)
Validator.hasMinimumUppercase(String password, int uppercaseCount)
Validator.hasMinimumLowercase(String password, int lowercaseCount)
Validator.hasMinimumNumericCharacters(String password, int numericCount)
Validator.hasMinimumSpecialCharacters(String password, int specialCharactersCount)
copied to clipboard
Random Image #
// Example: Get a random image URL with custom dimensions (300x400) from Picsum
Image.network(RandomImage.picsumImage(300, 400)),
// Example: Get a random image URL from Robohash with custom parameters
Image.network(
RandomImage.randomImage(
slug: 'example-slug',
size: Size(400, 400),
set: ImageSet.set1,
bg: ImageBg.bg1,
imageType: ImageType.jpg,
color: ImageColor.blue)
),
// Example: Get a random image URL from DummyImage with custom parameters
Image.network(
RandomImage.dummyImage(
text: 'Hello World',
size: Size(300, 300),
imageType: ImageType.png,
bgColor: Colors.red,
fgColor: Colors.white)
),
copied to clipboard
degreeToRadian(45); //// Output: 0.7853981633974483
// Delay execution for 500 milliseconds and return a value.
String result = await wait<String>(500, () => 'Delayed value');
//This method loads bytes from the specified asset path.
Future<Uint8List> getBytesFromAsset(String path, {int? width})
//This method checks the network connection by attempting to lookup 'google.com'.
bool isConnected = await checkConnection();
copied to clipboard
Typedefs for Callback Functions #
FutureVoidCallback // Future<void> Function();
FutureDynamicCallback // Future<dynamic> Function();
FutureIntCallback // Future<int> Function();
FutureStringCallback // Future<String> Function();
FutureDoubleCallback // Future<double> Function();
DynamicCallback // dynamic Function();
IntCallback // int Function();
StringCallback // String Function();
DoubleCallback // double Function();
StringArgVoidCallback // void Function(String arg);
IntArgVoidCallback // void Function(int arg);
DoubleArgVoidCallback // void Function(double arg);
copied to clipboard
Image Previews #
Flutter Toast #

Tap Safe Gesture #

Avatar Glow #

Outline Avatar Glow #

Avatar Glow MultiColor #

Outline Avatar Glow MultiColor #

App Button #

Marquee #

RatingBar #

Read More Text #

Rounded Check Box #

Text Icon #

showDialogWithCloseIcon #

Sharp Borders #

Flutter Tag #

Features and bugs #
Please file feature requests and bugs at the [issue tracker][tracker]. [tracker]: https://github.com/sachin4kmt/flutter_helper_kit/issues